bailian-cli-core 2.7.2 → 2.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +290 -13
- package/dist/index.mjs +62 -63
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,createWriteStream as r,existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,statSync as l,unlinkSync as u,writeFileSync as d}from"fs";import{homedir as f,tmpdir as p}from"os";import{basename as m,extname as h,join as g}from"path";import{parse as _,stringify as v}from"yaml";import{Dispatcher as y,fetch as ee,getGlobalDispatcher as b,setGlobalDispatcher as te}from"undici";import{createHash as ne,createHmac as re,randomBytes as ie,randomUUID as ae}from"crypto";import{Readable as oe}from"stream";import{createInterface as se}from"readline";import{pipeline as ce}from"stream/promises";import*as le from"yauzl";import{copyFileSync as ue,cpSync as de,createReadStream as fe,createWriteStream as pe,existsSync as x,lstatSync as me,mkdirSync as he,readFileSync as ge,readdirSync as _e,readlinkSync as ve,realpathSync as ye,renameSync as S,rmSync as C,statSync as be,symlinkSync as xe,writeFileSync as Se}from"node:fs";import{isIP as Ce}from"node:net";import{Readable as we}from"node:stream";import{basename as Te,dirname as Ee,isAbsolute as De,join as w,relative as Oe,resolve as ke,sep as Ae}from"node:path";import{parse as je}from"csv-parse";import{stringify as Me}from"csv-stringify/sync";import{link as Ne,mkdir as Pe,open as Fe,readFile as Ie,rename as Le,unlink as Re}from"node:fs/promises";import{createHash as ze,randomUUID as Be}from"node:crypto";import{setTimeout as Ve}from"node:timers/promises";import{createInterface as He}from"node:readline/promises";import{homedir as Ue}from"node:os";import{pipeline as We}from"node:stream/promises";import{createBrotliDecompress as Ge}from"node:zlib";import Ke from"tar-stream";var qe=Object.create,Je=Object.defineProperty,Ye=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyNames,Ze=Object.getPrototypeOf,Qe=Object.prototype.hasOwnProperty,T=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),$e=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Qe.call(e,s)&&s!==n&&Je(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ye(t,s))||r.enumerable});return e},et=(e,t,n)=>(n=e==null?{}:qe(Ze(e)),$e(t||!e||!e.__esModule||!Qe.call(e,`default`)?Je(n,`default`,{value:e,enumerable:!0}):n,e)),tt=/* @__PURE__ */ e(import.meta.url);const E={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10,INTERRUPTED:130};var D=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=E.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api,this.rawResponse=r?.rawResponse}toJSON(){let e=rt(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}},nt=class extends D{constructor(e,t){super(e,E.USAGE,t),this.name=`UsageError`}};function rt(e){if(e!=null){if(e instanceof Error){let t={message:e.message},n=e.code;return n&&(t.code=n),t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return{message:String(e)};try{return{message:JSON.stringify(e)}}catch{return}}}function it(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.error?.code??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new D(r,E.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id??t.requestID}})}function at(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw ot(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw ot(e);return n.origin}function ot(e){return new D(`Invalid model base URL "${e}".`,E.USAGE,`Use an absolute http(s) URL.`)}const st={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},ct={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},lt=`https://bailian.cn-beijing.aliyuncs.com`,ut=[`en-US`,`zh-CN`],dt=`en-US`,ft=[`language`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],pt=/* @__PURE__ */ new Set([`text`,`json`]),mt=/* @__PURE__ */ new Set([`domestic`,`international`]),ht=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function gt(e){return ht.test(e)}function _t(e){if(e===void 0)return;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)return[];let e=n.trim();if(!gt(e))return[];t.includes(e)||t.push(e)}return t}function vt(e){try{return at(e)}catch{return}}function yt(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&ut.includes(t.language)&&(n.language=t.language),typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.security_token==`string`&&t.security_token.length>0&&(n.security_token=t.security_token),typeof t.base_url==`string`){let e=vt(t.base_url);e&&(n.base_url=e)}typeof t.output==`string`&&pt.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.watermark==`boolean`&&(n.watermark=t.watermark),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_speech_recognition_model==`string`&&t.default_speech_recognition_model.length>0&&(n.default_speech_recognition_model=t.default_speech_recognition_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model);let r=_t(t.api_key_capabilities);return r!==void 0&&(n.api_key_capabilities=r),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&&mt.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function bt(e){if(e.flags.apiKey)return`flag`;if(e.env.DASHSCOPE_API_KEY?.trim())return`env`;if(e.file.api_key)return`config`}function xt(e){if(e.flags.baseUrl)return`flag`;if(e.env.DASHSCOPE_BASE_URL?.trim())return`env`;if(e.file.base_url)return`config`}function St(e){return{apiKeySource:bt(e),baseUrlSource:xt(e)}}function Ct(e){let{apiKeySource:t,baseUrlSource:n}=e;return!!(t&&n&&t!==n)}function wt(e,t=st.cn){let n=e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url;return{baseUrl:at(n||t),baseUrlIsDefault:!n}}function Tt(e,t=st.cn){return wt(e,t).baseUrl}function Et(e){let t=Tt(e);if(e.flags.apiKey)return{token:e.flags.apiKey,baseUrl:t,source:`flag`};let n=e.env.DASHSCOPE_API_KEY?.trim();if(n)return{token:n,baseUrl:t,source:`env`};if(e.file.api_key)return{token:e.file.api_key,baseUrl:t,source:`config`};throw new D(`No API key found.`,E.AUTH,"Set DASHSCOPE_API_KEY, pass --api-key, or run `bl auth login`.")}function Dt(e){let t=e.file.access_token?.trim();if(!t)throw new D(`No console access token found.`,E.AUTH,"Run `bl auth login --console`.");return{token:t,region:e.flags.consoleRegion||e.file.console_region||`cn-beijing`,site:e.flags.consoleSite||e.file.console_site||`domestic`,switchAgent:e.flags.consoleSwitchAgent||e.file.console_switch_agent||void 0,source:`config`}}function Ot(e){let t=kt(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0,e.flags.securityToken);if(t)return t;let n=kt(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(At(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||At(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(n)return n;let r=kt(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret),e.file.security_token);if(r)return r;throw new D(`No OpenAPI AK/SK credentials found.`,E.AUTH,"Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, pass --access-key-id and --access-key-secret, or run `bl auth login --open-api`.")}function kt(e,t,n,r,i){if(!r)return;let a=At(t),o=At(n);if(!a||!o)throw new D(`Incomplete OpenAPI AK/SK credentials found.`,E.AUTH,jt(e));return{accessKeyId:a,accessKeySecret:o,securityToken:At(i),source:e}}function At(e){return e?.trim()||void 0}function jt(e){return e===`flag`?`Pass both --access-key-id and --access-key-secret, or remove the partial flags to use env/config credentials.`:e===`env`?`Set both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, or unset the partial env vars to use config credentials.`:"Run `bl auth login --open-api --access-key-id <id> --access-key-secret <secret>` again to save a complete pair."}function Mt(e){let t={};try{t.apiKey=Et(e)}catch{}try{t.console=Dt(e)}catch{}try{t.openapi=Ot(e)}catch{}return t}function Nt(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function Pt(){return g(Nt(),`config.json`)}function Ft(){return g(Nt(),`credentials.json`)}async function It(){let e=Nt(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function Lt(e){return v(e).replace(/\n$/,``)}function Rt(e){return JSON.stringify(e,null,2)}function zt(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function Bt(e){return e===`json`||e===`text`?e:`text`}function Vt(e,t){switch(t){case`json`:return Rt(e);case`text`:return Lt(e)}}const Ht={"en-US":`Timeout must be a positive finite number.`,"zh-CN":`请求超时必须是一个有限的正数。`};function Ut(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return Ht}const Wt=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,Gt=`active_config`;function Kt(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function qt(e){if(e!==void 0&&e!==``&&e!=="default"){if(typeof e!=`string`||!Wt.test(e))throw new D(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,E.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(ft.includes(e)||e===Gt)throw new D(`Invalid config name "${e}". It conflicts with a config key.`,E.USAGE);return e}}function Jt(){let e=Pt();if(!i(e))return{};try{let t=JSON.parse(o(e,`utf-8`));return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e;return(t instanceof SyntaxError||t.message.includes(`JSON`))&&console.warn(`Warning: config file is corrupted; using defaults.`),{}}}function Yt(e,t){let n=qt(e[Gt]);if(n&&t&&!Kt(e[n]))throw new D(`Active config "${n}" does not exist.`,E.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function Xt(e,t){if(!t)return e;let n=e[t];return Kt(n)?n:{}}function Zt(e){return yt(Xt(Jt(),e))}async function Qt(e,t,n={}){let r=Jt();if(t)r[t]=e;else{for(let e of Object.keys(r))ft.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[Gt]=t??`default`),await $t(r)}async function $t(e){await It();let t=Pt(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
|
|
2
|
-
`,{mode:384}),s(n,t)}function en(){let e=Jt(),t={};for(let[n,r]of Object.entries(e))ft.includes(n)||n===Gt||Kt(r)&&(t[n]=yt(r));return{default:yt(e),named:t,active:Yt(e,!0)??`default`}}function tn(e,t){let n=qt(t);if(n&&!Kt(e[n]))throw new D(`Config "${n}" does not exist.`,E.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function nn(e){return tn(Jt(),e)}async function rn(e){let t=Jt(),n=tn(t,e);return t[Gt]=n,await $t(t),n}async function an(e){let t=qt(e);if(!t)throw new D(`Cannot delete the default profile.`,E.USAGE);let n=Jt();return Kt(n[t])?(delete n[t],Yt(n,!1)===t&&(n[Gt]=`default`),await $t(n),!0):!1}function on(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:Zt(),configName:void 0},fallbackFrom:e.configName}}function sn(e){let t=Jt(),n=e.config!==void 0,r=Yt(t,!n),i=n?qt(e.config):r;return{flags:e,file:yt(Xt(t,i)),env:process.env,configName:i,configPath:Pt()}}function cn(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=Ut(i)===void 0?i:void 0,o=t.timeout??a??n.timeout??300,s=Ut(o);if(s)throw new D(s[`en-US`],E.USAGE);return{configPath:e.configPath??Pt(),configName:e.configName,output:Bt(t.output||r.DASHSCOPE_OUTPUT||n.output),outputExplicit:!!(t.output||r.DASHSCOPE_OUTPUT||n.output),outputSource:t.output?`flag`:r.DASHSCOPE_OUTPUT?`env`:n.output?`file`:`default`,outputDir:n.output_dir||void 0,timeout:o,watermark:n.watermark??!0,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultSpeechRecognitionModel:n.default_speech_recognition_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,verbose:t.verbose||r.DASHSCOPE_VERBOSE===`1`,quiet:t.quiet||!1,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const ln={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function un(e){return e?ln[e]:void 0}function dn(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function fn(e,t,n){if(n)return t;let r=dn(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const pn={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function mn(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>Mt({...e,file:Zt(t)}),stored(){let e=Zt(t);return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret||e.security_token),baseUrl:e.base_url,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>Tt(e,t),async login(e){let r=e.api_key?fn(e.api_key,t,n):t,i=n||r!==t,a=Zt(r);for(let[t,n]of Object.entries(e))if(n!==void 0){if(t===`api_key_capabilities`&&Array.isArray(n)){let e=Array.isArray(a[t])?a[t]:[];a[t]=[.../* @__PURE__ */ new Set([...e,...n])]}else a[t]=t===`base_url`?at(String(n)):n}await Qt(a,r,{activate:i})},async logout(e){let n=Zt(t),r=pn[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await Qt(n,t),!0},get path(){return e.configPath??Pt()}}}const hn=process.versions.bun?void 0:b();globalThis.Request,hn&&b()!==hn&&te(hn);const gn={async fetch(e,t){return process.versions.bun?globalThis.fetch(e,t):ee(e,t)}},_n={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function vn(e,t){return _n[e]?.[t]??_n[`cn-beijing`][t]}function yn(e){let t=e.consoleRegion??`cn-beijing`,n=e.consoleSite??`domestic`,r=e.consoleSwitchAgent;return r==null?{consoleRegion:t,consoleSite:n}:{consoleRegion:t,consoleSite:n,consoleSwitchAgent:r}}function bn(e){let t=yn(e);return(n,r)=>Sn({region:t.consoleRegion,site:t.consoleSite,switchAgent:t.consoleSwitchAgent},e.timeout,{api:n,data:r})}function xn(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function Sn(e,t,{api:n,data:r},i){let a=vn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=xn(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;i?.verbose&&(process.stderr.write(`> POST ${f}\n`),process.stderr.write(`> payload ${JSON.stringify({params:JSON.parse(c),region:e.region},null,2)}\n`));let p=await gn.fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(i?.verbose&&process.stderr.write(`< ${p.status} ${p.statusText}\n`),!p.ok){let e=await p.text().catch(()=>``);throw new D(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,E.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t),r=n.includes(`NotLogined`);throw new D(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?E.AUTH:E.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}function Cn(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}const wn=`bailian-cli`,Tn=`bailian-cli-call`,En=`BailianCLI`,Dn=`X-Dashscope-Service`;function On(e){return JSON.stringify({channel:wn,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function kn(e,t=wn){return{"x-dashscope-source-config":On(e),"x-dashscope-openapisource":En,[Dn]:t}}const An=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function jn(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function Mn(e,t){let n=Pn((t.timeout??e.settings.timeout)*1e3,t.signal);try{return Fn(await Nn(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function Nn(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...kn(e.identity),...t.headers};if(!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),jn(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),e.settings.verbose){console.error(`> ${t.method??`GET`} ${t.url}`);let n=i.Authorization;n&&console.error(`> Auth: ${Cn(n.replace(/^Bearer /,``))}`),console.error(`> x-dashscope-source-config: ${On(e.identity)}`)}let a={method:t.method??`GET`,headers:i,body:t.body?r?t.body:JSON.stringify(t.body):void 0,signal:n,...process.versions.bun?{timeout:!1}:{dispatcher:y.prototype.compose.call(b(),An)}},o=await gn.fetch(t.url,a);if(e.settings.verbose){console.error(`< ${o.status} ${o.statusText}`);let e=o.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}if(!o.ok){let e=await o.text(),n;try{let t=JSON.parse(e);n=typeof t==`object`&&t?t:{message:e}}catch{n={message:e}}n.request_id??=o.headers.get(`x-request-id`)??void 0;let r=it(o.status,n,t.url);throw new D(r.message,r.exitCode,r.hint,{api:r.api,rawResponse:e})}return o}function Pn(e,t){let n=new AbortController,r,i=!1,a=t=>{i||(clearTimeout(r),r=setTimeout(()=>n.abort(t),e))},o=()=>n.abort(t?.reason),s=()=>{i=!0,clearTimeout(r),t?.removeEventListener(`abort`,o),n.signal.removeEventListener(`abort`,s)};return n.signal.addEventListener(`abort`,s,{once:!0}),t?.aborted?o():(t?.addEventListener(`abort`,o,{once:!0}),a()),{signal:n.signal,cleanup:s,abort:e=>n.abort(e),pauseTimeout:()=>clearTimeout(r),resetIdleTimeout:()=>a(new D(`Response body idle timeout: no data received for ${e/1e3}s.`,E.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function Fn(e,t){if(!e.body)return t.cleanup(),e;t.pauseTimeout();let n=e.body.getReader(),{signal:r}=t,i=!1,a,o=()=>{i=!0,r.removeEventListener(`abort`,a),t.cleanup()},s=e=>n.cancel(e).finally(()=>n.releaseLock()),c=new ReadableStream({start(e){a=()=>{i||(o(),e.error(r.reason),s(r.reason).catch(()=>{}))},r.addEventListener(`abort`,a,{once:!0}),r.aborted&&a()},async pull(e){try{t.resetIdleTimeout();let r=await n.read();if(t.pauseTimeout(),i)return;r.done?(o(),n.releaseLock(),e.close()):e.enqueue(r.value)}catch(t){if(i)return;o(),n.releaseLock(),e.error(r.aborted?r.reason:t)}},cancel(e){return o(),t.abort(e),s(e).catch(()=>{})}},{highWaterMark:0}),l=new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(l,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),l}async function In(e,t){let n=Pn((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await Nn(e,t,n.signal),i;try{i=await r.json()}catch(e){if(n.signal.aborted)throw n.signal.reason;if(!(e instanceof SyntaxError))throw e;let t=r.headers.get(`content-type`)||``;throw new D(`API returned non-JSON response (${t||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${t||`未知类型`}),服务器可能出现问题。`,E.GENERAL)}if(typeof i==`object`&&i&&(i.code&&i.code!==`200`&&i.code!==200&&i.code!==`Success`||i.error)){let e=it(r.status,{...i,request_id:i.request_id??i.requestID??r.headers.get(`x-request-id`)??void 0},t.url);throw new D(e.message,e.exitCode,e.hint,{api:e.api,rawResponse:JSON.stringify(i)})}return i}catch(e){throw n.signal.aborted?n.signal.reason:e}finally{n.cleanup()}}function Ln(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0&&r!==``){if(Array.isArray(r))for(let e=0;e<r.length;e++){let i=r[e];i!==``&&t.push([`${n}.${e+1}`,i])}else t.push([n,r])}return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${zn(e)}=${zn(String(t))}`).join(`&`)}function Rn(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=ae(),i=Bn(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
|
|
1
|
+
import{createRequire as e}from"node:module";import{appendFileSync as t,createReadStream as n,createWriteStream as r,existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,rmSync as c,statSync as l,unlinkSync as u,writeFileSync as d}from"fs";import{homedir as f,tmpdir as p}from"os";import{basename as m,extname as h,join as g}from"path";import{parse as _,stringify as v}from"yaml";import{Dispatcher as y,fetch as b,getGlobalDispatcher as x,setGlobalDispatcher as ee}from"undici";import{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie}from"crypto";import{Readable as ae}from"stream";import{createInterface as oe}from"readline";import{pipeline as se}from"stream/promises";import*as ce from"yauzl";import{copyFileSync as le,cpSync as ue,createReadStream as de,createWriteStream as fe,existsSync as S,lstatSync as pe,mkdirSync as me,readFileSync as he,readdirSync as ge,readlinkSync as _e,realpathSync as ve,renameSync as C,rmSync as w,statSync as ye,symlinkSync as be,writeFileSync as xe}from"node:fs";import{isIP as Se}from"node:net";import{Readable as Ce}from"node:stream";import{basename as we,dirname as Te,isAbsolute as Ee,join as T,relative as De,resolve as Oe,sep as ke}from"node:path";import{parse as Ae}from"csv-parse";import{stringify as je}from"csv-stringify/sync";import{link as Me,mkdir as Ne,open as Pe,readFile as Fe,rename as Ie,unlink as Le}from"node:fs/promises";import{createHash as Re,randomUUID as ze}from"node:crypto";import{setTimeout as Be}from"node:timers/promises";import{createInterface as Ve}from"node:readline/promises";import{homedir as He}from"node:os";import{pipeline as Ue}from"node:stream/promises";import{createBrotliDecompress as We}from"node:zlib";import Ge from"tar-stream";var Ke=Object.create,qe=Object.defineProperty,Je=Object.getOwnPropertyDescriptor,Ye=Object.getOwnPropertyNames,Xe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty,E=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ye(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ze.call(e,s)&&s!==n&&qe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Je(t,s))||r.enumerable});return e},$e=(e,t,n)=>(n=e==null?{}:Ke(Xe(e)),Qe(t||!e||!e.__esModule||!Ze.call(e,`default`)?qe(n,`default`,{value:e,enumerable:!0}):n,e)),et=/* @__PURE__ */ e(import.meta.url);const tt=/(?:authorization|cookie|apikey|accesskey(?:id)?|privatekey|credentials?|token|password|secret)$/i;function nt(e,t=/* @__PURE__ */ new Set,n=0){if(typeof e==`bigint`)return e.toString();if(typeof e==`function`)return`[Function]`;if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;if(n>=8)return`[Truncated]`;t.add(e);try{let r=Object.getOwnPropertyDescriptors(e),i=e=>{if(e)return`value`in e?nt(e.value,t,n+1):`[Accessor]`};if(Array.isArray(e)){let e=r.length?.value;return Array.from({length:e},(e,t)=>i(r[String(t)]))}return Object.fromEntries(Object.entries(r).filter(([,e])=>e.enumerable).map(([e,t])=>[e,tt.test(e.replaceAll(/[-_]/g,``))?`[REDACTED]`:i(t)]))}catch{return`[Unserializable]`}finally{t.delete(e)}}const D={SUCCESS:0,GENERAL:1,USAGE:2,AUTH:3,QUOTA:4,TIMEOUT:5,NETWORK:6,CONFIRMATION_REQUIRED:7,CONTENT_FILTER:10,INTERRUPTED:130};var O=class extends Error{exitCode;hint;api;rawResponse;constructor(e,t=D.GENERAL,n,r){super(e,r?.cause===void 0?void 0:{cause:r.cause}),this.name=`BailianError`,this.exitCode=t,this.hint=n,this.api=r?.api,this.rawResponse=r?.rawResponse}toJSON(){let e=it(this.cause);return{error:{code:this.exitCode,message:this.message,...this.hint?{hint:this.hint}:{},...this.api?.httpStatus===void 0?{}:{http_status:this.api.httpStatus},...this.api?.apiCode?{api_code:this.api.apiCode}:{},...this.api?.requestId?{request_id:this.api.requestId}:{},...e?{cause:e}:{}}}}},rt=class extends O{constructor(e,t){super(e,D.USAGE,t),this.name=`UsageError`}};function it(e){if(e!=null){if(e instanceof Error){let t={message:e.message},n=e.code;return n&&(t.code=n),t}if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return{message:String(e)};try{return{message:JSON.stringify(nt(e))}}catch{return}}}var at=class extends O{reason;constructor(e,t,n,r){super(t,D.AUTH,n,r),this.reason=e}};function ot(e,t,n){let r=t.error?.message||t.message||`HTTP ${e}`,i=t.error?.type??t.error?.code??t.code,a=typeof i==`string`?i:typeof i==`number`?String(i):void 0;return new O(r,D.GENERAL,void 0,{api:{httpStatus:e,apiCode:a,requestId:t.request_id??t.requestID}})}function st(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw ct(e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw ct(e);return n.origin}function ct(e){return new O(`Invalid model base URL "${e}".`,D.USAGE,`Use an absolute http(s) URL.`)}const lt={cn:`https://dashscope.aliyuncs.com`,us:`https://dashscope-us.aliyuncs.com`,intl:`https://dashscope-intl.aliyuncs.com`},ut={cn:`https://help.aliyun.com/zh/model-studio`,us:`https://help.aliyun.com/zh/model-studio`,intl:`https://help.aliyun.com/zh/model-studio`},dt=`https://bailian.cn-beijing.aliyuncs.com`,ft=[`en-US`,`zh-CN`],pt=`en-US`,mt=[`language`,`api_key`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`,`base_url`,`output`,`output_dir`,`timeout`,`watermark`,`default_text_model`,`default_video_model`,`default_image_to_video_model`,`default_reference_to_video_model`,`default_image_model`,`default_speech_model`,`default_speech_recognition_model`,`default_omni_model`,`api_key_capabilities`,`workspace_id`,`console_site`,`console_region`,`console_switch_agent`,`telemetry`],ht=/* @__PURE__ */ new Set([`text`,`json`]),gt=/* @__PURE__ */ new Set([`domestic`,`international`]),_t=/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;function vt(e){return _t.test(e)}function yt(e){if(e===void 0)return;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)return[];let e=n.trim();if(!vt(e))return[];t.includes(e)||t.push(e)}return t}function bt(e){try{return st(e)}catch{return}}function xt(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};if(typeof t.language==`string`&&ft.includes(t.language)&&(n.language=t.language),typeof t.api_key==`string`&&(n.api_key=t.api_key),typeof t.access_token==`string`&&t.access_token.length>0?n.access_token=t.access_token:typeof t.accessToken==`string`&&t.accessToken.length>0&&(n.access_token=t.accessToken),typeof t.access_key_id==`string`&&t.access_key_id.length>0?n.access_key_id=t.access_key_id:typeof t.openapi_access_key_id==`string`&&t.openapi_access_key_id.length>0&&(n.access_key_id=t.openapi_access_key_id),typeof t.access_key_secret==`string`&&t.access_key_secret.length>0?n.access_key_secret=t.access_key_secret:typeof t.openapi_access_key_secret==`string`&&t.openapi_access_key_secret.length>0&&(n.access_key_secret=t.openapi_access_key_secret),typeof t.security_token==`string`&&t.security_token.length>0&&(n.security_token=t.security_token),typeof t.base_url==`string`){let e=bt(t.base_url);e&&(n.base_url=e)}typeof t.output==`string`&&ht.has(t.output)&&(n.output=t.output),typeof t.output_dir==`string`&&t.output_dir.length>0&&(n.output_dir=t.output_dir),typeof t.timeout==`number`&&t.timeout>0&&(n.timeout=t.timeout),typeof t.watermark==`boolean`&&(n.watermark=t.watermark),typeof t.default_text_model==`string`&&t.default_text_model.length>0&&(n.default_text_model=t.default_text_model),typeof t.default_video_model==`string`&&t.default_video_model.length>0&&(n.default_video_model=t.default_video_model),typeof t.default_image_to_video_model==`string`&&t.default_image_to_video_model.length>0&&(n.default_image_to_video_model=t.default_image_to_video_model),typeof t.default_reference_to_video_model==`string`&&t.default_reference_to_video_model.length>0&&(n.default_reference_to_video_model=t.default_reference_to_video_model),typeof t.default_image_model==`string`&&t.default_image_model.length>0&&(n.default_image_model=t.default_image_model),typeof t.default_speech_model==`string`&&t.default_speech_model.length>0&&(n.default_speech_model=t.default_speech_model),typeof t.default_speech_recognition_model==`string`&&t.default_speech_recognition_model.length>0&&(n.default_speech_recognition_model=t.default_speech_recognition_model),typeof t.default_omni_model==`string`&&t.default_omni_model.length>0&&(n.default_omni_model=t.default_omni_model);let r=yt(t.api_key_capabilities);return r!==void 0&&(n.api_key_capabilities=r),typeof t.workspace_id==`string`&&t.workspace_id.length>0&&(n.workspace_id=t.workspace_id),typeof t.console_site==`string`&>.has(t.console_site)&&(n.console_site=t.console_site),typeof t.console_region==`string`&&t.console_region.length>0&&(n.console_region=t.console_region),typeof t.console_switch_agent==`number`&&t.console_switch_agent>0&&(n.console_switch_agent=t.console_switch_agent),typeof t.telemetry==`boolean`&&(n.telemetry=t.telemetry),n}function St(e){if(e.flags.apiKey)return`flag`;if(e.env.DASHSCOPE_API_KEY?.trim())return`env`;if(e.file.api_key)return`config`}function Ct(e){if(e.flags.baseUrl)return`flag`;if(e.env.DASHSCOPE_BASE_URL?.trim())return`env`;if(e.file.base_url)return`config`}function wt(e){return{apiKeySource:St(e),baseUrlSource:Ct(e)}}function Tt(e){let{apiKeySource:t,baseUrlSource:n}=e;return!!(t&&n&&t!==n)}function Et(e,t=lt.cn){let n=e.flags.baseUrl||e.env.DASHSCOPE_BASE_URL||e.file.base_url;return{baseUrl:st(n||t),baseUrlIsDefault:!n}}function Dt(e,t=lt.cn){return Et(e,t).baseUrl}function Ot(e){let t=Dt(e);if(e.flags.apiKey)return{token:e.flags.apiKey,baseUrl:t,source:`flag`};let n=e.env.DASHSCOPE_API_KEY?.trim();if(n)return{token:n,baseUrl:t,source:`env`};if(e.file.api_key)return{token:e.file.api_key,baseUrl:t,source:`config`};throw new at(`missing-api-key`,`No API key found.`,`Set DASHSCOPE_API_KEY or pass --api-key.`)}function kt(e){let t=e.file.access_token?.trim();if(!t)throw new at(`missing-console-token`,`No console access token found.`);return{token:t,region:e.flags.consoleRegion||e.file.console_region||`cn-beijing`,site:e.flags.consoleSite||e.file.console_site||`domestic`,switchAgent:e.flags.consoleSwitchAgent||e.file.console_switch_agent||void 0,source:`config`}}function At(e){let t=jt(`flag`,e.flags.accessKeyId,e.flags.accessKeySecret,e.flags.accessKeyId!==void 0||e.flags.accessKeySecret!==void 0,e.flags.securityToken);if(t)return t;let n=jt(`env`,e.env.BAILIAN_ACCESS_KEY_ID,e.env.BAILIAN_ACCESS_KEY_SECRET,!!(Mt(e.env.BAILIAN_ACCESS_KEY_ID)||Mt(e.env.BAILIAN_ACCESS_KEY_SECRET)),e.env.BAILIAN_SECURITY_TOKEN,`BAILIAN`);if(n)return n;let r=jt(`config`,e.file.access_key_id,e.file.access_key_secret,!!(e.file.access_key_id||e.file.access_key_secret),e.file.security_token);if(r)return r;let i=jt(`env`,e.env.ALIBABA_CLOUD_ACCESS_KEY_ID,e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,!!(Mt(e.env.ALIBABA_CLOUD_ACCESS_KEY_ID)||Mt(e.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET)),e.env.ALIBABA_CLOUD_SECURITY_TOKEN);if(i)return i;throw new at(`missing-openapi-pair`,`No OpenAPI AK/SK credentials found.`,`Set BAILIAN_ACCESS_KEY_ID and BAILIAN_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET), or pass --access-key-id and --access-key-secret.`)}function jt(e,t,n,r,i,a=`ALIBABA_CLOUD`){if(!r)return;let o=Mt(t),s=Mt(n);if(!o||!s)throw new at(`incomplete-openapi-${e}`,`Incomplete OpenAPI AK/SK credentials found.`,Nt(e,a));return{accessKeyId:o,accessKeySecret:s,securityToken:Mt(i),source:e}}function Mt(e){return e?.trim()||void 0}function Nt(e,t){return e===`flag`?`Pass both --access-key-id and --access-key-secret, or remove the partial flags to use env/config credentials.`:e===`env`?`Set both ${t}_ACCESS_KEY_ID and ${t}_ACCESS_KEY_SECRET, or unset the partial env vars.`:`Save a complete AccessKey ID and secret pair in the selected configuration.`}function Pt(e){let t={};try{t.apiKey=Ot(e)}catch{}try{t.console=kt(e)}catch{}try{t.openapi=At(e)}catch{}return t}function Ft(){return process.env.BAILIAN_CONFIG_DIR?process.env.BAILIAN_CONFIG_DIR:g(f(),`.bailian`)}function It(){return g(Ft(),`config.json`)}function Lt(){return g(Ft(),`credentials.json`)}async function Rt(){let e=Ft(),t=await import(`fs/promises`);await t.mkdir(e,{recursive:!0,mode:448});try{await t.chmod(e,448)}catch{}}function zt(e){return v(e).replace(/\n$/,``)}function Bt(e){return JSON.stringify(e,null,2)}function Vt(e,t,n){return JSON.stringify({error:{code:e,message:t,...n?{hint:n}:{}}},null,2)}function Ht(e){return e===`json`||e===`text`?e:`text`}function Ut(e,t){switch(t){case`json`:return Bt(e);case`text`:return zt(e)}}const Wt={"en-US":`Timeout must be a positive finite number.`,"zh-CN":`请求超时必须是一个有限的正数。`};function Gt(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return Wt}const Kt=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,qt=`active_config`;function Jt(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function Yt(e){if(e!==void 0&&e!==``&&e!=="default"){if(typeof e!=`string`||!Kt.test(e))throw new O(`Invalid config name "${typeof e==`string`?e:JSON.stringify(e)}".`,D.USAGE,`Use letters, numbers, '-' or '_', starting with a letter or number.`);if(mt.includes(e)||e===qt)throw new O(`Invalid config name "${e}". It conflicts with a config key.`,D.USAGE);return e}}function Xt(e){let t=It();if(!i(t))return{};try{let e=JSON.parse(o(t,`utf-8`));return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(t){let n=t;return(n instanceof SyntaxError||n.message.includes(`JSON`))&&e?.({code:`CONFIG_CORRUPTED`,message:{"en-US":`Config file is corrupted; using defaults.`,"zh-CN":`配置文件已损坏,将使用默认配置。`}}),{}}}function Zt(e,t){let n=Yt(e[qt]);if(n&&t&&!Jt(e[n]))throw new O(`Active config "${n}" does not exist.`,D.USAGE,`Use --config default to select the default config, then activate an existing profile.`);return n}function Qt(e,t){if(!t)return e;let n=e[t];return Jt(n)?n:{}}function $t(e){return xt(Qt(Xt(),e))}async function en(e,t,n={}){let r=Xt();if(t)r[t]=e;else{for(let e of Object.keys(r))mt.includes(e)&&delete r[e];Object.assign(r,e)}n.activate&&(r[qt]=t??`default`),await tn(r)}async function tn(e){await Rt();let t=It(),n=t+`.tmp`;d(n,JSON.stringify(e,null,2)+`
|
|
2
|
+
`,{mode:384}),s(n,t)}function nn(){let e=Xt(),t={};for(let[n,r]of Object.entries(e))mt.includes(n)||n===qt||Jt(r)&&(t[n]=xt(r));return{default:xt(e),named:t,active:Zt(e,!0)??`default`}}function rn(e,t){let n=Yt(t);if(n&&!Jt(e[n]))throw new O(`Config "${n}" does not exist.`,D.USAGE,`Create or log in to the profile before activating it.`);return n??`default`}function an(e){return rn(Xt(),e)}async function on(e){let t=Xt(),n=rn(t,e);return t[qt]=n,await tn(t),n}async function sn(e){let t=Yt(e);if(!t)throw new O(`Cannot delete the default profile.`,D.USAGE);let n=Xt();return Jt(n[t])?(delete n[t],Zt(n,!1)===t&&(n[qt]=`default`),await tn(n),!0):!1}function cn(e,t){if(e.flags.apiKey||e.flags.baseUrl||e.env.DASHSCOPE_API_KEY?.trim()||e.env.DASHSCOPE_BASE_URL||!e.configName)return{sources:e};let n=e.file.api_key_capabilities;return n===void 0||n.includes(t)?{sources:e}:{sources:{...e,file:$t(),configName:void 0},fallbackFrom:e.configName}}function ln(e,t){let n=Xt(t),r=e.config!==void 0,i=Zt(n,!r),a=r?Yt(e.config):i;return{flags:e,file:xt(Qt(n,a)),env:process.env,configName:a,configPath:It()}}function un({flags:e,env:t,file:n={}}){let r=e.output||t.DASHSCOPE_OUTPUT||n.output;return{output:Ht(r),outputExplicit:!!r,outputSource:e.output?`flag`:t.DASHSCOPE_OUTPUT?`env`:n.output?`file`:`default`,quiet:e.quiet||t.DASHSCOPE_QUIET===`1`,verbose:e.verbose||t.DASHSCOPE_VERBOSE===`1`}}function dn(e){let{flags:t,file:n,env:r}=e,i=r.DASHSCOPE_TIMEOUT?Number(r.DASHSCOPE_TIMEOUT):void 0,a=Gt(i)===void 0?i:void 0,o=t.timeout??a??n.timeout??300,s=Gt(o);if(s)throw new O(s[`en-US`],D.USAGE);return{configPath:e.configPath??It(),configName:e.configName,...un(e),outputDir:n.output_dir||void 0,timeout:o,watermark:n.watermark??!0,defaultTextModel:n.default_text_model,defaultVideoModel:n.default_video_model,defaultImageToVideoModel:n.default_image_to_video_model,defaultReferenceToVideoModel:n.default_reference_to_video_model,defaultImageModel:n.default_image_model,defaultSpeechModel:n.default_speech_model,defaultSpeechRecognitionModel:n.default_speech_recognition_model,defaultOmniModel:n.default_omni_model,workspaceId:t.workspaceId||r.BAILIAN_WORKSPACE_ID||n.workspace_id||void 0,consoleRegion:t.consoleRegion||n.console_region||void 0,consoleSite:t.consoleSite||n.console_site||void 0,consoleSwitchAgent:t.consoleSwitchAgent||n.console_switch_agent||void 0,dryRun:t.dryRun||!1,telemetry:r.DO_NOT_TRACK===`1`?!1:n.telemetry??!0}}const fn={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`,defaultSpeechModel:`qwen-audio-3.0-tts-plus`,defaultSpeechRecognitionModel:`qwen-audio-3.0-asr-flash`,apiKeyCapabilities:[`text.chat`,`vision.describe`,`image.generate`,`image.edit`,`speech.recognize`,`speech.synthesize`,`video.generate`,`video.ref`,`video.task.get`,`video.download`]}};function pn(e){return e?fn[e]:void 0}function mn(e){let t=e.trim();return t.startsWith(`sk-sp-`)?`token-plan`:t.startsWith(`sk-`)?`ordinary`:`unknown`}function hn(e,t,n){if(n)return t;let r=mn(e);if(r===`token-plan`)return`token-plan`;if(r!==`ordinary`||t!==`token-plan`)return t}const gn={console:[`access_token`],openapi:[`access_key_id`,`access_key_secret`,`security_token`],all:[`api_key`,`base_url`,`access_token`,`access_key_id`,`access_key_secret`,`security_token`]};function _n(e){let t=e.configName,n=e.flags.config!==void 0;return{describe:()=>Pt({...e,file:$t(t)}),stored(){let e=$t(t);return{apiKey:!!e.api_key,console:!!e.access_token,openapi:!!(e.access_key_id||e.access_key_secret||e.security_token),baseUrl:e.base_url,apiKeyCapabilities:e.api_key_capabilities}},resolveBaseUrl:t=>Dt(e,t),async login(e){let r=e.api_key?hn(e.api_key,t,n):t,i=n||r!==t,a=$t(r);for(let[t,n]of Object.entries(e))if(n!==void 0){if(t===`api_key_capabilities`&&Array.isArray(n)){let e=Array.isArray(a[t])?a[t]:[];a[t]=[.../* @__PURE__ */ new Set([...e,...n])]}else a[t]=t===`base_url`?st(String(n)):n}await en(a,r,{activate:i})},async logout(e){let n=$t(t),r=gn[e];if(!r.some(e=>n[e]!==void 0))return!1;for(let e of r)delete n[e];return await en(n,t),!0},get path(){return e.configPath??It()}}}function vn(e){try{let t=new URL(e);t.username=``,t.password=``;for(let e of t.searchParams.keys())t.searchParams.set(e,`[REDACTED]`);return t.hash=``,t.toString()}catch{return`[Invalid URL]`}}function yn(e,t,n,r){e.debug?.({message:{"en-US":`HTTP request`,"zh-CN":`HTTP 请求`},details:{method:t,url:vn(n),...r}})}function bn(e,t){e.debug?.({message:{"en-US":`HTTP response`,"zh-CN":`HTTP 响应`},details:{status:t.status,status_text:t.statusText,request_id:t.headers.get(`x-request-id`)??void 0}})}const xn=process.versions.bun?void 0:x();globalThis.Request,xn&&x()!==xn&&ee(xn);const Sn={async fetch(e,t){return process.versions.bun?globalThis.fetch(e,t):b(e,t)}},Cn={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function wn(e,t){return Cn[e]?.[t]??Cn[`cn-beijing`][t]}function Tn(e){let t=e.consoleRegion??`cn-beijing`,n=e.consoleSite??`domestic`,r=e.consoleSwitchAgent;return r==null?{consoleRegion:t,consoleSite:n}:{consoleRegion:t,consoleSite:n,consoleSwitchAgent:r}}function En(e,t={}){let n=Tn(e);return(r,i)=>On({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:r,data:i},t)}function Dn(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function On(e,t,{api:n,data:r},i={}){let a=wn(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=Dn(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;yn(i,`POST`,f,{api:n,region:e.region});let p=await Sn.fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(bn(i,p),!p.ok){let e=await p.text().catch(()=>``);throw new O(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,D.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t);throw n.includes(`NotLogined`)?new at(`expired-console-session`,`Console session is not logged in or has expired.`,i.recoveryHint,{rawResponse:e}):new O(`Console gateway error: ${n}`,D.GENERAL,void 0,{rawResponse:e})}return m}const kn=`bailian-cli`,An=`bailian-cli-call`,jn=`BailianCLI`,Mn=`X-Dashscope-Service`;function Nn(e){return JSON.stringify({channel:kn,tags:{t1:`public`,t2:e.binName,t3:e.version}})}function Pn(e,t=kn){return{"x-dashscope-source-config":Nn(e),"x-dashscope-openapisource":jn,[Mn]:t}}const Fn=e=>(t,n)=>e({...t,headersTimeout:0,bodyTimeout:0},n);function In(e){return typeof e!=`object`||!e||e instanceof FormData?!1:JSON.stringify(e).includes(`oss://`)}async function Ln(e,t){let n=zn((t.timeout??e.settings.timeout)*1e3,t.signal);try{return Bn(await Rn(e,t,n.signal),n)}catch(e){throw n.cleanup(),n.signal.aborted?n.signal.reason:e}}async function Rn(e,t,n){let r=typeof FormData<`u`&&t.body instanceof FormData,i={"User-Agent":`${e.identity.clientName}/${e.identity.version}`,...Pn(e.identity),...t.headers};!r&&!i[`Content-Type`]&&(i[`Content-Type`]=`application/json`),t.async&&(i[`X-DashScope-Async`]=`enable`),In(t.body)&&(i[`X-DashScope-OssResourceResolve`]=`enable`),yn(e,t.method??`GET`,t.url);let a={method:t.method??`GET`,headers:i,body:t.body?r?t.body:JSON.stringify(t.body):void 0,signal:n,...process.versions.bun?{timeout:!1}:{dispatcher:y.prototype.compose.call(x(),Fn)}},o=await Sn.fetch(t.url,a);if(bn(e,o),!o.ok){let e=await o.text(),n;try{let t=JSON.parse(e);n=typeof t==`object`&&t?t:{message:e}}catch{n={message:e}}n.request_id??=o.headers.get(`x-request-id`)??void 0;let r=ot(o.status,n,t.url);throw new O(r.message,r.exitCode,r.hint,{api:r.api,rawResponse:e})}return o}function zn(e,t){let n=new AbortController,r,i=!1,a=t=>{i||(clearTimeout(r),r=setTimeout(()=>n.abort(t),e))},o=()=>n.abort(t?.reason),s=()=>{i=!0,clearTimeout(r),t?.removeEventListener(`abort`,o),n.signal.removeEventListener(`abort`,s)};return n.signal.addEventListener(`abort`,s,{once:!0}),t?.aborted?o():(t?.addEventListener(`abort`,o,{once:!0}),a()),{signal:n.signal,cleanup:s,abort:e=>n.abort(e),pauseTimeout:()=>clearTimeout(r),resetIdleTimeout:()=>a(new O(`Response body idle timeout: no data received for ${e/1e3}s.`,D.TIMEOUT,`Increase --timeout to allow a longer interval between response chunks.`))}}function Bn(e,t){if(!e.body)return t.cleanup(),e;t.pauseTimeout();let n=e.body.getReader(),{signal:r}=t,i=!1,a,o=()=>{i=!0,r.removeEventListener(`abort`,a),t.cleanup()},s=e=>n.cancel(e).finally(()=>n.releaseLock()),c=new ReadableStream({start(e){a=()=>{i||(o(),e.error(r.reason),s(r.reason).catch(()=>{}))},r.addEventListener(`abort`,a,{once:!0}),r.aborted&&a()},async pull(e){try{t.resetIdleTimeout();let r=await n.read();if(t.pauseTimeout(),i)return;r.done?(o(),n.releaseLock(),e.close()):e.enqueue(r.value)}catch(t){if(i)return;o(),n.releaseLock(),e.error(r.aborted?r.reason:t)}},cancel(e){return o(),t.abort(e),s(e).catch(()=>{})}},{highWaterMark:0}),l=new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(l,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type}}),l}async function Vn(e,t){let n=zn((t.timeout??e.settings.timeout)*1e3,t.signal);try{let r=await Rn(e,t,n.signal),i;try{i=await r.json()}catch(e){if(n.signal.aborted)throw n.signal.reason;if(!(e instanceof SyntaxError))throw e;let t=r.headers.get(`content-type`)||``;throw new O(`API returned non-JSON response (${t||`unknown type`}). Server may be experiencing issues.\nAPI 返回了非 JSON 响应(${t||`未知类型`}),服务器可能出现问题。`,D.GENERAL)}if(typeof i==`object`&&i&&(i.code&&i.code!==`200`&&i.code!==200&&i.code!==`Success`||i.error)){let e=ot(r.status,{...i,request_id:i.request_id??i.requestID??r.headers.get(`x-request-id`)??void 0},t.url);throw new O(e.message,e.exitCode,e.hint,{api:e.api,rawResponse:JSON.stringify(i)})}return i}catch(e){throw n.signal.aborted?n.signal.reason:e}finally{n.cleanup()}}function Hn(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0&&r!==``){if(Array.isArray(r))for(let e=0;e<r.length;e++){let i=r[e];i!==``&&t.push([`${n}.${e+1}`,i])}else t.push([n,r])}return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${Wn(e)}=${Wn(String(t))}`).join(`&`)}function Un(e){let t=e.method??`POST`,n=(/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/,`Z`),r=ie(),i=Gn(e.body),a={host:e.host,"x-acs-action":e.action,"x-acs-version":e.version,"x-acs-date":n,"x-acs-signature-nonce":r,"x-acs-content-sha256":i,"content-type":`application/json`};e.securityToken&&(a[`x-acs-security-token`]=e.securityToken);let o=Object.keys(a).filter(e=>e===`host`||e===`content-type`||e.startsWith(`x-acs-`)).sort(),s=o.map(e=>`${e}:${a[e]}`).join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`,c=o.join(`;`),l=e.queryString??``,u=[t,e.pathname,l,s,c,i].join(`
|
|
5
|
-
`),d=`ACS3-HMAC-SHA256`,f=`${d}\n${Bn(u)}`,p=Vn(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function zn(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Bn(e){return ne(`sha256`).update(e,`utf8`).digest(`hex`)}function Vn(e,t){return re(`sha256`,e).update(t,`utf8`).digest(`hex`)}const Hn=[`cn-beijing`,`ap-southeast-1`];function Un(e){return new D(`Local-file temporary upload is supported only in ${Hn.join(`, `)}; "${e}" is not supported.`,E.USAGE,`Use a reachable HTTPS media URL instead.`)}function Wn(e){if(dn(e)===`token-plan`)throw Un(`Token Plan`)}function Gn(e,t){let n=at(e),r=new URL(n).hostname.toLowerCase();if(/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/.test(r))throw Un(`Token Plan`);if(r===new URL(st.cn).hostname||r===new URL(st.intl).hostname)return Wn(t),n;if(r===new URL(st.us).hostname)throw Un(r);let i=/^[^.]+\.([a-z0-9-]+)\.maas\.aliyuncs\.com$/.exec(r)?.[1];if(i===`cn-beijing`||i===`ap-southeast-1`)return Wn(t),n;if(i)throw Un(i);return n}async function Kn(e,t,n,r,i){let a=`${Gn(r,e)}/api/v1/uploads`,o=`${a}?action=getPolicy&model=${encodeURIComponent(t)}`,s=rr(15e3,i),c=await gn.fetch(o,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...kn(n)},signal:s.signal}).finally(s.cleanup);if(!c.ok){let e=await c.text().catch(()=>``),t;try{t=JSON.parse(e)}catch{}let n=typeof t?.message==`string`&&t.message?t.message:e||`${c.status} ${c.statusText}`,r=typeof t?.code==`string`?t.code:void 0,i=typeof t?.request_id==`string`?t.request_id:void 0;throw new D(`${[`HTTP ${c.status}`,r?`code=${r}`:void 0,i?`request_id=${i}`:void 0,`upload_endpoint=${a}`].filter(e=>e!==void 0).join(`; `)} - ${n}`,E.GENERAL,void 0,{api:{httpStatus:c.status,apiCode:r,requestId:i},rawResponse:e.slice(0,500)})}return(await c.json()).data}async function qn(e,t,n,r=120){let i=m(t),a=`${e.upload_dir}/${i}`,s=o(t),c=new FormData;c.append(`OSSAccessKeyId`,e.oss_access_key_id),c.append(`Signature`,e.signature),c.append(`policy`,e.policy),c.append(`x-oss-object-acl`,e.x_oss_object_acl),c.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),c.append(`key`,a),c.append(`success_action_status`,`200`),c.append(`file`,new Blob([s]),i);let l=rr(r*1e3,n),u=await gn.fetch(e.upload_host,{method:`POST`,body:c,signal:l.signal}).finally(l.cleanup);if(!u.ok){let e=await u.text().catch(()=>``);throw new D(`Failed to upload file to OSS (HTTP ${u.status}): ${e}`,E.GENERAL)}return`oss://${a}`}const Jn={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`},Yn={".aac":`audio/aac`,".amr":`audio/amr`,".flac":`audio/flac`,".m4a":`audio/mp4`,".mp3":`audio/mpeg`,".oga":`audio/ogg`,".ogg":`audio/ogg`,".opus":`audio/opus`,".wav":`audio/wav`,".weba":`audio/webm`,".wma":`audio/x-ms-wma`};function Xn(e,t,n){if(!i(e))throw new D(`File not found: ${e}`,E.USAGE);if(!l(e).isFile())throw new D(`Not a file: ${e}`,E.USAGE);let r=h(e).toLowerCase(),a=t[r];if(!a)throw new D(`Unsupported ${n} format "${r||`unknown`}".`,E.USAGE,`Use an ${n} file with a recognized extension.`);return`data:${a};base64,${o(e).toString(`base64`)}`}function Zn(e){return Xn(e,Jn,`image`)}function Qn(e){return Xn(e,Yn,`audio`)}function $n(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function er(e){let{apiKey:t,baseUrl:n=st.cn,model:r,filePath:a,identity:o,signal:s,timeout:c}=e;if(!i(a))throw new D(`File not found: ${a}`,E.USAGE);if(!l(a).isFile())throw new D(`Not a file: ${a}`,E.USAGE);return qn(await Kn(t,r,o,n,s),a,s,c)}function tr(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function nr(e,t,n,r){return tr(e)?er({apiKey:t,baseUrl:r.baseUrl,model:n,filePath:e,identity:r.identity,signal:r.signal,timeout:r.timeout}):e}function rr(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}const ir=Object.freeze({status:`aborted`});function O(e,t,n){function r(n,r){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=/* @__PURE__ */ new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var ar=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};const or={};function sr(e){return e&&Object.assign(or,e),or}function cr(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function lr(e,t){return typeof t==`bigint`?t.toString():t}function ur(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function dr(e){return e==null}function fr(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function pr(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function k(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function mr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function hr(e){return JSON.stringify(e)}const gr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function _r(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const vr=ur(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function yr(e){if(_r(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return _r(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}const br=/* @__PURE__ */ new Set([`string`,`number`,`symbol`]);function xr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Sr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function A(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Cr(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const wr={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Tr(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return Sr(e,{...e._zod.def,shape:n,checks:[]})}function Er(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return Sr(e,{...e._zod.def,shape:n,checks:[]})}function Dr(e,t){if(!yr(t))throw Error(`Invalid input to extend: expected a plain object`);return Sr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return mr(this,`shape`,n),n},checks:[]})}function Or(e,t){return Sr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return mr(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function kr(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Sr(t,{...t._zod.def,shape:i,checks:[]})}function Ar(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Sr(t,{...t._zod.def,shape:i,checks:[]})}function jr(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Mr(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Nr(e){return typeof e==`string`?e:e?.message}function Pr(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=Nr(e.inst?._zod.def?.error?.(e))??Nr(t?.error?.(e))??Nr(n.customError?.(e))??Nr(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Fr(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ir(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const Lr=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,lr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Rr=O(`$ZodError`,Lr),zr=O(`$ZodError`,Lr,{Parent:Error});function Br(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Vr(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const Hr=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new ar;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Pr(e,a,sr())));throw gr(t,i?.callee),t}return o.value},Ur=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Pr(e,a,sr())));throw gr(t,i?.callee),t}return o.value},Wr=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new ar;return a.issues.length?{success:!1,error:new(e??Rr)(a.issues.map(e=>Pr(e,i,sr())))}:{success:!0,data:a.value}},Gr=/* @__PURE__*/ Wr(zr),Kr=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Pr(e,i,sr())))}:{success:!0,data:a.value}},qr=/* @__PURE__*/ Kr(zr),Jr=/^[cC][^\s-]{8,}$/,Yr=/^[0-9a-z]+$/,Xr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zr=/^[0-9a-vA-V]{20}$/,Qr=/^[A-Za-z0-9]{27}$/,$r=/^[a-zA-Z0-9_-]{21}$/,ei=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ti=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ni=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,ri=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function ii(){return/* @__PURE__ */ RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const ai=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,si=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ci=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,li=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ui=/^[A-Za-z0-9_-]*$/,di=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,fi=/^\+(?:[0-9]){6,14}[0-9]$/,pi=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,mi=/*@__PURE__*/ RegExp(`^${pi}$`);function hi(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function gi(e){return RegExp(`^${hi(e)}$`)}function _i(e){let t=hi({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${pi}T(?:${r})$`)}const vi=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},yi=/^\d+$/,bi=/^-?\d+(?:\.\d+)?/i,xi=/true|false/i,Si=/null/i,Ci=/^[^A-Z]*$/,wi=/^[^a-z]*$/,Ti=/*@__PURE__*/ O(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ei={number:`number`,bigint:`bigint`,object:`date`},Di=/*@__PURE__*/ O(`$ZodCheckLessThan`,(e,t)=>{Ti.init(e,t);let n=Ei[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Oi=/*@__PURE__*/ O(`$ZodCheckGreaterThan`,(e,t)=>{Ti.init(e,t);let n=Ei[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ki=/*@__PURE__*/ O(`$ZodCheckMultipleOf`,(e,t)=>{Ti.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):pr(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ai=/*@__PURE__*/ O(`$ZodCheckNumberFormat`,(e,t)=>{Ti.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=wr[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=yi)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),ji=/*@__PURE__*/ O(`$ZodCheckMaxLength`,(e,t)=>{var n;Ti.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!dr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Fr(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Mi=/*@__PURE__*/ O(`$ZodCheckMinLength`,(e,t)=>{var n;Ti.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!dr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Fr(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ni=/*@__PURE__*/ O(`$ZodCheckLengthEquals`,(e,t)=>{var n;Ti.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!dr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Fr(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Pi=/*@__PURE__*/ O(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Ti.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=/* @__PURE__ */ new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Fi=/*@__PURE__*/ O(`$ZodCheckRegex`,(e,t)=>{Pi.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ii=/*@__PURE__*/ O(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Ci,Pi.init(e,t)}),Li=/*@__PURE__*/ O(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=wi,Pi.init(e,t)}),Ri=/*@__PURE__*/ O(`$ZodCheckIncludes`,(e,t)=>{Ti.init(e,t);let n=xr(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),zi=/*@__PURE__*/ O(`$ZodCheckStartsWith`,(e,t)=>{Ti.init(e,t);let n=RegExp(`^${xr(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Bi=/*@__PURE__*/ O(`$ZodCheckEndsWith`,(e,t)=>{Ti.init(e,t);let n=RegExp(`.*${xr(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Vi=/*@__PURE__*/ O(`$ZodCheckOverwrite`,(e,t)=>{Ti.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Hi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
5
|
+
`),d=`ACS3-HMAC-SHA256`,f=`${d}\n${Gn(u)}`,p=Kn(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function Wn(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Gn(e){return te(`sha256`).update(e,`utf8`).digest(`hex`)}function Kn(e,t){return ne(`sha256`,e).update(t,`utf8`).digest(`hex`)}const qn=[`cn-beijing`,`ap-southeast-1`];function Jn(e){return new O(`Local-file temporary upload is supported only in ${qn.join(`, `)}; "${e}" is not supported.`,D.USAGE,`Use a reachable HTTPS media URL instead.`)}function Yn(e){if(mn(e)===`token-plan`)throw Jn(`Token Plan`)}function Xn(e,t){let n=st(e),r=new URL(n).hostname.toLowerCase();if(/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/.test(r))throw Jn(`Token Plan`);if(r===new URL(lt.cn).hostname||r===new URL(lt.intl).hostname)return Yn(t),n;if(r===new URL(lt.us).hostname)throw Jn(r);let i=/^[^.]+\.([a-z0-9-]+)\.maas\.aliyuncs\.com$/.exec(r)?.[1];if(i===`cn-beijing`||i===`ap-southeast-1`)return Yn(t),n;if(i)throw Jn(i);return n}async function Zn(e,t,n,r,i){let a=`${Xn(r,e)}/api/v1/uploads`,o=`${a}?action=getPolicy&model=${encodeURIComponent(t)}`,s=cr(15e3,i),c=await Sn.fetch(o,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...Pn(n)},signal:s.signal}).finally(s.cleanup);if(!c.ok){let e=await c.text().catch(()=>``),t;try{t=JSON.parse(e)}catch{}let n=typeof t?.message==`string`&&t.message?t.message:e||`${c.status} ${c.statusText}`,r=typeof t?.code==`string`?t.code:void 0,i=typeof t?.request_id==`string`?t.request_id:void 0;throw new O(`${[`HTTP ${c.status}`,r?`code=${r}`:void 0,i?`request_id=${i}`:void 0,`upload_endpoint=${a}`].filter(e=>e!==void 0).join(`; `)} - ${n}`,D.GENERAL,void 0,{api:{httpStatus:c.status,apiCode:r,requestId:i},rawResponse:e.slice(0,500)})}return(await c.json()).data}async function Qn(e,t,n,r=120){let i=m(t),a=`${e.upload_dir}/${i}`,s=o(t),c=new FormData;c.append(`OSSAccessKeyId`,e.oss_access_key_id),c.append(`Signature`,e.signature),c.append(`policy`,e.policy),c.append(`x-oss-object-acl`,e.x_oss_object_acl),c.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),c.append(`key`,a),c.append(`success_action_status`,`200`),c.append(`file`,new Blob([s]),i);let l=cr(r*1e3,n),u=await Sn.fetch(e.upload_host,{method:`POST`,body:c,signal:l.signal}).finally(l.cleanup);if(!u.ok){let e=await u.text().catch(()=>``);throw new O(`Failed to upload file to OSS (HTTP ${u.status}): ${e}`,D.GENERAL)}return`oss://${a}`}const $n={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`},er={".aac":`audio/aac`,".amr":`audio/amr`,".flac":`audio/flac`,".m4a":`audio/mp4`,".mp3":`audio/mpeg`,".oga":`audio/ogg`,".ogg":`audio/ogg`,".opus":`audio/opus`,".wav":`audio/wav`,".weba":`audio/webm`,".wma":`audio/x-ms-wma`};function tr(e,t,n){if(!i(e))throw new O(`File not found: ${e}`,D.USAGE);if(!l(e).isFile())throw new O(`Not a file: ${e}`,D.USAGE);let r=h(e).toLowerCase(),a=t[r];if(!a)throw new O(`Unsupported ${n} format "${r||`unknown`}".`,D.USAGE,`Use an ${n} file with a recognized extension.`);return`data:${a};base64,${o(e).toString(`base64`)}`}function nr(e){return tr(e,$n,`image`)}function rr(e){return tr(e,er,`audio`)}function ir(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function ar(e){let{apiKey:t,baseUrl:n=lt.cn,model:r,filePath:a,identity:o,signal:s,timeout:c}=e;if(!i(a))throw new O(`File not found: ${a}`,D.USAGE);if(!l(a).isFile())throw new O(`Not a file: ${a}`,D.USAGE);return Qn(await Zn(t,r,o,n,s),a,s,c)}function or(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function sr(e,t,n,r){return or(e)?ar({apiKey:t,baseUrl:r.baseUrl,model:n,filePath:e,identity:r.identity,signal:r.signal,timeout:r.timeout}):e}function cr(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}const lr=Object.freeze({status:`aborted`});function k(e,t,n){function r(n,r){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=/* @__PURE__ */ new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var ur=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};const dr={};function fr(e){return e&&Object.assign(dr,e),dr}function pr(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function mr(e,t){return typeof t==`bigint`?t.toString():t}function hr(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function gr(e){return e==null}function _r(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function vr(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function A(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function br(e){return JSON.stringify(e)}const xr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Sr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Cr=hr(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function wr(e){if(Sr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return Sr(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}const Tr=/* @__PURE__ */ new Set([`string`,`number`,`symbol`]);function Er(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Dr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Or(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const kr={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ar(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return Dr(e,{...e._zod.def,shape:n,checks:[]})}function jr(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return Dr(e,{...e._zod.def,shape:n,checks:[]})}function Mr(e,t){if(!wr(t))throw Error(`Invalid input to extend: expected a plain object`);return Dr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return yr(this,`shape`,n),n},checks:[]})}function Nr(e,t){return Dr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return yr(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function Pr(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Dr(t,{...t._zod.def,shape:i,checks:[]})}function Fr(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Dr(t,{...t._zod.def,shape:i,checks:[]})}function Ir(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Lr(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Rr(e){return typeof e==`string`?e:e?.message}function zr(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=Rr(e.inst?._zod.def?.error?.(e))??Rr(t?.error?.(e))??Rr(n.customError?.(e))??Rr(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Br(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Vr(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const Hr=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,mr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ur=k(`$ZodError`,Hr),Wr=k(`$ZodError`,Hr,{Parent:Error});function Gr(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Kr(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const qr=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new ur;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>zr(e,a,fr())));throw xr(t,i?.callee),t}return o.value},Jr=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>zr(e,a,fr())));throw xr(t,i?.callee),t}return o.value},Yr=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new ur;return a.issues.length?{success:!1,error:new(e??Ur)(a.issues.map(e=>zr(e,i,fr())))}:{success:!0,data:a.value}},Xr=/* @__PURE__*/ Yr(Wr),Zr=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>zr(e,i,fr())))}:{success:!0,data:a.value}},Qr=/* @__PURE__*/ Zr(Wr),$r=/^[cC][^\s-]{8,}$/,ei=/^[0-9a-z]+$/,ti=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ni=/^[0-9a-vA-V]{20}$/,ri=/^[A-Za-z0-9]{27}$/,ii=/^[a-zA-Z0-9_-]{21}$/,ai=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oi=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,si=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,ci=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function li(){return/* @__PURE__ */ RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const ui=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,di=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,fi=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,pi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,mi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hi=/^[A-Za-z0-9_-]*$/,gi=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,_i=/^\+(?:[0-9]){6,14}[0-9]$/,vi=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,yi=/*@__PURE__*/ RegExp(`^${vi}$`);function bi(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function xi(e){return RegExp(`^${bi(e)}$`)}function Si(e){let t=bi({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${vi}T(?:${r})$`)}const Ci=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},wi=/^\d+$/,Ti=/^-?\d+(?:\.\d+)?/i,Ei=/true|false/i,Di=/null/i,Oi=/^[^A-Z]*$/,ki=/^[^a-z]*$/,Ai=/*@__PURE__*/ k(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ji={number:`number`,bigint:`bigint`,object:`date`},Mi=/*@__PURE__*/ k(`$ZodCheckLessThan`,(e,t)=>{Ai.init(e,t);let n=ji[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ni=/*@__PURE__*/ k(`$ZodCheckGreaterThan`,(e,t)=>{Ai.init(e,t);let n=ji[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Pi=/*@__PURE__*/ k(`$ZodCheckMultipleOf`,(e,t)=>{Ai.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):vr(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Fi=/*@__PURE__*/ k(`$ZodCheckNumberFormat`,(e,t)=>{Ai.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=kr[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=wi)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),Ii=/*@__PURE__*/ k(`$ZodCheckMaxLength`,(e,t)=>{var n;Ai.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=Br(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Li=/*@__PURE__*/ k(`$ZodCheckMinLength`,(e,t)=>{var n;Ai.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Br(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ri=/*@__PURE__*/ k(`$ZodCheckLengthEquals`,(e,t)=>{var n;Ai.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Br(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),zi=/*@__PURE__*/ k(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Ai.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=/* @__PURE__ */ new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Bi=/*@__PURE__*/ k(`$ZodCheckRegex`,(e,t)=>{zi.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vi=/*@__PURE__*/ k(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Oi,zi.init(e,t)}),Hi=/*@__PURE__*/ k(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=ki,zi.init(e,t)}),Ui=/*@__PURE__*/ k(`$ZodCheckIncludes`,(e,t)=>{Ai.init(e,t);let n=Er(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Wi=/*@__PURE__*/ k(`$ZodCheckStartsWith`,(e,t)=>{Ai.init(e,t);let n=RegExp(`^${Er(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Gi=/*@__PURE__*/ k(`$ZodCheckEndsWith`,(e,t)=>{Ai.init(e,t);let n=RegExp(`.*${Er(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ki=/*@__PURE__*/ k(`$ZodCheckOverwrite`,(e,t)=>{Ai.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var qi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
6
6
|
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
7
|
-
`))}};const
|
|
7
|
+
`))}};const Ji={major:4,minor:0,patch:0},M=/*@__PURE__*/ k(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ji;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Ir(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new ur;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Ir(e,t))});else{if(e.issues.length===t)continue;r||=Ir(e,t)}}return i?i.then(()=>e):e};e._zod.run=(n,i)=>{let a=e._zod.parse(n,i);if(a instanceof Promise){if(i.async===!1)throw new ur;return a.then(e=>t(e,r,i))}return t(a,r,i)}}e[`~standard`]={validate:t=>{try{let n=Xr(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Qr(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),Yi=/*@__PURE__*/ k(`$ZodString`,(e,t)=>{M.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ci(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),N=/*@__PURE__*/ k(`$ZodStringFormat`,(e,t)=>{zi.init(e,t),Yi.init(e,t)}),Xi=/*@__PURE__*/ k(`$ZodGUID`,(e,t)=>{t.pattern??=oi,N.init(e,t)}),Zi=/*@__PURE__*/ k(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=si(e)}else t.pattern??=si();N.init(e,t)}),Qi=/*@__PURE__*/ k(`$ZodEmail`,(e,t)=>{t.pattern??=ci,N.init(e,t)}),$i=/*@__PURE__*/ k(`$ZodURL`,(e,t)=>{N.init(e,t),e._zod.check=n=>{try{let r=n.value,i=new URL(r),a=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:gi.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=!r.endsWith(`/`)&&a.endsWith(`/`)?a.slice(0,-1):a;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),ea=/*@__PURE__*/ k(`$ZodEmoji`,(e,t)=>{t.pattern??=li(),N.init(e,t)}),ta=/*@__PURE__*/ k(`$ZodNanoID`,(e,t)=>{t.pattern??=ii,N.init(e,t)}),na=/*@__PURE__*/ k(`$ZodCUID`,(e,t)=>{t.pattern??=$r,N.init(e,t)}),ra=/*@__PURE__*/ k(`$ZodCUID2`,(e,t)=>{t.pattern??=ei,N.init(e,t)}),ia=/*@__PURE__*/ k(`$ZodULID`,(e,t)=>{t.pattern??=ti,N.init(e,t)}),aa=/*@__PURE__*/ k(`$ZodXID`,(e,t)=>{t.pattern??=ni,N.init(e,t)}),oa=/*@__PURE__*/ k(`$ZodKSUID`,(e,t)=>{t.pattern??=ri,N.init(e,t)}),sa=/*@__PURE__*/ k(`$ZodISODateTime`,(e,t)=>{t.pattern??=Si(t),N.init(e,t)}),ca=/*@__PURE__*/ k(`$ZodISODate`,(e,t)=>{t.pattern??=yi,N.init(e,t)}),la=/*@__PURE__*/ k(`$ZodISOTime`,(e,t)=>{t.pattern??=xi(t),N.init(e,t)}),ua=/*@__PURE__*/ k(`$ZodISODuration`,(e,t)=>{t.pattern??=ai,N.init(e,t)}),da=/*@__PURE__*/ k(`$ZodIPv4`,(e,t)=>{t.pattern??=ui,N.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),fa=/*@__PURE__*/ k(`$ZodIPv6`,(e,t)=>{t.pattern??=di,N.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv6`}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),pa=/*@__PURE__*/ k(`$ZodCIDRv4`,(e,t)=>{t.pattern??=fi,N.init(e,t)}),ma=/*@__PURE__*/ k(`$ZodCIDRv6`,(e,t)=>{t.pattern??=pi,N.init(e,t),e._zod.check=n=>{let[r,i]=n.value.split(`/`);try{if(!i)throw Error();let e=Number(i);if(`${e}`!==i||e<0||e>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function ha(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const ga=/*@__PURE__*/ k(`$ZodBase64`,(e,t)=>{t.pattern??=mi,N.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{ha(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function _a(e){if(!hi.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return ha(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const va=/*@__PURE__*/ k(`$ZodBase64URL`,(e,t)=>{t.pattern??=hi,N.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{_a(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),ya=/*@__PURE__*/ k(`$ZodE164`,(e,t)=>{t.pattern??=_i,N.init(e,t)});function ba(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const xa=/*@__PURE__*/ k(`$ZodJWT`,(e,t)=>{N.init(e,t),e._zod.check=n=>{ba(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Sa=/*@__PURE__*/ k(`$ZodNumber`,(e,t)=>{M.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ti,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ca=/*@__PURE__*/ k(`$ZodNumber`,(e,t)=>{Fi.init(e,t),Sa.init(e,t)}),wa=/*@__PURE__*/ k(`$ZodBoolean`,(e,t)=>{M.init(e,t),e._zod.pattern=Ei,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ta=/*@__PURE__*/ k(`$ZodNull`,(e,t)=>{M.init(e,t),e._zod.pattern=Di,e._zod.values=/* @__PURE__ */ new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Ea=/*@__PURE__*/ k(`$ZodAny`,(e,t)=>{M.init(e,t),e._zod.parse=e=>e}),Da=/*@__PURE__*/ k(`$ZodUnknown`,(e,t)=>{M.init(e,t),e._zod.parse=e=>e}),Oa=/*@__PURE__*/ k(`$ZodNever`,(e,t)=>{M.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ka(e,t,n){e.issues.length&&t.issues.push(...Lr(n,e.issues)),t.value[n]=e.value}const Aa=/*@__PURE__*/ k(`$ZodArray`,(e,t)=>{M.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>ka(t,n,e))):ka(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function ja(e,t,n){e.issues.length&&t.issues.push(...Lr(n,e.issues)),t.value[n]=e.value}function Ma(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...Lr(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Na=/*@__PURE__*/ k(`$ZodObject`,(e,t)=>{M.init(e,t);let n=hr(()=>{let e=Object.keys(t.shape);for(let n of e)if(!(t.shape[n]instanceof M))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Or(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});A(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */ new Set);for(let e of r.values)n[t].add(e)}}return n});let r=e=>{let t=new qi([`shape`,`payload`,`ctx`]),r=n.value,i=e=>{let t=br(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of r.keys)a[e]=`key_${o++}`;t.write(`const newResult = {}`);for(let e of r.keys)if(r.optionalKeys.has(e)){let n=a[e];t.write(`const ${n} = ${i(e)};`);let r=br(e);t.write(`
|
|
8
8
|
if (${n}.issues.length) {
|
|
9
9
|
if (input[${r}] === undefined) {
|
|
10
10
|
if (${r} in input) {
|
|
@@ -26,74 +26,73 @@ import{createRequire as e}from"node:module";import{appendFileSync as t,createRea
|
|
|
26
26
|
`)}else{let n=a[e];t.write(`const ${n} = ${i(e)};`),t.write(`
|
|
27
27
|
if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
28
28
|
...iss,
|
|
29
|
-
path: iss.path ? [${
|
|
30
|
-
})));`),t.write(`newResult[${hr(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=_r,o=!or.jitless,s=o&&vr.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??=n.value;let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||=r(t.shape),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?Da(e,u,t,f):Ea(e,u,t))):i?Da(r,u,t,f):Ea(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>Ea(t,u,e))):Ea(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function ka(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Pr(e,r,sr())))}),t}const Aa=/*@__PURE__*/ O(`$ZodUnion`,(e,t)=>{j.init(e,t),k(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),k(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),k(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),k(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>fr(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>ka(t,n,e,r)):ka(a,n,e,r)}}),ja=/*@__PURE__*/ O(`$ZodDiscriminatedUnion`,(e,t)=>{Aa.init(e,t);let n=e._zod.parse;k(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=/* @__PURE__ */ new Set);for(let r of n)e[t].add(r)}}return e});let r=ur(()=>{let e=t.options,n=/* @__PURE__ */ new Map;for(let r of e){let e=r._zod.propValues[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!_r(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,input:o,path:[t.discriminator],inst:e}),i)}}),Ma=/*@__PURE__*/ O(`$ZodIntersection`,(e,t)=>{j.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Pa(e,t,n)):Pa(e,i,a)}});function Na(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(yr(e)&&yr(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Na(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Na(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Pa(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),jr(e))return e;let r=Na(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const Fa=/*@__PURE__*/ O(`$ZodRecord`,(e,t)=>{j.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!yr(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...Mr(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...Mr(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>Pr(e,r,sr())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Mr(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Mr(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Ia=/*@__PURE__*/ O(`$ZodEnum`,(e,t)=>{j.init(e,t);let n=cr(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>br.has(typeof e)).map(e=>typeof e==`string`?xr(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),La=/*@__PURE__*/ O(`$ZodLiteral`,(e,t)=>{j.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?xr(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),Ra=/*@__PURE__*/ O(`$ZodTransform`,(e,t)=>{j.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new ar;return e.value=r,e}}),za=/*@__PURE__*/ O(`$ZodOptional`,(e,t)=>{j.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,k(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,void 0]):void 0),k(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${fr(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),Ba=/*@__PURE__*/ O(`$ZodNullable`,(e,t)=>{j.init(e,t),k(e._zod,`optin`,()=>t.innerType._zod.optin),k(e._zod,`optout`,()=>t.innerType._zod.optout),k(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${fr(e.source)}|null)$`):void 0}),k(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Va=/*@__PURE__*/ O(`$ZodDefault`,(e,t)=>{j.init(e,t),e._zod.optin=`optional`,k(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Ha(e,t)):Ha(r,t)}});function Ha(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Ua=/*@__PURE__*/ O(`$ZodPrefault`,(e,t)=>{j.init(e,t),e._zod.optin=`optional`,k(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Wa=/*@__PURE__*/ O(`$ZodNonOptional`,(e,t)=>{j.init(e,t),k(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Ga(t,e)):Ga(i,e)}});function Ga(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const Ka=/*@__PURE__*/ O(`$ZodCatch`,(e,t)=>{j.init(e,t),e._zod.optin=`optional`,k(e._zod,`optout`,()=>t.innerType._zod.optout),k(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Pr(e,n,sr()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Pr(e,n,sr()))},input:e.value}),e.issues=[]),e)}}),qa=/*@__PURE__*/ O(`$ZodPipe`,(e,t)=>{j.init(e,t),k(e._zod,`values`,()=>t.in._zod.values),k(e._zod,`optin`,()=>t.in._zod.optin),k(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ja(e,t,n)):Ja(r,t,n)}});function Ja(e,t,n){return jr(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Ya=/*@__PURE__*/ O(`$ZodReadonly`,(e,t)=>{j.init(e,t),k(e._zod,`propValues`,()=>t.innerType._zod.propValues),k(e._zod,`values`,()=>t.innerType._zod.values),k(e._zod,`optin`,()=>t.innerType._zod.optin),k(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Xa):Xa(r)}});function Xa(e){return e.value=Object.freeze(e.value),e}const Za=/*@__PURE__*/ O(`$ZodCustom`,(e,t)=>{Ti.init(e,t),j.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Qa(t,n,r,e));Qa(i,n,r,e)}});function Qa(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Ir(e))}}var $a=class{constructor(){this._map=/* @__PURE__ */ new Map,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=/* @__PURE__ */ new Map,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function eo(){return new $a}const to=/*@__PURE__*/ eo();function no(e,t){return new e({type:`string`,...A(t)})}function ro(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...A(t)})}function io(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...A(t)})}function ao(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...A(t)})}function oo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...A(t)})}function so(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...A(t)})}function co(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...A(t)})}function lo(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...A(t)})}function uo(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...A(t)})}function fo(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...A(t)})}function po(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...A(t)})}function mo(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...A(t)})}function ho(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...A(t)})}function go(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...A(t)})}function _o(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...A(t)})}function vo(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...A(t)})}function yo(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...A(t)})}function bo(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...A(t)})}function xo(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...A(t)})}function So(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...A(t)})}function Co(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...A(t)})}function wo(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...A(t)})}function To(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...A(t)})}function Eo(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...A(t)})}function Do(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...A(t)})}function Oo(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...A(t)})}function ko(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...A(t)})}function Ao(e,t){return new e({type:`number`,checks:[],...A(t)})}function jo(e,t){return new e({type:`number`,coerce:!0,checks:[],...A(t)})}function Mo(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...A(t)})}function No(e,t){return new e({type:`boolean`,...A(t)})}function Po(e,t){return new e({type:`null`,...A(t)})}function Fo(e){return new e({type:`any`})}function Io(e){return new e({type:`unknown`})}function Lo(e,t){return new e({type:`never`,...A(t)})}function Ro(e,t){return new Di({check:`less_than`,...A(t),value:e,inclusive:!1})}function zo(e,t){return new Di({check:`less_than`,...A(t),value:e,inclusive:!0})}function Bo(e,t){return new Oi({check:`greater_than`,...A(t),value:e,inclusive:!1})}function Vo(e,t){return new Oi({check:`greater_than`,...A(t),value:e,inclusive:!0})}function Ho(e,t){return new ki({check:`multiple_of`,...A(t),value:e})}function Uo(e,t){return new ji({check:`max_length`,...A(t),maximum:e})}function Wo(e,t){return new Mi({check:`min_length`,...A(t),minimum:e})}function Go(e,t){return new Ni({check:`length_equals`,...A(t),length:e})}function Ko(e,t){return new Fi({check:`string_format`,format:`regex`,...A(t),pattern:e})}function qo(e){return new Ii({check:`string_format`,format:`lowercase`,...A(e)})}function Jo(e){return new Li({check:`string_format`,format:`uppercase`,...A(e)})}function Yo(e,t){return new Ri({check:`string_format`,format:`includes`,...A(t),includes:e})}function Xo(e,t){return new zi({check:`string_format`,format:`starts_with`,...A(t),prefix:e})}function Zo(e,t){return new Bi({check:`string_format`,format:`ends_with`,...A(t),suffix:e})}function Qo(e){return new Vi({check:`overwrite`,tx:e})}function $o(e){return Qo(t=>t.normalize(e))}function es(){return Qo(e=>e.trim())}function ts(){return Qo(e=>e.toLowerCase())}function ns(){return Qo(e=>e.toUpperCase())}function rs(e,t,n){return new e({type:`array`,element:t,...A(n)})}function is(e,t,n){let r=A(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function as(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...A(n)})}function os(e){return!!e._zod}function ss(e,t){return os(e)?Gr(e,t):e.safeParse(t)}function cs(e){if(!e)return;let t;if(t=os(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function ls(e){if(os(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const us=/*@__PURE__*/ O(`ZodISODateTime`,(e,t)=>{na.init(e,t),F.init(e,t)});function ds(e){return Eo(us,e)}const fs=/*@__PURE__*/ O(`ZodISODate`,(e,t)=>{ra.init(e,t),F.init(e,t)});function ps(e){return Do(fs,e)}const ms=/*@__PURE__*/ O(`ZodISOTime`,(e,t)=>{ia.init(e,t),F.init(e,t)});function hs(e){return Oo(ms,e)}const gs=/*@__PURE__*/ O(`ZodISODuration`,(e,t)=>{aa.init(e,t),F.init(e,t)});function _s(e){return ko(gs,e)}const vs=(e,t)=>{Rr.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Vr(e,t)},flatten:{value:t=>Br(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})};O(`ZodError`,vs);const ys=O(`ZodError`,vs,{Parent:Error}),bs=/* @__PURE__ */ Hr(ys),xs=/* @__PURE__ */ Ur(ys),Ss=/* @__PURE__ */ Wr(ys),Cs=/* @__PURE__ */ Kr(ys),N=/*@__PURE__*/ O(`ZodType`,(e,t)=>(j.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>Sr(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>bs(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ss(e,t,n),e.parseAsync=async(t,n)=>xs(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Cs(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(Fc(t,n)),e.superRefine=t=>e.check(Ic(t)),e.overwrite=t=>e.check(Qo(t)),e.optional=()=>W(e),e.nullable=()=>yc(e),e.nullish=()=>W(yc(e)),e.nonoptional=t=>Tc(e,t),e.array=()=>z(e),e.or=t=>V([e,t]),e.and=t=>uc(e,t),e.transform=t=>kc(e,gc(t)),e.default=t=>xc(e,t),e.prefault=t=>Cc(e,t),e.catch=t=>Dc(e,t),e.pipe=t=>kc(e,t),e.readonly=()=>jc(e),e.describe=t=>{let n=e.clone();return to.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return to.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return to.get(e);let n=e.clone();return to.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),ws=/*@__PURE__*/ O(`_ZodString`,(e,t)=>{Wi.init(e,t),N.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Ko(...t)),e.includes=(...t)=>e.check(Yo(...t)),e.startsWith=(...t)=>e.check(Xo(...t)),e.endsWith=(...t)=>e.check(Zo(...t)),e.min=(...t)=>e.check(Wo(...t)),e.max=(...t)=>e.check(Uo(...t)),e.length=(...t)=>e.check(Go(...t)),e.nonempty=(...t)=>e.check(Wo(1,...t)),e.lowercase=t=>e.check(qo(t)),e.uppercase=t=>e.check(Jo(t)),e.trim=()=>e.check(es()),e.normalize=(...t)=>e.check($o(...t)),e.toLowerCase=()=>e.check(ts()),e.toUpperCase=()=>e.check(ns())}),Ts=/*@__PURE__*/ O(`ZodString`,(e,t)=>{Wi.init(e,t),ws.init(e,t),e.email=t=>e.check(ro(Es,t)),e.url=t=>e.check(lo(ks,t)),e.jwt=t=>e.check(To(Gs,t)),e.emoji=t=>e.check(uo(js,t)),e.guid=t=>e.check(io(Ds,t)),e.uuid=t=>e.check(ao(Os,t)),e.uuidv4=t=>e.check(oo(Os,t)),e.uuidv6=t=>e.check(so(Os,t)),e.uuidv7=t=>e.check(co(Os,t)),e.nanoid=t=>e.check(fo(Ms,t)),e.guid=t=>e.check(io(Ds,t)),e.cuid=t=>e.check(po(Ns,t)),e.cuid2=t=>e.check(mo(Ps,t)),e.ulid=t=>e.check(ho(Fs,t)),e.base64=t=>e.check(So(Hs,t)),e.base64url=t=>e.check(Co(Us,t)),e.xid=t=>e.check(go(Is,t)),e.ksuid=t=>e.check(_o(Ls,t)),e.ipv4=t=>e.check(vo(Rs,t)),e.ipv6=t=>e.check(yo(zs,t)),e.cidrv4=t=>e.check(bo(Bs,t)),e.cidrv6=t=>e.check(xo(Vs,t)),e.e164=t=>e.check(wo(Ws,t)),e.datetime=t=>e.check(ds(t)),e.date=t=>e.check(ps(t)),e.time=t=>e.check(hs(t)),e.duration=t=>e.check(_s(t))});function P(e){return no(Ts,e)}const F=/*@__PURE__*/ O(`ZodStringFormat`,(e,t)=>{M.init(e,t),ws.init(e,t)}),Es=/*@__PURE__*/ O(`ZodEmail`,(e,t)=>{qi.init(e,t),F.init(e,t)}),Ds=/*@__PURE__*/ O(`ZodGUID`,(e,t)=>{Gi.init(e,t),F.init(e,t)}),Os=/*@__PURE__*/ O(`ZodUUID`,(e,t)=>{Ki.init(e,t),F.init(e,t)}),ks=/*@__PURE__*/ O(`ZodURL`,(e,t)=>{Ji.init(e,t),F.init(e,t)});function As(e){return lo(ks,e)}const js=/*@__PURE__*/ O(`ZodEmoji`,(e,t)=>{Yi.init(e,t),F.init(e,t)}),Ms=/*@__PURE__*/ O(`ZodNanoID`,(e,t)=>{Xi.init(e,t),F.init(e,t)}),Ns=/*@__PURE__*/ O(`ZodCUID`,(e,t)=>{Zi.init(e,t),F.init(e,t)}),Ps=/*@__PURE__*/ O(`ZodCUID2`,(e,t)=>{Qi.init(e,t),F.init(e,t)}),Fs=/*@__PURE__*/ O(`ZodULID`,(e,t)=>{$i.init(e,t),F.init(e,t)}),Is=/*@__PURE__*/ O(`ZodXID`,(e,t)=>{ea.init(e,t),F.init(e,t)}),Ls=/*@__PURE__*/ O(`ZodKSUID`,(e,t)=>{ta.init(e,t),F.init(e,t)}),Rs=/*@__PURE__*/ O(`ZodIPv4`,(e,t)=>{oa.init(e,t),F.init(e,t)}),zs=/*@__PURE__*/ O(`ZodIPv6`,(e,t)=>{sa.init(e,t),F.init(e,t)}),Bs=/*@__PURE__*/ O(`ZodCIDRv4`,(e,t)=>{ca.init(e,t),F.init(e,t)}),Vs=/*@__PURE__*/ O(`ZodCIDRv6`,(e,t)=>{la.init(e,t),F.init(e,t)}),Hs=/*@__PURE__*/ O(`ZodBase64`,(e,t)=>{da.init(e,t),F.init(e,t)}),Us=/*@__PURE__*/ O(`ZodBase64URL`,(e,t)=>{pa.init(e,t),F.init(e,t)}),Ws=/*@__PURE__*/ O(`ZodE164`,(e,t)=>{ma.init(e,t),F.init(e,t)}),Gs=/*@__PURE__*/ O(`ZodJWT`,(e,t)=>{ga.init(e,t),F.init(e,t)}),Ks=/*@__PURE__*/ O(`ZodNumber`,(e,t)=>{_a.init(e,t),N.init(e,t),e.gt=(t,n)=>e.check(Bo(t,n)),e.gte=(t,n)=>e.check(Vo(t,n)),e.min=(t,n)=>e.check(Vo(t,n)),e.lt=(t,n)=>e.check(Ro(t,n)),e.lte=(t,n)=>e.check(zo(t,n)),e.max=(t,n)=>e.check(zo(t,n)),e.int=t=>e.check(Js(t)),e.safe=t=>e.check(Js(t)),e.positive=t=>e.check(Bo(0,t)),e.nonnegative=t=>e.check(Vo(0,t)),e.negative=t=>e.check(Ro(0,t)),e.nonpositive=t=>e.check(zo(0,t)),e.multipleOf=(t,n)=>e.check(Ho(t,n)),e.step=(t,n)=>e.check(Ho(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function I(e){return Ao(Ks,e)}const qs=/*@__PURE__*/ O(`ZodNumberFormat`,(e,t)=>{va.init(e,t),Ks.init(e,t)});function Js(e){return Mo(qs,e)}const Ys=/*@__PURE__*/ O(`ZodBoolean`,(e,t)=>{ya.init(e,t),N.init(e,t)});function L(e){return No(Ys,e)}const Xs=/*@__PURE__*/ O(`ZodNull`,(e,t)=>{ba.init(e,t),N.init(e,t)});function Zs(e){return Po(Xs,e)}const Qs=/*@__PURE__*/ O(`ZodAny`,(e,t)=>{xa.init(e,t),N.init(e,t)});function $s(){return Fo(Qs)}const ec=/*@__PURE__*/ O(`ZodUnknown`,(e,t)=>{Sa.init(e,t),N.init(e,t)});function R(){return Io(ec)}const tc=/*@__PURE__*/ O(`ZodNever`,(e,t)=>{Ca.init(e,t),N.init(e,t)});function nc(e){return Lo(tc,e)}const rc=/*@__PURE__*/ O(`ZodArray`,(e,t)=>{Ta.init(e,t),N.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Wo(t,n)),e.nonempty=t=>e.check(Wo(1,t)),e.max=(t,n)=>e.check(Uo(t,n)),e.length=(t,n)=>e.check(Go(t,n)),e.unwrap=()=>e.element});function z(e,t){return rs(rc,e,t)}const ic=/*@__PURE__*/ O(`ZodObject`,(e,t)=>{Oa.init(e,t),N.init(e,t),k(e,`shape`,()=>t.shape),e.keyof=()=>pc(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:R()}),e.loose=()=>e.clone({...e._zod.def,catchall:R()}),e.strict=()=>e.clone({...e._zod.def,catchall:nc()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Dr(e,t),e.merge=t=>Or(e,t),e.pick=t=>Tr(e,t),e.omit=t=>Er(e,t),e.partial=(...t)=>kr(_c,e,t[0]),e.required=(...t)=>Ar(wc,e,t[0])});function B(e,t){let n={type:`object`,get shape(){return mr(this,`shape`,{...e}),this.shape},...A(t)};return new ic(n)}function ac(e,t){return new ic({type:`object`,get shape(){return mr(this,`shape`,{...e}),this.shape},catchall:R(),...A(t)})}const oc=/*@__PURE__*/ O(`ZodUnion`,(e,t)=>{Aa.init(e,t),N.init(e,t),e.options=t.options});function V(e,t){return new oc({type:`union`,options:e,...A(t)})}const sc=/*@__PURE__*/ O(`ZodDiscriminatedUnion`,(e,t)=>{oc.init(e,t),ja.init(e,t)});function cc(e,t,n){return new sc({type:`union`,options:t,discriminator:e,...A(n)})}const lc=/*@__PURE__*/ O(`ZodIntersection`,(e,t)=>{Ma.init(e,t),N.init(e,t)});function uc(e,t){return new lc({type:`intersection`,left:e,right:t})}const dc=/*@__PURE__*/ O(`ZodRecord`,(e,t)=>{Fa.init(e,t),N.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function H(e,t,n){return new dc({type:`record`,keyType:e,valueType:t,...A(n)})}const fc=/*@__PURE__*/ O(`ZodEnum`,(e,t)=>{Ia.init(e,t),N.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new fc({...t,checks:[],...A(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new fc({...t,checks:[],...A(r),entries:i})}});function pc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new fc({type:`enum`,entries:n,...A(t)})}const mc=/*@__PURE__*/ O(`ZodLiteral`,(e,t)=>{La.init(e,t),N.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function U(e,t){return new mc({type:`literal`,values:Array.isArray(e)?e:[e],...A(t)})}const hc=/*@__PURE__*/ O(`ZodTransform`,(e,t)=>{Ra.init(e,t),N.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Ir(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(Ir(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function gc(e){return new hc({type:`transform`,transform:e})}const _c=/*@__PURE__*/ O(`ZodOptional`,(e,t)=>{za.init(e,t),N.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W(e){return new _c({type:`optional`,innerType:e})}const vc=/*@__PURE__*/ O(`ZodNullable`,(e,t)=>{Ba.init(e,t),N.init(e,t),e.unwrap=()=>e._zod.def.innerType});function yc(e){return new vc({type:`nullable`,innerType:e})}const bc=/*@__PURE__*/ O(`ZodDefault`,(e,t)=>{Va.init(e,t),N.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function xc(e,t){return new bc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const Sc=/*@__PURE__*/ O(`ZodPrefault`,(e,t)=>{Ua.init(e,t),N.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Cc(e,t){return new Sc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const wc=/*@__PURE__*/ O(`ZodNonOptional`,(e,t)=>{Wa.init(e,t),N.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Tc(e,t){return new wc({type:`nonoptional`,innerType:e,...A(t)})}const Ec=/*@__PURE__*/ O(`ZodCatch`,(e,t)=>{Ka.init(e,t),N.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Dc(e,t){return new Ec({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const Oc=/*@__PURE__*/ O(`ZodPipe`,(e,t)=>{qa.init(e,t),N.init(e,t),e.in=t.in,e.out=t.out});function kc(e,t){return new Oc({type:`pipe`,in:e,out:t})}const Ac=/*@__PURE__*/ O(`ZodReadonly`,(e,t)=>{Ya.init(e,t),N.init(e,t)});function jc(e){return new Ac({type:`readonly`,innerType:e})}const Mc=/*@__PURE__*/ O(`ZodCustom`,(e,t)=>{Za.init(e,t),N.init(e,t)});function Nc(e){let t=new Ti({check:`custom`});return t._zod.check=e,t}function Pc(e,t){return is(Mc,e??(()=>!0),t)}function Fc(e,t={}){return as(Mc,e,t)}function Ic(e){let t=Nc(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(Ir(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(Ir(r))}},e(n.value,n)));return t}function Lc(e,t){return kc(gc(e),t)}const Rc={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};function zc(e){return jo(Ks,e)}const Bc=`2025-11-25`,Vc=[Bc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Hc=`io.modelcontextprotocol/related-task`,Uc=Pc(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Wc=V([P(),I().int()]),Gc=P();ac({ttl:I().optional(),pollInterval:I().optional()});const Kc=B({ttl:I().optional()}),qc=B({taskId:P()}),Jc=ac({progressToken:Wc.optional(),[Hc]:qc.optional()}),Yc=B({_meta:Jc.optional()}),Xc=Yc.extend({task:Kc.optional()}),Zc=e=>Xc.safeParse(e).success,Qc=B({method:P(),params:Yc.loose().optional()}),$c=B({_meta:Jc.optional()}),el=B({method:P(),params:$c.loose().optional()}),tl=ac({_meta:Jc.optional()}),nl=V([P(),I().int()]),rl=B({jsonrpc:U(`2.0`),id:nl,...Qc.shape}).strict(),il=e=>rl.safeParse(e).success,al=B({jsonrpc:U(`2.0`),...el.shape}).strict(),ol=e=>al.safeParse(e).success,sl=B({jsonrpc:U(`2.0`),id:nl,result:tl}).strict(),cl=e=>sl.safeParse(e).success;var G;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(G||={});const ll=B({jsonrpc:U(`2.0`),id:nl.optional(),error:B({code:I().int(),message:P(),data:R().optional()})}).strict(),ul=e=>ll.safeParse(e).success,dl=V([rl,al,sl,ll]);V([sl,ll]);const fl=tl.strict(),pl=$c.extend({requestId:nl.optional(),reason:P().optional()}),ml=el.extend({method:U(`notifications/cancelled`),params:pl}),hl=B({icons:z(B({src:P(),mimeType:P().optional(),sizes:z(P()).optional(),theme:pc([`light`,`dark`]).optional()})).optional()}),gl=B({name:P(),title:P().optional()}),_l=gl.extend({...gl.shape,...hl.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),vl=Lc(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,uc(B({form:uc(B({applyDefaults:L().optional()}),H(P(),R())).optional(),url:Uc.optional()}),H(P(),R()).optional())),yl=ac({list:Uc.optional(),cancel:Uc.optional(),requests:ac({sampling:ac({createMessage:Uc.optional()}).optional(),elicitation:ac({create:Uc.optional()}).optional()}).optional()}),bl=ac({list:Uc.optional(),cancel:Uc.optional(),requests:ac({tools:ac({call:Uc.optional()}).optional()}).optional()}),xl=B({experimental:H(P(),Uc).optional(),sampling:B({context:Uc.optional(),tools:Uc.optional()}).optional(),elicitation:vl.optional(),roots:B({listChanged:L().optional()}).optional(),tasks:yl.optional(),extensions:H(P(),Uc).optional()}),Sl=Yc.extend({protocolVersion:P(),capabilities:xl,clientInfo:_l}),Cl=Qc.extend({method:U(`initialize`),params:Sl}),wl=B({experimental:H(P(),Uc).optional(),logging:Uc.optional(),completions:Uc.optional(),prompts:B({listChanged:L().optional()}).optional(),resources:B({subscribe:L().optional(),listChanged:L().optional()}).optional(),tools:B({listChanged:L().optional()}).optional(),tasks:bl.optional(),extensions:H(P(),Uc).optional()}),Tl=tl.extend({protocolVersion:P(),capabilities:wl,serverInfo:_l,instructions:P().optional()}),El=el.extend({method:U(`notifications/initialized`),params:$c.optional()}),Dl=e=>El.safeParse(e).success,Ol=Qc.extend({method:U(`ping`),params:Yc.optional()}),kl=B({progress:I(),total:W(I()),message:W(P())}),Al=B({...$c.shape,...kl.shape,progressToken:Wc}),jl=el.extend({method:U(`notifications/progress`),params:Al}),Ml=Yc.extend({cursor:Gc.optional()}),Nl=Qc.extend({params:Ml.optional()}),Pl=tl.extend({nextCursor:Gc.optional()}),Fl=pc([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Il=B({taskId:P(),status:Fl,ttl:V([I(),Zs()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:W(I()),statusMessage:W(P())}),Ll=tl.extend({task:Il}),Rl=$c.merge(Il),zl=el.extend({method:U(`notifications/tasks/status`),params:Rl}),Bl=Qc.extend({method:U(`tasks/get`),params:Yc.extend({taskId:P()})}),Vl=tl.merge(Il),Hl=Qc.extend({method:U(`tasks/result`),params:Yc.extend({taskId:P()})});tl.loose();const Ul=Nl.extend({method:U(`tasks/list`)}),Wl=Pl.extend({tasks:z(Il)}),Gl=Qc.extend({method:U(`tasks/cancel`),params:Yc.extend({taskId:P()})}),Kl=tl.merge(Il),ql=B({uri:P(),mimeType:W(P()),_meta:H(P(),R()).optional()}),Jl=ql.extend({text:P()}),Yl=P().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Xl=ql.extend({blob:Yl}),Zl=pc([`user`,`assistant`]),Ql=B({audience:z(Zl).optional(),priority:I().min(0).max(1).optional(),lastModified:ds({offset:!0}).optional()}),$l=B({...gl.shape,...hl.shape,uri:P(),description:W(P()),mimeType:W(P()),size:W(I()),annotations:Ql.optional(),_meta:W(ac({}))}),eu=B({...gl.shape,...hl.shape,uriTemplate:P(),description:W(P()),mimeType:W(P()),annotations:Ql.optional(),_meta:W(ac({}))}),tu=Nl.extend({method:U(`resources/list`)}),nu=Pl.extend({resources:z($l)}),ru=Nl.extend({method:U(`resources/templates/list`)}),iu=Pl.extend({resourceTemplates:z(eu)}),au=Yc.extend({uri:P()}),ou=au,su=Qc.extend({method:U(`resources/read`),params:ou}),cu=tl.extend({contents:z(V([Jl,Xl]))}),lu=el.extend({method:U(`notifications/resources/list_changed`),params:$c.optional()}),uu=au,du=Qc.extend({method:U(`resources/subscribe`),params:uu}),fu=au,pu=Qc.extend({method:U(`resources/unsubscribe`),params:fu}),mu=$c.extend({uri:P()}),hu=el.extend({method:U(`notifications/resources/updated`),params:mu}),gu=B({name:P(),description:W(P()),required:W(L())}),_u=B({...gl.shape,...hl.shape,description:W(P()),arguments:W(z(gu)),_meta:W(ac({}))}),vu=Nl.extend({method:U(`prompts/list`)}),yu=Pl.extend({prompts:z(_u)}),bu=Yc.extend({name:P(),arguments:H(P(),P()).optional()}),xu=Qc.extend({method:U(`prompts/get`),params:bu}),Su=B({type:U(`text`),text:P(),annotations:Ql.optional(),_meta:H(P(),R()).optional()}),Cu=B({type:U(`image`),data:Yl,mimeType:P(),annotations:Ql.optional(),_meta:H(P(),R()).optional()}),wu=B({type:U(`audio`),data:Yl,mimeType:P(),annotations:Ql.optional(),_meta:H(P(),R()).optional()}),Tu=B({type:U(`tool_use`),name:P(),id:P(),input:H(P(),R()),_meta:H(P(),R()).optional()}),Eu=B({type:U(`resource`),resource:V([Jl,Xl]),annotations:Ql.optional(),_meta:H(P(),R()).optional()}),Du=V([Su,Cu,wu,$l.extend({type:U(`resource_link`)}),Eu]),Ou=B({role:Zl,content:Du}),ku=tl.extend({description:P().optional(),messages:z(Ou)}),Au=el.extend({method:U(`notifications/prompts/list_changed`),params:$c.optional()}),ju=B({title:P().optional(),readOnlyHint:L().optional(),destructiveHint:L().optional(),idempotentHint:L().optional(),openWorldHint:L().optional()}),Mu=B({taskSupport:pc([`required`,`optional`,`forbidden`]).optional()}),Nu=B({...gl.shape,...hl.shape,description:P().optional(),inputSchema:B({type:U(`object`),properties:H(P(),Uc).optional(),required:z(P()).optional()}).catchall(R()),outputSchema:B({type:U(`object`),properties:H(P(),Uc).optional(),required:z(P()).optional()}).catchall(R()).optional(),annotations:ju.optional(),execution:Mu.optional(),_meta:H(P(),R()).optional()}),Pu=Nl.extend({method:U(`tools/list`)}),Fu=Pl.extend({tools:z(Nu)}),Iu=tl.extend({content:z(Du).default([]),structuredContent:H(P(),R()).optional(),isError:L().optional()});Iu.or(tl.extend({toolResult:R()}));const Lu=Xc.extend({name:P(),arguments:H(P(),R()).optional()}),Ru=Qc.extend({method:U(`tools/call`),params:Lu}),zu=el.extend({method:U(`notifications/tools/list_changed`),params:$c.optional()}),Bu=B({autoRefresh:L().default(!0),debounceMs:I().int().nonnegative().default(300)}),Vu=pc([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Hu=Yc.extend({level:Vu}),Uu=Qc.extend({method:U(`logging/setLevel`),params:Hu}),Wu=$c.extend({level:Vu,logger:P().optional(),data:R()}),Gu=el.extend({method:U(`notifications/message`),params:Wu}),Ku=B({hints:z(B({name:P().optional()})).optional(),costPriority:I().min(0).max(1).optional(),speedPriority:I().min(0).max(1).optional(),intelligencePriority:I().min(0).max(1).optional()}),qu=B({mode:pc([`auto`,`required`,`none`]).optional()}),Ju=B({type:U(`tool_result`),toolUseId:P().describe(`The unique identifier for the corresponding tool call.`),content:z(Du).default([]),structuredContent:B({}).loose().optional(),isError:L().optional(),_meta:H(P(),R()).optional()}),Yu=cc(`type`,[Su,Cu,wu]),Xu=cc(`type`,[Su,Cu,wu,Tu,Ju]),Zu=B({role:Zl,content:V([Xu,z(Xu)]),_meta:H(P(),R()).optional()}),Qu=Xc.extend({messages:z(Zu),modelPreferences:Ku.optional(),systemPrompt:P().optional(),includeContext:pc([`none`,`thisServer`,`allServers`]).optional(),temperature:I().optional(),maxTokens:I().int(),stopSequences:z(P()).optional(),metadata:Uc.optional(),tools:z(Nu).optional(),toolChoice:qu.optional()}),$u=Qc.extend({method:U(`sampling/createMessage`),params:Qu}),ed=tl.extend({model:P(),stopReason:W(pc([`endTurn`,`stopSequence`,`maxTokens`]).or(P())),role:Zl,content:Yu}),td=tl.extend({model:P(),stopReason:W(pc([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(P())),role:Zl,content:V([Xu,z(Xu)])}),nd=B({type:U(`boolean`),title:P().optional(),description:P().optional(),default:L().optional()}),rd=B({type:U(`string`),title:P().optional(),description:P().optional(),minLength:I().optional(),maxLength:I().optional(),format:pc([`email`,`uri`,`date`,`date-time`]).optional(),default:P().optional()}),id=B({type:pc([`number`,`integer`]),title:P().optional(),description:P().optional(),minimum:I().optional(),maximum:I().optional(),default:I().optional()}),ad=B({type:U(`string`),title:P().optional(),description:P().optional(),enum:z(P()),default:P().optional()}),od=B({type:U(`string`),title:P().optional(),description:P().optional(),oneOf:z(B({const:P(),title:P()})),default:P().optional()}),sd=V([V([B({type:U(`string`),title:P().optional(),description:P().optional(),enum:z(P()),enumNames:z(P()).optional(),default:P().optional()}),V([ad,od]),V([B({type:U(`array`),title:P().optional(),description:P().optional(),minItems:I().optional(),maxItems:I().optional(),items:B({type:U(`string`),enum:z(P())}),default:z(P()).optional()}),B({type:U(`array`),title:P().optional(),description:P().optional(),minItems:I().optional(),maxItems:I().optional(),items:B({anyOf:z(B({const:P(),title:P()}))}),default:z(P()).optional()})])]),nd,rd,id]),cd=V([Xc.extend({mode:U(`form`).optional(),message:P(),requestedSchema:B({type:U(`object`),properties:H(P(),sd),required:z(P()).optional()})}),Xc.extend({mode:U(`url`),message:P(),elicitationId:P(),url:P().url()})]),ld=Qc.extend({method:U(`elicitation/create`),params:cd}),ud=$c.extend({elicitationId:P()}),dd=el.extend({method:U(`notifications/elicitation/complete`),params:ud}),fd=tl.extend({action:pc([`accept`,`decline`,`cancel`]),content:Lc(e=>e===null?void 0:e,H(P(),V([P(),I(),L(),z(P())])).optional())}),pd=B({type:U(`ref/resource`),uri:P()}),md=B({type:U(`ref/prompt`),name:P()}),hd=Yc.extend({ref:V([md,pd]),argument:B({name:P(),value:P()}),context:B({arguments:H(P(),P()).optional()}).optional()}),gd=Qc.extend({method:U(`completion/complete`),params:hd}),_d=tl.extend({completion:ac({values:z(P()).max(100),total:W(I().int()),hasMore:W(L())})}),vd=B({uri:P().startsWith(`file://`),name:P().optional(),_meta:H(P(),R()).optional()}),yd=Qc.extend({method:U(`roots/list`),params:Yc.optional()}),bd=tl.extend({roots:z(vd)}),xd=el.extend({method:U(`notifications/roots/list_changed`),params:$c.optional()});V([Ol,Cl,gd,Uu,xu,vu,tu,ru,su,du,pu,Ru,Pu,Bl,Hl,Ul,Gl]),V([ml,jl,El,xd,zl]),V([fl,ed,td,fd,bd,Vl,Wl,Ll]),V([Ol,$u,ld,yd,Bl,Hl,Ul,Gl]),V([ml,jl,Gu,hu,lu,zu,Au,zl,dd]),V([fl,Tl,_d,ku,yu,nu,iu,cu,Iu,Fu,Vl,Wl,Ll]);var K=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===G.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Sd(e.elicitations,n)}return new e(t,n,r)}},Sd=class extends K{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(G.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Cd(e){return e===`completed`||e===`failed`||e===`cancelled`}function wd(e){let t=cs(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=ls(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Td(e,t){let n=ss(e,t);if(!n.success)throw n.error;return n.data}var Ed=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=/* @__PURE__ */ new Map,this._requestHandlerAbortControllers=/* @__PURE__ */ new Map,this._notificationHandlers=/* @__PURE__ */ new Map,this._responseHandlers=/* @__PURE__ */ new Map,this._progressHandlers=/* @__PURE__ */ new Map,this._timeoutInfo=/* @__PURE__ */ new Map,this._pendingDebouncedNotifications=/* @__PURE__ */ new Set,this._taskProgressTokens=/* @__PURE__ */ new Map,this._requestResolvers=/* @__PURE__ */ new Map,this.setNotificationHandler(ml,e=>{this._oncancel(e)}),this.setNotificationHandler(jl,e=>{this._onprogress(e)}),this.setRequestHandler(Ol,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Bl,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Hl,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(!await this._taskStore.getTask(r,t.sessionId))throw new K(G.InvalidParams,`Task not found: ${r}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new K(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(/* @__PURE__ */ Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new K(G.InvalidParams,`Task not found: ${r}`);if(!Cd(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(Cd(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[Hc]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Ul,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new K(G.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Gl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Task not found: ${e.params.taskId}`);if(Cd(n.status))throw new K(G.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new K(G.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof K?e:new K(G.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),K.fromError(G.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),cl(e)||ul(e)?this._onresponse(e):il(e)?this._onrequest(e,t):ol(e)?this._onnotification(e):this._onerror(/* @__PURE__ */ Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=/* @__PURE__ */ new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=K.fromError(G.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(/* @__PURE__ */ Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Hc]?.taskId,a=r?.sessionId,o=this._taskStore,s=!0,c;if(i&&o&&this._taskMessageQueue&&a!==void 0&&(s=!1,c=(async()=>{if(!await o.getTask(i,a))throw new K(G.InvalidParams,`Task not found: ${i}`);s=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:G.MethodNotFound,message:`Method not found`}};if(i&&c){let e={type:`error`,message:t,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(i,e,a),()=>r?.send(t)).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let u=Zc(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,f={signal:l.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(l.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(l.signal.aborted)throw new K(G.ConnectionClosed,`Request was cancelled`);let a={...r,relatedRequestId:e.id};i&&!a.relatedTask&&(a.relatedTask={taskId:i});let o=a.relatedTask?.taskId??i;return o&&d&&await d.updateTaskStatus(o,`input_required`),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new K(G.ConnectionClosed,`Request was cancelled`);u&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async t=>{if(l.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(l.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:G.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue&&s?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(/* @__PURE__ */ Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),cl(e)?n(e):n(new K(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(/* @__PURE__ */ Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(cl(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),cl(e)?r(e):r(K.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof K?e:new K(G.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Ll,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new K(G.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Cd(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new K(G.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new K(G.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof K?e:new K(G.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(/* @__PURE__ */ Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Hc]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send cancellation: ${e}`))),l(e instanceof K?e:new K(G.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=ss(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(K.fromError(G.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(/* @__PURE__ */ Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Vl,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Wl,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Kl,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Hc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Hc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Hc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=wd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Td(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=wd(e);this._notificationHandlers.set(n,n=>{let r=Td(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n??this._transport?.sessionId,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&il(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new K(G.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(/* @__PURE__ */ Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e,n);t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted){n(new K(G.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new K(G.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new K(G.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=zl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Cd(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new K(G.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Cd(a.status))throw new K(G.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=zl.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Cd(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Dd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Od(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Dd(a)&&Dd(i)?{...a,...i}:i}return n}var kd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Ad=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=kd();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=/* @__PURE__ */ new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||/* @__PURE__ */ new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),q=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=kd(),n=Ad();var r=kd();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Ad();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ce(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ce(this.rhs,e,n),this}get names(){return se(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ce(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(le(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>oe(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ue(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ce(this.condition,e,t),this}get names(){let e=super.names;return se(e,this.condition),this.else&&oe(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ce(this.iteration,e,t),this}get names(){return oe(super.names,this.iteration.names)}},ee=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return se(se(super.names,this.from),this.to)}},b=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ce(this.iterable,e,t),this}get names(){return oe(super.names,this.iterable.names)}},te=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};te.kind=`func`;var ne=class extends p{render(e){return`return `+super.render(e)}};ne.kind=`return`;var re=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&oe(e,this.catch.names),this.finally&&oe(e,this.finally.names),e}},ie=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ie.kind=`catch`;var ae=class extends m{render(e){return`finally`+super.render(e)}};ae.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
31
|
-
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=/* @__PURE__ */ new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new ee(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new b(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new b(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new ne;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(ne)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new re;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ie(e),t(e)}return n&&(this._currNode=r.finally=new ae,this.code(n)),this._endBlockNode(ie,ae)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new te(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(te)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function oe(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function se(e,n){return n instanceof t._CodeOrName?oe(e,n.names):e}function ce(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function le(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ue(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${he(e)}`}e.not=ue;let de=me(e.operators.AND);function fe(...e){return e.reduce(de)}e.and=fe;let pe=me(e.operators.OR);function x(...e){return e.reduce(pe)}e.or=x;function me(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${he(n)} ${e} ${he(r)}`}function he(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),J=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=q(),n=kd();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||b(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function ee(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=ee;function b(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=b})),jd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Md=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=q(),n=J(),r=jd();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){
|
|
29
|
+
path: iss.path ? [${br(e)}, ...iss.path] : [${br(e)}]
|
|
30
|
+
})));`),t.write(`newResult[${br(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=Sr,o=!dr.jitless,s=o&&Cr.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??=n.value;let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||=r(t.shape),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?Ma(e,u,t,f):ja(e,u,t))):i?Ma(r,u,t,f):ja(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>ja(t,u,e))):ja(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function Pa(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>zr(e,r,fr())))}),t}const Fa=/*@__PURE__*/ k(`$ZodUnion`,(e,t)=>{M.init(e,t),A(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),A(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),A(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),A(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>_r(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>Pa(t,n,e,r)):Pa(a,n,e,r)}}),Ia=/*@__PURE__*/ k(`$ZodDiscriminatedUnion`,(e,t)=>{Fa.init(e,t);let n=e._zod.parse;A(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=/* @__PURE__ */ new Set);for(let r of n)e[t].add(r)}}return e});let r=hr(()=>{let e=t.options,n=/* @__PURE__ */ new Map;for(let r of e){let e=r._zod.propValues[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Sr(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,input:o,path:[t.discriminator],inst:e}),i)}}),La=/*@__PURE__*/ k(`$ZodIntersection`,(e,t)=>{M.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>za(e,t,n)):za(e,i,a)}});function Ra(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(wr(e)&&wr(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ra(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Ra(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function za(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Ir(e))return e;let r=Ra(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const Ba=/*@__PURE__*/ k(`$ZodRecord`,(e,t)=>{M.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!wr(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...Lr(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...Lr(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>zr(e,r,fr())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Lr(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Lr(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Va=/*@__PURE__*/ k(`$ZodEnum`,(e,t)=>{M.init(e,t);let n=pr(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>Tr.has(typeof e)).map(e=>typeof e==`string`?Er(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),Ha=/*@__PURE__*/ k(`$ZodLiteral`,(e,t)=>{M.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Er(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),Ua=/*@__PURE__*/ k(`$ZodTransform`,(e,t)=>{M.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new ur;return e.value=r,e}}),Wa=/*@__PURE__*/ k(`$ZodOptional`,(e,t)=>{M.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,A(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,void 0]):void 0),A(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${_r(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),Ga=/*@__PURE__*/ k(`$ZodNullable`,(e,t)=>{M.init(e,t),A(e._zod,`optin`,()=>t.innerType._zod.optin),A(e._zod,`optout`,()=>t.innerType._zod.optout),A(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${_r(e.source)}|null)$`):void 0}),A(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ka=/*@__PURE__*/ k(`$ZodDefault`,(e,t)=>{M.init(e,t),e._zod.optin=`optional`,A(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>qa(e,t)):qa(r,t)}});function qa(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Ja=/*@__PURE__*/ k(`$ZodPrefault`,(e,t)=>{M.init(e,t),e._zod.optin=`optional`,A(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ya=/*@__PURE__*/ k(`$ZodNonOptional`,(e,t)=>{M.init(e,t),A(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Xa(t,e)):Xa(i,e)}});function Xa(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const Za=/*@__PURE__*/ k(`$ZodCatch`,(e,t)=>{M.init(e,t),e._zod.optin=`optional`,A(e._zod,`optout`,()=>t.innerType._zod.optout),A(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>zr(e,n,fr()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>zr(e,n,fr()))},input:e.value}),e.issues=[]),e)}}),Qa=/*@__PURE__*/ k(`$ZodPipe`,(e,t)=>{M.init(e,t),A(e._zod,`values`,()=>t.in._zod.values),A(e._zod,`optin`,()=>t.in._zod.optin),A(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>$a(e,t,n)):$a(r,t,n)}});function $a(e,t,n){return Ir(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const eo=/*@__PURE__*/ k(`$ZodReadonly`,(e,t)=>{M.init(e,t),A(e._zod,`propValues`,()=>t.innerType._zod.propValues),A(e._zod,`values`,()=>t.innerType._zod.values),A(e._zod,`optin`,()=>t.innerType._zod.optin),A(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(to):to(r)}});function to(e){return e.value=Object.freeze(e.value),e}const no=/*@__PURE__*/ k(`$ZodCustom`,(e,t)=>{Ai.init(e,t),M.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>ro(t,n,r,e));ro(i,n,r,e)}});function ro(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Vr(e))}}var io=class{constructor(){this._map=/* @__PURE__ */ new Map,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=/* @__PURE__ */ new Map,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function ao(){return new io}const oo=/*@__PURE__*/ ao();function so(e,t){return new e({type:`string`,...j(t)})}function co(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...j(t)})}function lo(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...j(t)})}function uo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...j(t)})}function fo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...j(t)})}function po(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...j(t)})}function mo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...j(t)})}function ho(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...j(t)})}function go(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...j(t)})}function _o(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...j(t)})}function vo(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...j(t)})}function yo(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...j(t)})}function bo(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...j(t)})}function xo(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...j(t)})}function So(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...j(t)})}function Co(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...j(t)})}function wo(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...j(t)})}function To(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...j(t)})}function Eo(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...j(t)})}function Do(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...j(t)})}function Oo(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...j(t)})}function ko(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...j(t)})}function Ao(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...j(t)})}function jo(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...j(t)})}function Mo(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...j(t)})}function No(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...j(t)})}function Po(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...j(t)})}function Fo(e,t){return new e({type:`number`,checks:[],...j(t)})}function Io(e,t){return new e({type:`number`,coerce:!0,checks:[],...j(t)})}function Lo(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...j(t)})}function Ro(e,t){return new e({type:`boolean`,...j(t)})}function zo(e,t){return new e({type:`null`,...j(t)})}function Bo(e){return new e({type:`any`})}function Vo(e){return new e({type:`unknown`})}function Ho(e,t){return new e({type:`never`,...j(t)})}function Uo(e,t){return new Mi({check:`less_than`,...j(t),value:e,inclusive:!1})}function Wo(e,t){return new Mi({check:`less_than`,...j(t),value:e,inclusive:!0})}function Go(e,t){return new Ni({check:`greater_than`,...j(t),value:e,inclusive:!1})}function Ko(e,t){return new Ni({check:`greater_than`,...j(t),value:e,inclusive:!0})}function qo(e,t){return new Pi({check:`multiple_of`,...j(t),value:e})}function Jo(e,t){return new Ii({check:`max_length`,...j(t),maximum:e})}function Yo(e,t){return new Li({check:`min_length`,...j(t),minimum:e})}function Xo(e,t){return new Ri({check:`length_equals`,...j(t),length:e})}function Zo(e,t){return new Bi({check:`string_format`,format:`regex`,...j(t),pattern:e})}function Qo(e){return new Vi({check:`string_format`,format:`lowercase`,...j(e)})}function $o(e){return new Hi({check:`string_format`,format:`uppercase`,...j(e)})}function es(e,t){return new Ui({check:`string_format`,format:`includes`,...j(t),includes:e})}function ts(e,t){return new Wi({check:`string_format`,format:`starts_with`,...j(t),prefix:e})}function ns(e,t){return new Gi({check:`string_format`,format:`ends_with`,...j(t),suffix:e})}function rs(e){return new Ki({check:`overwrite`,tx:e})}function is(e){return rs(t=>t.normalize(e))}function as(){return rs(e=>e.trim())}function os(){return rs(e=>e.toLowerCase())}function ss(){return rs(e=>e.toUpperCase())}function cs(e,t,n){return new e({type:`array`,element:t,...j(n)})}function ls(e,t,n){let r=j(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function us(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...j(n)})}function ds(e){return!!e._zod}function fs(e,t){return ds(e)?Xr(e,t):e.safeParse(t)}function ps(e){if(!e)return;let t;if(t=ds(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function ms(e){if(ds(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const hs=/*@__PURE__*/ k(`ZodISODateTime`,(e,t)=>{sa.init(e,t),js.init(e,t)});function gs(e){return jo(hs,e)}const _s=/*@__PURE__*/ k(`ZodISODate`,(e,t)=>{ca.init(e,t),js.init(e,t)});function vs(e){return Mo(_s,e)}const ys=/*@__PURE__*/ k(`ZodISOTime`,(e,t)=>{la.init(e,t),js.init(e,t)});function bs(e){return No(ys,e)}const xs=/*@__PURE__*/ k(`ZodISODuration`,(e,t)=>{ua.init(e,t),js.init(e,t)});function Ss(e){return Po(xs,e)}const Cs=(e,t)=>{Ur.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Kr(e,t)},flatten:{value:t=>Gr(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})};k(`ZodError`,Cs);const ws=k(`ZodError`,Cs,{Parent:Error}),Ts=/* @__PURE__ */ qr(ws),Es=/* @__PURE__ */ Jr(ws),Ds=/* @__PURE__ */ Yr(ws),Os=/* @__PURE__ */ Zr(ws),P=/*@__PURE__*/ k(`ZodType`,(e,t)=>(M.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>Dr(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Ts(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ds(e,t,n),e.parseAsync=async(t,n)=>Es(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Os(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(Vc(t,n)),e.superRefine=t=>e.check(Hc(t)),e.overwrite=t=>e.check(rs(t)),e.optional=()=>W(e),e.nullable=()=>Tc(e),e.nullish=()=>W(Tc(e)),e.nonoptional=t=>jc(e,t),e.array=()=>z(e),e.or=t=>V([e,t]),e.and=t=>gc(e,t),e.transform=t=>Fc(e,Sc(t)),e.default=t=>Dc(e,t),e.prefault=t=>kc(e,t),e.catch=t=>Nc(e,t),e.pipe=t=>Fc(e,t),e.readonly=()=>Lc(e),e.describe=t=>{let n=e.clone();return oo.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return oo.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return oo.get(e);let n=e.clone();return oo.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),ks=/*@__PURE__*/ k(`_ZodString`,(e,t)=>{Yi.init(e,t),P.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Zo(...t)),e.includes=(...t)=>e.check(es(...t)),e.startsWith=(...t)=>e.check(ts(...t)),e.endsWith=(...t)=>e.check(ns(...t)),e.min=(...t)=>e.check(Yo(...t)),e.max=(...t)=>e.check(Jo(...t)),e.length=(...t)=>e.check(Xo(...t)),e.nonempty=(...t)=>e.check(Yo(1,...t)),e.lowercase=t=>e.check(Qo(t)),e.uppercase=t=>e.check($o(t)),e.trim=()=>e.check(as()),e.normalize=(...t)=>e.check(is(...t)),e.toLowerCase=()=>e.check(os()),e.toUpperCase=()=>e.check(ss())}),As=/*@__PURE__*/ k(`ZodString`,(e,t)=>{Yi.init(e,t),ks.init(e,t),e.email=t=>e.check(co(Ms,t)),e.url=t=>e.check(ho(Fs,t)),e.jwt=t=>e.check(Ao(Zs,t)),e.emoji=t=>e.check(go(Ls,t)),e.guid=t=>e.check(lo(Ns,t)),e.uuid=t=>e.check(uo(Ps,t)),e.uuidv4=t=>e.check(fo(Ps,t)),e.uuidv6=t=>e.check(po(Ps,t)),e.uuidv7=t=>e.check(mo(Ps,t)),e.nanoid=t=>e.check(_o(Rs,t)),e.guid=t=>e.check(lo(Ns,t)),e.cuid=t=>e.check(vo(zs,t)),e.cuid2=t=>e.check(yo(Bs,t)),e.ulid=t=>e.check(bo(Vs,t)),e.base64=t=>e.check(Do(Js,t)),e.base64url=t=>e.check(Oo(Ys,t)),e.xid=t=>e.check(xo(Hs,t)),e.ksuid=t=>e.check(So(Us,t)),e.ipv4=t=>e.check(Co(Ws,t)),e.ipv6=t=>e.check(wo(Gs,t)),e.cidrv4=t=>e.check(To(Ks,t)),e.cidrv6=t=>e.check(Eo(qs,t)),e.e164=t=>e.check(ko(Xs,t)),e.datetime=t=>e.check(gs(t)),e.date=t=>e.check(vs(t)),e.time=t=>e.check(bs(t)),e.duration=t=>e.check(Ss(t))});function F(e){return so(As,e)}const js=/*@__PURE__*/ k(`ZodStringFormat`,(e,t)=>{N.init(e,t),ks.init(e,t)}),Ms=/*@__PURE__*/ k(`ZodEmail`,(e,t)=>{Qi.init(e,t),js.init(e,t)}),Ns=/*@__PURE__*/ k(`ZodGUID`,(e,t)=>{Xi.init(e,t),js.init(e,t)}),Ps=/*@__PURE__*/ k(`ZodUUID`,(e,t)=>{Zi.init(e,t),js.init(e,t)}),Fs=/*@__PURE__*/ k(`ZodURL`,(e,t)=>{$i.init(e,t),js.init(e,t)});function Is(e){return ho(Fs,e)}const Ls=/*@__PURE__*/ k(`ZodEmoji`,(e,t)=>{ea.init(e,t),js.init(e,t)}),Rs=/*@__PURE__*/ k(`ZodNanoID`,(e,t)=>{ta.init(e,t),js.init(e,t)}),zs=/*@__PURE__*/ k(`ZodCUID`,(e,t)=>{na.init(e,t),js.init(e,t)}),Bs=/*@__PURE__*/ k(`ZodCUID2`,(e,t)=>{ra.init(e,t),js.init(e,t)}),Vs=/*@__PURE__*/ k(`ZodULID`,(e,t)=>{ia.init(e,t),js.init(e,t)}),Hs=/*@__PURE__*/ k(`ZodXID`,(e,t)=>{aa.init(e,t),js.init(e,t)}),Us=/*@__PURE__*/ k(`ZodKSUID`,(e,t)=>{oa.init(e,t),js.init(e,t)}),Ws=/*@__PURE__*/ k(`ZodIPv4`,(e,t)=>{da.init(e,t),js.init(e,t)}),Gs=/*@__PURE__*/ k(`ZodIPv6`,(e,t)=>{fa.init(e,t),js.init(e,t)}),Ks=/*@__PURE__*/ k(`ZodCIDRv4`,(e,t)=>{pa.init(e,t),js.init(e,t)}),qs=/*@__PURE__*/ k(`ZodCIDRv6`,(e,t)=>{ma.init(e,t),js.init(e,t)}),Js=/*@__PURE__*/ k(`ZodBase64`,(e,t)=>{ga.init(e,t),js.init(e,t)}),Ys=/*@__PURE__*/ k(`ZodBase64URL`,(e,t)=>{va.init(e,t),js.init(e,t)}),Xs=/*@__PURE__*/ k(`ZodE164`,(e,t)=>{ya.init(e,t),js.init(e,t)}),Zs=/*@__PURE__*/ k(`ZodJWT`,(e,t)=>{xa.init(e,t),js.init(e,t)}),Qs=/*@__PURE__*/ k(`ZodNumber`,(e,t)=>{Sa.init(e,t),P.init(e,t),e.gt=(t,n)=>e.check(Go(t,n)),e.gte=(t,n)=>e.check(Ko(t,n)),e.min=(t,n)=>e.check(Ko(t,n)),e.lt=(t,n)=>e.check(Uo(t,n)),e.lte=(t,n)=>e.check(Wo(t,n)),e.max=(t,n)=>e.check(Wo(t,n)),e.int=t=>e.check(ec(t)),e.safe=t=>e.check(ec(t)),e.positive=t=>e.check(Go(0,t)),e.nonnegative=t=>e.check(Ko(0,t)),e.negative=t=>e.check(Uo(0,t)),e.nonpositive=t=>e.check(Wo(0,t)),e.multipleOf=(t,n)=>e.check(qo(t,n)),e.step=(t,n)=>e.check(qo(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function I(e){return Fo(Qs,e)}const $s=/*@__PURE__*/ k(`ZodNumberFormat`,(e,t)=>{Ca.init(e,t),Qs.init(e,t)});function ec(e){return Lo($s,e)}const tc=/*@__PURE__*/ k(`ZodBoolean`,(e,t)=>{wa.init(e,t),P.init(e,t)});function L(e){return Ro(tc,e)}const nc=/*@__PURE__*/ k(`ZodNull`,(e,t)=>{Ta.init(e,t),P.init(e,t)});function rc(e){return zo(nc,e)}const ic=/*@__PURE__*/ k(`ZodAny`,(e,t)=>{Ea.init(e,t),P.init(e,t)});function ac(){return Bo(ic)}const oc=/*@__PURE__*/ k(`ZodUnknown`,(e,t)=>{Da.init(e,t),P.init(e,t)});function R(){return Vo(oc)}const sc=/*@__PURE__*/ k(`ZodNever`,(e,t)=>{Oa.init(e,t),P.init(e,t)});function cc(e){return Ho(sc,e)}const lc=/*@__PURE__*/ k(`ZodArray`,(e,t)=>{Aa.init(e,t),P.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Yo(t,n)),e.nonempty=t=>e.check(Yo(1,t)),e.max=(t,n)=>e.check(Jo(t,n)),e.length=(t,n)=>e.check(Xo(t,n)),e.unwrap=()=>e.element});function z(e,t){return cs(lc,e,t)}const uc=/*@__PURE__*/ k(`ZodObject`,(e,t)=>{Na.init(e,t),P.init(e,t),A(e,`shape`,()=>t.shape),e.keyof=()=>yc(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:R()}),e.loose=()=>e.clone({...e._zod.def,catchall:R()}),e.strict=()=>e.clone({...e._zod.def,catchall:cc()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Mr(e,t),e.merge=t=>Nr(e,t),e.pick=t=>Ar(e,t),e.omit=t=>jr(e,t),e.partial=(...t)=>Pr(Cc,e,t[0]),e.required=(...t)=>Fr(Ac,e,t[0])});function B(e,t){let n={type:`object`,get shape(){return yr(this,`shape`,{...e}),this.shape},...j(t)};return new uc(n)}function dc(e,t){return new uc({type:`object`,get shape(){return yr(this,`shape`,{...e}),this.shape},catchall:R(),...j(t)})}const fc=/*@__PURE__*/ k(`ZodUnion`,(e,t)=>{Fa.init(e,t),P.init(e,t),e.options=t.options});function V(e,t){return new fc({type:`union`,options:e,...j(t)})}const pc=/*@__PURE__*/ k(`ZodDiscriminatedUnion`,(e,t)=>{fc.init(e,t),Ia.init(e,t)});function mc(e,t,n){return new pc({type:`union`,options:t,discriminator:e,...j(n)})}const hc=/*@__PURE__*/ k(`ZodIntersection`,(e,t)=>{La.init(e,t),P.init(e,t)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}const _c=/*@__PURE__*/ k(`ZodRecord`,(e,t)=>{Ba.init(e,t),P.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function H(e,t,n){return new _c({type:`record`,keyType:e,valueType:t,...j(n)})}const vc=/*@__PURE__*/ k(`ZodEnum`,(e,t)=>{Va.init(e,t),P.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new vc({...t,checks:[],...j(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new vc({...t,checks:[],...j(r),entries:i})}});function yc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new vc({type:`enum`,entries:n,...j(t)})}const bc=/*@__PURE__*/ k(`ZodLiteral`,(e,t)=>{Ha.init(e,t),P.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function U(e,t){return new bc({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}const xc=/*@__PURE__*/ k(`ZodTransform`,(e,t)=>{Ua.init(e,t),P.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Vr(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(Vr(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Sc(e){return new xc({type:`transform`,transform:e})}const Cc=/*@__PURE__*/ k(`ZodOptional`,(e,t)=>{Wa.init(e,t),P.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W(e){return new Cc({type:`optional`,innerType:e})}const wc=/*@__PURE__*/ k(`ZodNullable`,(e,t)=>{Ga.init(e,t),P.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Tc(e){return new wc({type:`nullable`,innerType:e})}const Ec=/*@__PURE__*/ k(`ZodDefault`,(e,t)=>{Ka.init(e,t),P.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Dc(e,t){return new Ec({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const Oc=/*@__PURE__*/ k(`ZodPrefault`,(e,t)=>{Ja.init(e,t),P.init(e,t),e.unwrap=()=>e._zod.def.innerType});function kc(e,t){return new Oc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const Ac=/*@__PURE__*/ k(`ZodNonOptional`,(e,t)=>{Ya.init(e,t),P.init(e,t),e.unwrap=()=>e._zod.def.innerType});function jc(e,t){return new Ac({type:`nonoptional`,innerType:e,...j(t)})}const Mc=/*@__PURE__*/ k(`ZodCatch`,(e,t)=>{Za.init(e,t),P.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Nc(e,t){return new Mc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const Pc=/*@__PURE__*/ k(`ZodPipe`,(e,t)=>{Qa.init(e,t),P.init(e,t),e.in=t.in,e.out=t.out});function Fc(e,t){return new Pc({type:`pipe`,in:e,out:t})}const Ic=/*@__PURE__*/ k(`ZodReadonly`,(e,t)=>{eo.init(e,t),P.init(e,t)});function Lc(e){return new Ic({type:`readonly`,innerType:e})}const Rc=/*@__PURE__*/ k(`ZodCustom`,(e,t)=>{no.init(e,t),P.init(e,t)});function zc(e){let t=new Ai({check:`custom`});return t._zod.check=e,t}function Bc(e,t){return ls(Rc,e??(()=>!0),t)}function Vc(e,t={}){return us(Rc,e,t)}function Hc(e){let t=zc(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(Vr(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(Vr(r))}},e(n.value,n)));return t}function Uc(e,t){return Fc(Sc(e),t)}const Wc={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};function Gc(e){return Io(Qs,e)}const Kc=`2025-11-25`,qc=[Kc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Jc=`io.modelcontextprotocol/related-task`,Yc=Bc(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Xc=V([F(),I().int()]),Zc=F();dc({ttl:I().optional(),pollInterval:I().optional()});const Qc=B({ttl:I().optional()}),$c=B({taskId:F()}),el=dc({progressToken:Xc.optional(),[Jc]:$c.optional()}),tl=B({_meta:el.optional()}),nl=tl.extend({task:Qc.optional()}),rl=e=>nl.safeParse(e).success,il=B({method:F(),params:tl.loose().optional()}),al=B({_meta:el.optional()}),ol=B({method:F(),params:al.loose().optional()}),sl=dc({_meta:el.optional()}),cl=V([F(),I().int()]),ll=B({jsonrpc:U(`2.0`),id:cl,...il.shape}).strict(),ul=e=>ll.safeParse(e).success,dl=B({jsonrpc:U(`2.0`),...ol.shape}).strict(),fl=e=>dl.safeParse(e).success,pl=B({jsonrpc:U(`2.0`),id:cl,result:sl}).strict(),ml=e=>pl.safeParse(e).success;var G;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(G||={});const hl=B({jsonrpc:U(`2.0`),id:cl.optional(),error:B({code:I().int(),message:F(),data:R().optional()})}).strict(),gl=e=>hl.safeParse(e).success,_l=V([ll,dl,pl,hl]);V([pl,hl]);const vl=sl.strict(),yl=al.extend({requestId:cl.optional(),reason:F().optional()}),bl=ol.extend({method:U(`notifications/cancelled`),params:yl}),xl=B({icons:z(B({src:F(),mimeType:F().optional(),sizes:z(F()).optional(),theme:yc([`light`,`dark`]).optional()})).optional()}),Sl=B({name:F(),title:F().optional()}),Cl=Sl.extend({...Sl.shape,...xl.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),wl=Uc(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,gc(B({form:gc(B({applyDefaults:L().optional()}),H(F(),R())).optional(),url:Yc.optional()}),H(F(),R()).optional())),Tl=dc({list:Yc.optional(),cancel:Yc.optional(),requests:dc({sampling:dc({createMessage:Yc.optional()}).optional(),elicitation:dc({create:Yc.optional()}).optional()}).optional()}),El=dc({list:Yc.optional(),cancel:Yc.optional(),requests:dc({tools:dc({call:Yc.optional()}).optional()}).optional()}),Dl=B({experimental:H(F(),Yc).optional(),sampling:B({context:Yc.optional(),tools:Yc.optional()}).optional(),elicitation:wl.optional(),roots:B({listChanged:L().optional()}).optional(),tasks:Tl.optional(),extensions:H(F(),Yc).optional()}),Ol=tl.extend({protocolVersion:F(),capabilities:Dl,clientInfo:Cl}),kl=il.extend({method:U(`initialize`),params:Ol}),Al=B({experimental:H(F(),Yc).optional(),logging:Yc.optional(),completions:Yc.optional(),prompts:B({listChanged:L().optional()}).optional(),resources:B({subscribe:L().optional(),listChanged:L().optional()}).optional(),tools:B({listChanged:L().optional()}).optional(),tasks:El.optional(),extensions:H(F(),Yc).optional()}),jl=sl.extend({protocolVersion:F(),capabilities:Al,serverInfo:Cl,instructions:F().optional()}),Ml=ol.extend({method:U(`notifications/initialized`),params:al.optional()}),Nl=e=>Ml.safeParse(e).success,Pl=il.extend({method:U(`ping`),params:tl.optional()}),Fl=B({progress:I(),total:W(I()),message:W(F())}),Il=B({...al.shape,...Fl.shape,progressToken:Xc}),Ll=ol.extend({method:U(`notifications/progress`),params:Il}),Rl=tl.extend({cursor:Zc.optional()}),zl=il.extend({params:Rl.optional()}),Bl=sl.extend({nextCursor:Zc.optional()}),Vl=yc([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Hl=B({taskId:F(),status:Vl,ttl:V([I(),rc()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:W(I()),statusMessage:W(F())}),Ul=sl.extend({task:Hl}),Wl=al.merge(Hl),Gl=ol.extend({method:U(`notifications/tasks/status`),params:Wl}),Kl=il.extend({method:U(`tasks/get`),params:tl.extend({taskId:F()})}),ql=sl.merge(Hl),Jl=il.extend({method:U(`tasks/result`),params:tl.extend({taskId:F()})});sl.loose();const Yl=zl.extend({method:U(`tasks/list`)}),Xl=Bl.extend({tasks:z(Hl)}),Zl=il.extend({method:U(`tasks/cancel`),params:tl.extend({taskId:F()})}),Ql=sl.merge(Hl),$l=B({uri:F(),mimeType:W(F()),_meta:H(F(),R()).optional()}),eu=$l.extend({text:F()}),tu=F().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),nu=$l.extend({blob:tu}),ru=yc([`user`,`assistant`]),iu=B({audience:z(ru).optional(),priority:I().min(0).max(1).optional(),lastModified:gs({offset:!0}).optional()}),au=B({...Sl.shape,...xl.shape,uri:F(),description:W(F()),mimeType:W(F()),size:W(I()),annotations:iu.optional(),_meta:W(dc({}))}),ou=B({...Sl.shape,...xl.shape,uriTemplate:F(),description:W(F()),mimeType:W(F()),annotations:iu.optional(),_meta:W(dc({}))}),su=zl.extend({method:U(`resources/list`)}),cu=Bl.extend({resources:z(au)}),lu=zl.extend({method:U(`resources/templates/list`)}),uu=Bl.extend({resourceTemplates:z(ou)}),du=tl.extend({uri:F()}),fu=du,pu=il.extend({method:U(`resources/read`),params:fu}),mu=sl.extend({contents:z(V([eu,nu]))}),hu=ol.extend({method:U(`notifications/resources/list_changed`),params:al.optional()}),gu=du,_u=il.extend({method:U(`resources/subscribe`),params:gu}),vu=du,yu=il.extend({method:U(`resources/unsubscribe`),params:vu}),bu=al.extend({uri:F()}),xu=ol.extend({method:U(`notifications/resources/updated`),params:bu}),Su=B({name:F(),description:W(F()),required:W(L())}),Cu=B({...Sl.shape,...xl.shape,description:W(F()),arguments:W(z(Su)),_meta:W(dc({}))}),wu=zl.extend({method:U(`prompts/list`)}),Tu=Bl.extend({prompts:z(Cu)}),Eu=tl.extend({name:F(),arguments:H(F(),F()).optional()}),Du=il.extend({method:U(`prompts/get`),params:Eu}),Ou=B({type:U(`text`),text:F(),annotations:iu.optional(),_meta:H(F(),R()).optional()}),ku=B({type:U(`image`),data:tu,mimeType:F(),annotations:iu.optional(),_meta:H(F(),R()).optional()}),Au=B({type:U(`audio`),data:tu,mimeType:F(),annotations:iu.optional(),_meta:H(F(),R()).optional()}),ju=B({type:U(`tool_use`),name:F(),id:F(),input:H(F(),R()),_meta:H(F(),R()).optional()}),Mu=B({type:U(`resource`),resource:V([eu,nu]),annotations:iu.optional(),_meta:H(F(),R()).optional()}),Nu=V([Ou,ku,Au,au.extend({type:U(`resource_link`)}),Mu]),Pu=B({role:ru,content:Nu}),Fu=sl.extend({description:F().optional(),messages:z(Pu)}),Iu=ol.extend({method:U(`notifications/prompts/list_changed`),params:al.optional()}),Lu=B({title:F().optional(),readOnlyHint:L().optional(),destructiveHint:L().optional(),idempotentHint:L().optional(),openWorldHint:L().optional()}),Ru=B({taskSupport:yc([`required`,`optional`,`forbidden`]).optional()}),zu=B({...Sl.shape,...xl.shape,description:F().optional(),inputSchema:B({type:U(`object`),properties:H(F(),Yc).optional(),required:z(F()).optional()}).catchall(R()),outputSchema:B({type:U(`object`),properties:H(F(),Yc).optional(),required:z(F()).optional()}).catchall(R()).optional(),annotations:Lu.optional(),execution:Ru.optional(),_meta:H(F(),R()).optional()}),Bu=zl.extend({method:U(`tools/list`)}),Vu=Bl.extend({tools:z(zu)}),Hu=sl.extend({content:z(Nu).default([]),structuredContent:H(F(),R()).optional(),isError:L().optional()});Hu.or(sl.extend({toolResult:R()}));const Uu=nl.extend({name:F(),arguments:H(F(),R()).optional()}),Wu=il.extend({method:U(`tools/call`),params:Uu}),Gu=ol.extend({method:U(`notifications/tools/list_changed`),params:al.optional()}),Ku=B({autoRefresh:L().default(!0),debounceMs:I().int().nonnegative().default(300)}),qu=yc([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Ju=tl.extend({level:qu}),Yu=il.extend({method:U(`logging/setLevel`),params:Ju}),Xu=al.extend({level:qu,logger:F().optional(),data:R()}),Zu=ol.extend({method:U(`notifications/message`),params:Xu}),Qu=B({hints:z(B({name:F().optional()})).optional(),costPriority:I().min(0).max(1).optional(),speedPriority:I().min(0).max(1).optional(),intelligencePriority:I().min(0).max(1).optional()}),$u=B({mode:yc([`auto`,`required`,`none`]).optional()}),ed=B({type:U(`tool_result`),toolUseId:F().describe(`The unique identifier for the corresponding tool call.`),content:z(Nu).default([]),structuredContent:B({}).loose().optional(),isError:L().optional(),_meta:H(F(),R()).optional()}),td=mc(`type`,[Ou,ku,Au]),nd=mc(`type`,[Ou,ku,Au,ju,ed]),rd=B({role:ru,content:V([nd,z(nd)]),_meta:H(F(),R()).optional()}),id=nl.extend({messages:z(rd),modelPreferences:Qu.optional(),systemPrompt:F().optional(),includeContext:yc([`none`,`thisServer`,`allServers`]).optional(),temperature:I().optional(),maxTokens:I().int(),stopSequences:z(F()).optional(),metadata:Yc.optional(),tools:z(zu).optional(),toolChoice:$u.optional()}),ad=il.extend({method:U(`sampling/createMessage`),params:id}),od=sl.extend({model:F(),stopReason:W(yc([`endTurn`,`stopSequence`,`maxTokens`]).or(F())),role:ru,content:td}),sd=sl.extend({model:F(),stopReason:W(yc([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(F())),role:ru,content:V([nd,z(nd)])}),cd=B({type:U(`boolean`),title:F().optional(),description:F().optional(),default:L().optional()}),ld=B({type:U(`string`),title:F().optional(),description:F().optional(),minLength:I().optional(),maxLength:I().optional(),format:yc([`email`,`uri`,`date`,`date-time`]).optional(),default:F().optional()}),ud=B({type:yc([`number`,`integer`]),title:F().optional(),description:F().optional(),minimum:I().optional(),maximum:I().optional(),default:I().optional()}),dd=B({type:U(`string`),title:F().optional(),description:F().optional(),enum:z(F()),default:F().optional()}),fd=B({type:U(`string`),title:F().optional(),description:F().optional(),oneOf:z(B({const:F(),title:F()})),default:F().optional()}),pd=V([V([B({type:U(`string`),title:F().optional(),description:F().optional(),enum:z(F()),enumNames:z(F()).optional(),default:F().optional()}),V([dd,fd]),V([B({type:U(`array`),title:F().optional(),description:F().optional(),minItems:I().optional(),maxItems:I().optional(),items:B({type:U(`string`),enum:z(F())}),default:z(F()).optional()}),B({type:U(`array`),title:F().optional(),description:F().optional(),minItems:I().optional(),maxItems:I().optional(),items:B({anyOf:z(B({const:F(),title:F()}))}),default:z(F()).optional()})])]),cd,ld,ud]),md=V([nl.extend({mode:U(`form`).optional(),message:F(),requestedSchema:B({type:U(`object`),properties:H(F(),pd),required:z(F()).optional()})}),nl.extend({mode:U(`url`),message:F(),elicitationId:F(),url:F().url()})]),hd=il.extend({method:U(`elicitation/create`),params:md}),gd=al.extend({elicitationId:F()}),_d=ol.extend({method:U(`notifications/elicitation/complete`),params:gd}),vd=sl.extend({action:yc([`accept`,`decline`,`cancel`]),content:Uc(e=>e===null?void 0:e,H(F(),V([F(),I(),L(),z(F())])).optional())}),yd=B({type:U(`ref/resource`),uri:F()}),bd=B({type:U(`ref/prompt`),name:F()}),xd=tl.extend({ref:V([bd,yd]),argument:B({name:F(),value:F()}),context:B({arguments:H(F(),F()).optional()}).optional()}),Sd=il.extend({method:U(`completion/complete`),params:xd}),Cd=sl.extend({completion:dc({values:z(F()).max(100),total:W(I().int()),hasMore:W(L())})}),wd=B({uri:F().startsWith(`file://`),name:F().optional(),_meta:H(F(),R()).optional()}),Td=il.extend({method:U(`roots/list`),params:tl.optional()}),Ed=sl.extend({roots:z(wd)}),Dd=ol.extend({method:U(`notifications/roots/list_changed`),params:al.optional()});V([Pl,kl,Sd,Yu,Du,wu,su,lu,pu,_u,yu,Wu,Bu,Kl,Jl,Yl,Zl]),V([bl,Ll,Ml,Dd,Gl]),V([vl,od,sd,vd,Ed,ql,Xl,Ul]),V([Pl,ad,hd,Td,Kl,Jl,Yl,Zl]),V([bl,Ll,Zu,xu,hu,Gu,Iu,Gl,_d]),V([vl,jl,Cd,Fu,Tu,cu,uu,mu,Hu,Vu,ql,Xl,Ul]);var K=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===G.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Od(e.elicitations,n)}return new e(t,n,r)}},Od=class extends K{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(G.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function kd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Ad(e){let t=ps(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=ms(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function jd(e,t){let n=fs(e,t);if(!n.success)throw n.error;return n.data}var Md=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=/* @__PURE__ */ new Map,this._requestHandlerAbortControllers=/* @__PURE__ */ new Map,this._notificationHandlers=/* @__PURE__ */ new Map,this._responseHandlers=/* @__PURE__ */ new Map,this._progressHandlers=/* @__PURE__ */ new Map,this._timeoutInfo=/* @__PURE__ */ new Map,this._pendingDebouncedNotifications=/* @__PURE__ */ new Set,this._taskProgressTokens=/* @__PURE__ */ new Map,this._requestResolvers=/* @__PURE__ */ new Map,this.setNotificationHandler(bl,e=>{this._oncancel(e)}),this.setNotificationHandler(Ll,e=>{this._onprogress(e)}),this.setRequestHandler(Pl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Kl,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Jl,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(!await this._taskStore.getTask(r,t.sessionId))throw new K(G.InvalidParams,`Task not found: ${r}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new K(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(/* @__PURE__ */ Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new K(G.InvalidParams,`Task not found: ${r}`);if(!kd(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(kd(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[Jc]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Yl,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new K(G.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Zl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Task not found: ${e.params.taskId}`);if(kd(n.status))throw new K(G.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new K(G.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof K?e:new K(G.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),K.fromError(G.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),ml(e)||gl(e)?this._onresponse(e):ul(e)?this._onrequest(e,t):fl(e)?this._onnotification(e):this._onerror(/* @__PURE__ */ Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=/* @__PURE__ */ new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=K.fromError(G.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(/* @__PURE__ */ Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Jc]?.taskId,a=r?.sessionId,o=this._taskStore,s=!0,c;if(i&&o&&this._taskMessageQueue&&a!==void 0&&(s=!1,c=(async()=>{if(!await o.getTask(i,a))throw new K(G.InvalidParams,`Task not found: ${i}`);s=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:G.MethodNotFound,message:`Method not found`}};if(i&&c){let e={type:`error`,message:t,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(i,e,a),()=>r?.send(t)).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let u=rl(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,f={signal:l.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(l.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(l.signal.aborted)throw new K(G.ConnectionClosed,`Request was cancelled`);let a={...r,relatedRequestId:e.id};i&&!a.relatedTask&&(a.relatedTask={taskId:i});let o=a.relatedTask?.taskId??i;return o&&d&&await d.updateTaskStatus(o,`input_required`),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new K(G.ConnectionClosed,`Request was cancelled`);u&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async t=>{if(l.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(l.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:G.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue&&s?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(/* @__PURE__ */ Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),ml(e)?n(e):n(new K(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(/* @__PURE__ */ Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(ml(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),ml(e)?r(e):r(K.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof K?e:new K(G.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Ul,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new K(G.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},kd(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new K(G.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new K(G.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof K?e:new K(G.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(/* @__PURE__ */ Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Jc]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send cancellation: ${e}`))),l(e instanceof K?e:new K(G.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=fs(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(K.fromError(G.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(/* @__PURE__ */ Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},ql,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Xl,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Ql,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Jc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Jc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Jc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Ad(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=jd(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Ad(e);this._notificationHandlers.set(n,n=>{let r=jd(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n??this._transport?.sessionId,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&ul(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new K(G.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(/* @__PURE__ */ Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e,n);t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted){n(new K(G.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new K(G.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new K(G.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Gl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),kd(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new K(G.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(kd(a.status))throw new K(G.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Gl.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),kd(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Nd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pd(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Nd(a)&&Nd(i)?{...a,...i}:i}return n}var Fd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Id=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Fd();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=/* @__PURE__ */ new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||/* @__PURE__ */ new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),q=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Fd(),n=Id();var r=Fd();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=Id();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=se(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=se(this.rhs,e,n),this}get names(){return oe(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=se(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(ce(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ae(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(le(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=se(this.condition,e,t),this}get names(){let e=super.names;return oe(e,this.condition),this.else&&ae(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=se(this.iteration,e,t),this}get names(){return ae(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return oe(oe(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=se(this.iterable,e,t),this}get names(){return ae(super.names,this.iterable.names)}},ee=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ee.kind=`func`;var te=class extends p{render(e){return`return `+super.render(e)}};te.kind=`return`;var ne=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ae(e,this.catch.names),this.finally&&ae(e,this.finally.names),e}},re=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};re.kind=`catch`;var ie=class extends m{render(e){return`finally`+super.render(e)}};ie.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
31
|
+
`:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=/* @__PURE__ */ new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new te;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(te)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new ne;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new re(e),t(e)}return n&&(this._currNode=r.finally=new ie,this.code(n)),this._endBlockNode(re,ie)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new ee(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(ee)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function ae(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function oe(e,n){return n instanceof t._CodeOrName?ae(e,n.names):e}function se(e,n,r){return e instanceof t.Name?i(e):a(e)?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function ce(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function le(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${me(e)}`}e.not=le;let ue=pe(e.operators.AND);function de(...e){return e.reduce(ue)}e.and=de;let fe=pe(e.operators.OR);function S(...e){return e.reduce(fe)}e.or=S;function pe(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${me(n)} ${e} ${me(r)}`}function me(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),J=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=q(),n=Fd();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Ld=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Rd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=q(),n=J(),r=Ld();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){
|
|
32
32
|
/* istanbul ignore if */
|
|
33
|
-
if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),
|
|
33
|
+
if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),zd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Rd(),n=q(),r=Ld(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Bd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=/* @__PURE__ */ new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Vd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Hd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Bd(),n=Vd(),r=Rd(),i=q(),a=J();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=/* @__PURE__ */ new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
|
|
34
34
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
|
|
35
35
|
|| (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
|
|
36
|
-
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),
|
|
36
|
+
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Ud=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=q(),n=J();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Wd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=q(),n=J(),r=Ld(),i=J();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;
|
|
37
37
|
/* istanbul ignore if */
|
|
38
|
-
if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),
|
|
38
|
+
if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Gd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=q(),n=Ld(),r=Wd(),i=Rd();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){
|
|
39
39
|
/* istanbul ignore if */
|
|
40
|
-
if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Bd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=q(),n=J();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=/* @__PURE__ */ new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Vd=/* @__PURE__ */ T(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Hd=/* @__PURE__ */ T(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Ud=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=J(),n=Vd(),r=Hd(),i=/* @__PURE__ */ new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=/* @__PURE__ */ new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=/* @__PURE__ */ new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return/* @__PURE__ */ Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Wd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Nd(),n=Id(),r=Fd(),i=Id(),a=Ld(),o=zd(),s=Bd(),c=q(),l=jd(),u=Ud(),d=J(),f=Md();function p(e){if(te(e)&&(re(e),b(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&le(e),oe(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ie(e),ue(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function ee(e,n){if(te(e)&&(re(e),b(e))){ne(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function b({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function te(e){return typeof e.schema!=`boolean`}function ne(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&le(e),se(e),ce(e);let a=r.const(`_errs`,l.default.errors);ie(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function re(e){(0,d.checkUnknownRules)(e),ae(e)}function ie(e,t){if(e.opts.jtd)return fe(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);fe(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ae(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function oe(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function se(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ce(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function le({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ue(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&de(e),t.return((0,c._)`${l.default.errors} === 0`))}function de({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function fe(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>be(e,`$ref`,h.all.$ref.definition));return}p.jtd||x(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),pe(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):pe(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function pe(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&be(e,n.keyword,n.definition,t.type)})}function x(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(me(e,t),e.opts.allowUnionTypes||he(e,t),ge(e,e.dataTypes))}function me(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{ve(e.dataTypes,t)||S(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),ye(e,t)}}function he(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&S(e,`use allowUnionTypes to allow union type keyword`)}function ge(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>_e(t,e))&&S(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function _e(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function ve(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function ye(e,t){let n=[];for(let r of e.dataTypes)ve(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function S(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var C=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,Ce(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){
|
|
40
|
+
if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Kd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=q(),n=J();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=/* @__PURE__ */ new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),qd=/* @__PURE__ */ E(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Jd=/* @__PURE__ */ E(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Yd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=J(),n=qd(),r=Jd(),i=/* @__PURE__ */ new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=/* @__PURE__ */ new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=/* @__PURE__ */ new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return/* @__PURE__ */ Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Xd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=zd(),n=Hd(),r=Vd(),i=Hd(),a=Ud(),o=Gd(),s=Kd(),c=q(),l=Ld(),u=Yd(),d=J(),f=Rd();function p(e){if(ee(e)&&(ne(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&ce(e),ae(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),re(e),le(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(ee(e)&&(ne(e),x(e))){te(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function ee(e){return typeof e.schema!=`boolean`}function te(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&ce(e),oe(e),se(e);let a=r.const(`_errs`,l.default.errors);re(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function ne(e){(0,d.checkUnknownRules)(e),ie(e)}function re(e,t){if(e.opts.jtd)return de(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);de(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ie(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function ae(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function oe(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function se(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function ce({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function le(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ue(e),t.return((0,c._)`${l.default.errors} === 0`))}function ue({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function de(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ye(e,`$ref`,h.all.$ref.definition));return}p.jtd||S(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),fe(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):fe(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function fe(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ye(e,n.keyword,n.definition,t.type)})}function S(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(pe(e,t),e.opts.allowUnionTypes||me(e,t),he(e,e.dataTypes))}function pe(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{_e(e.dataTypes,t)||C(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),ve(e,t)}}function me(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&C(e,`use allowUnionTypes to allow union type keyword`)}function he(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>ge(t,e))&&C(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ge(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function _e(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function ve(e,t){let n=[];for(let r of e.dataTypes)_e(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function C(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var w=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,Se(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){
|
|
41
41
|
/* istanbul ignore if */
|
|
42
|
-
if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return ee(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=C;function be(e,t,n,r){let i=new C(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let xe=/^\/(?:[^~]|~0|~1)*$/,Se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ce(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!xe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=Se.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=Ce})),Gd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Kd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ud();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),qd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=q(),n=Gd(),r=jd(),i=Ud(),a=J(),o=Wd();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:/* @__PURE__ */ new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=/* @__PURE__ */ new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Jd=/* @__PURE__ */ T(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Yd=/* @__PURE__ */ T(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),a=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function s(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let c=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function l(e){return e.length=0,!0}function u(e,t,n){if(e.length){let r=s(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function d(e){let t=0,n={error:!1,address:``,zone:``},r=[],i=[],a=!1,o=!1,c=u;for(let s=0;s<e.length;s++){let u=e[s];if(u!==`[`&&u!==`]`){if(u===`:`){if(a===!0&&(o=!0),!c(i,r,n))break;if(++t>7){n.error=!0;break}s>0&&e[s-1]===`:`&&(a=!0),r.push(`:`);continue}if(u===`%`){if(!c(i,r,n))break;c=l}else{i.push(u);continue}}}return i.length&&(c===l?n.zone=i.join(``):o?r.push(i.join(``)):r.push(s(i))),n.address=r.join(``),n}function f(e){if(p(e,`:`)<2)return{host:e,isIPV6:!1};let t=d(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function p(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function m(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}let h={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},g=/[@/?#:]/g,_=/[@/?#]/g;function v(e,t){let n=t?_:g;return n.lastIndex=0,e.replace(n,e=>h[e])}function y(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let o=e.slice(r+1,r+3);if(i(o)){let e=o.toUpperCase(),i=String.fromCharCode(parseInt(e,16));t&&a(i)?n+=i:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ee(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&a(i)?t+=i:t+=`%`+e,n+=2;continue}}o(e[n])?t+=e[n]:t+=escape(e[n])}return t}function b(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function te(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let e=f(n);n=e.isIPV6===!0?`[${e.escapedHost}]`:v(n,!1)}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:c,recomposeAuthority:te,reescapeHostDelimiters:v,normalizePercentEncoding:y,normalizePathEncoding:ee,escapePreservingEscapes:b,removeDotSegments:m,isIPv4:r,isUUID:n,normalizeIPv6:f,stringArrayToHexStripped:s}})),Xd=/* @__PURE__ */ T(((e,t)=>{let{isUUID:n}=Yd(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),Zd=/* @__PURE__ */ T(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,escapePreservingEscapes:s,reescapeHostDelimiters:c,isIPv4:l,nonSimpleDomain:u}=Yd(),{SCHEMES:d,getSchemeHandler:f}=Xd();function p(e,t){return typeof e==`string`?e=te(e,t):typeof e==`object`&&(e=b(_(e,t),t)),e}function m(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=h(b(e,r),b(t,r),r,!0);return r.skipEscape=!0,_(i,r)}function h(e,t,n,i){let a={};return i||(e=b(_(e,n),n),t=b(_(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function g(e,t,n){let r=re(e,n),i=re(t,n);return r!==void 0&&i!==void 0&&r.toLowerCase()===i.toLowerCase()}function _(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[],l=f(o.scheme||n.scheme);l&&l.serialize&&l.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=a(n.path):(n.path=s(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),o.reference!==`suffix`&&n.scheme&&c.push(n.scheme,`:`);let u=i(n);if(u!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(u),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!l||!l.absolutePath)&&(e=r(e)),u===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,n.query),n.fragment!==void 0&&c.push(`#`,n.fragment),c.join(``)}let v=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function y(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function ee(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1,s=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let d=e.match(v);if(d){i.scheme=d[1],i.userinfo=d[3],i.host=d[4],i.port=parseInt(d[5],10),i.path=d[6]||``,i.query=d[7],i.fragment=d[8],isNaN(i.port)&&(i.port=d[5]);let t=y(i,d);if(t!==void 0&&(i.error=i.error||t,a=!0),i.host){if(l(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),s=e.isIPV6}else s=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let p=f(r.scheme||i.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&i.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&u(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}if((!p||p&&!p.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=c(unescape(i.host),s))),i.path&&=o(i.path),i.fragment))try{i.fragment=encodeURI(decodeURIComponent(i.fragment))}catch{i.error=i.error||`URI malformed`}p&&p.parse&&p.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:a}}function b(e,t){return ee(e,t).parsed}function te(e,t){return ne(e,t).normalized}function ne(e,t){let{parsed:n,malformedAuthorityOrPort:r}=ee(e,t);return{normalized:r?e:_(n,t),malformedAuthorityOrPort:r}}function re(e,t){if(typeof e==`string`){let{normalized:n,malformedAuthorityOrPort:r}=ne(e,t);return r?void 0:n}if(typeof e==`object`)return _(e,t)}let ie={SCHEMES:d,normalize:p,resolve:m,resolveComponent:h,equal:g,serialize:_,parse:b};t.exports=ie,t.exports.default=ie,t.exports.fastUri=ie})),Qd=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zd();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),$d=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Wd();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=Gd(),i=Kd(),a=Pd(),o=qd(),s=q(),c=Ud(),l=Id(),u=J(),d=Jd(),f=Qd(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=/* @__PURE__ */ new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=/* @__PURE__ */ new Set,this._loading={},this._cache=/* @__PURE__ */ new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=oe(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),ee.call(this,g,e,`NOT SUPPORTED`),ee.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=ie.call(this),e.formats&&ne.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&re.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),te.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=b.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=b.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(ce.call(this,n,t),!t)return(0,u.eachItem)(n,e=>le.call(this,e)),this;de.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>le.call(this,e,r):e=>r.type.forEach(t=>le.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=pe(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){
|
|
42
|
+
if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=w;function ye(e,t,n,r){let i=new w(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let be=/^\/(?:[^~]|~0|~1)*$/,xe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Se(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!be.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=xe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=Se})),Zd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Qd=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yd();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),$d=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=q(),n=Zd(),r=Ld(),i=Yd(),a=J(),o=Xd();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:/* @__PURE__ */ new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=/* @__PURE__ */ new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),ef=/* @__PURE__ */ E(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),tf=/* @__PURE__ */ E(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),a=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function s(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let c=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function l(e){return e.length=0,!0}function u(e,t,n){if(e.length){let r=s(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function d(e){let t=0,n={error:!1,address:``,zone:``},r=[],i=[],a=!1,o=!1,c=u;for(let s=0;s<e.length;s++){let u=e[s];if(u!==`[`&&u!==`]`){if(u===`:`){if(a===!0&&(o=!0),!c(i,r,n))break;if(++t>7){n.error=!0;break}s>0&&e[s-1]===`:`&&(a=!0),r.push(`:`);continue}if(u===`%`){if(!c(i,r,n))break;c=l}else{i.push(u);continue}}}return i.length&&(c===l?n.zone=i.join(``):o?r.push(i.join(``)):r.push(s(i))),n.address=r.join(``),n}function f(e){if(p(e,`:`)<2)return{host:e,isIPV6:!1};let t=d(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function p(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function m(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}let h={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},g=/[@/?#:]/g,_=/[@/?#]/g;function v(e,t){let n=t?_:g;return n.lastIndex=0,e.replace(n,e=>h[e])}function y(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let o=e.slice(r+1,r+3);if(i(o)){let e=o.toUpperCase(),i=String.fromCharCode(parseInt(e,16));t&&a(i)?n+=i:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function b(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&a(i)?t+=i:t+=`%`+e,n+=2;continue}}o(e[n])?t+=e[n]:t+=escape(e[n])}return t}function x(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ee(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let e=f(n);n=e.isIPV6===!0?`[${e.escapedHost}]`:v(n,!1)}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:c,recomposeAuthority:ee,reescapeHostDelimiters:v,normalizePercentEncoding:y,normalizePathEncoding:b,escapePreservingEscapes:x,removeDotSegments:m,isIPv4:r,isUUID:n,normalizeIPv6:f,stringArrayToHexStripped:s}})),nf=/* @__PURE__ */ E(((e,t)=>{let{isUUID:n}=tf(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),rf=/* @__PURE__ */ E(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,escapePreservingEscapes:s,reescapeHostDelimiters:c,isIPv4:l,nonSimpleDomain:u}=tf(),{SCHEMES:d,getSchemeHandler:f}=nf();function p(e,t){return typeof e==`string`?e=ee(e,t):typeof e==`object`&&(e=x(_(e,t),t)),e}function m(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=h(x(e,r),x(t,r),r,!0);return r.skipEscape=!0,_(i,r)}function h(e,t,n,i){let a={};return i||(e=x(_(e,n),n),t=x(_(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function g(e,t,n){let r=ne(e,n),i=ne(t,n);return r!==void 0&&i!==void 0&&r.toLowerCase()===i.toLowerCase()}function _(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[],l=f(o.scheme||n.scheme);l&&l.serialize&&l.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=a(n.path):(n.path=s(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),o.reference!==`suffix`&&n.scheme&&c.push(n.scheme,`:`);let u=i(n);if(u!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(u),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!l||!l.absolutePath)&&(e=r(e)),u===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,n.query),n.fragment!==void 0&&c.push(`#`,n.fragment),c.join(``)}let v=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function y(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function b(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1,s=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let d=e.match(v);if(d){i.scheme=d[1],i.userinfo=d[3],i.host=d[4],i.port=parseInt(d[5],10),i.path=d[6]||``,i.query=d[7],i.fragment=d[8],isNaN(i.port)&&(i.port=d[5]);let t=y(i,d);if(t!==void 0&&(i.error=i.error||t,a=!0),i.host){if(l(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),s=e.isIPV6}else s=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let p=f(r.scheme||i.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&i.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&u(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}if((!p||p&&!p.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=c(unescape(i.host),s))),i.path&&=o(i.path),i.fragment))try{i.fragment=encodeURI(decodeURIComponent(i.fragment))}catch{i.error=i.error||`URI malformed`}p&&p.parse&&p.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:a}}function x(e,t){return b(e,t).parsed}function ee(e,t){return te(e,t).normalized}function te(e,t){let{parsed:n,malformedAuthorityOrPort:r}=b(e,t);return{normalized:r?e:_(n,t),malformedAuthorityOrPort:r}}function ne(e,t){if(typeof e==`string`){let{normalized:n,malformedAuthorityOrPort:r}=te(e,t);return r?void 0:n}if(typeof e==`object`)return _(e,t)}let re={SCHEMES:d,normalize:p,resolve:m,resolveComponent:h,equal:g,serialize:_,parse:x};t.exports=re,t.exports.default=re,t.exports.fastUri=re})),af=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rf();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),of=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Xd();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=Zd(),i=Qd(),a=Bd(),o=$d(),s=q(),c=Yd(),l=Hd(),u=J(),d=ef(),f=af(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=/* @__PURE__ */ new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=/* @__PURE__ */ new Set,this._loading={},this._cache=/* @__PURE__ */ new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ae(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=re.call(this),e.formats&&te.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ne.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),ee.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(se.call(this,n,t),!t)return(0,u.eachItem)(n,e=>ce.call(this,e)),this;ue.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>ce.call(this,e,r):e=>r.type.forEach(t=>ce.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=fe(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){
|
|
43
43
|
/* istanbul ignore if */
|
|
44
|
-
if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function ee(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function b(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function te(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function ne(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function re(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function ie(){let e={...this.opts};for(let t of m)delete e[t];return e}let ae={log(){},warn(){},error(){}};function oe(e){if(e===!1)return ae;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let se=/^[a-z_$][a-z0-9_$:-]*$/i;function ce(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!se.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function le(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ue.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ue(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function de(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=pe(t)),e.validateSchema=this.compile(t,!0))}let fe={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function pe(e){return{anyOf:[e,fe]}}})),ef=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),tf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Kd(),n=Rd(),r=q(),i=jd(),a=qd(),o=J(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),nf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ef(),n=tf();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),rf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),af=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),of=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),sf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r=of();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),cf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Rd(),n=J(),r=q();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),lf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),uf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Rd(),n=q(),r=J();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),df=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),ff=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Vd();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),pf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Id(),n=q(),r=J(),i=ff();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),mf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r=ff();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),hf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r=ff();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{
|
|
44
|
+
if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function ee(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function te(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ne(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function re(){let e={...this.opts};for(let t of m)delete e[t];return e}let ie={log(){},warn(){},error(){}};function ae(e){if(e===!1)return ie;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let oe=/^[a-z_$][a-z0-9_$:-]*$/i;function se(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!oe.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function ce(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?le.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function le(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function ue(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=fe(t)),e.validateSchema=this.compile(t,!0))}let de={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function fe(e){return{anyOf:[e,de]}}})),sf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),cf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=Qd(),n=Wd(),r=q(),i=Ld(),a=$d(),o=J(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),lf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=sf(),n=cf();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),uf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),df=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),ff=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),pf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r=ff();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),mf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wd(),n=J(),r=q();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),hf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),gf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wd(),n=q(),r=J();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),_f=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),vf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qd();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),yf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Hd(),n=q(),r=J(),i=vf();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),bf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r=vf();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),xf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r=vf();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{
|
|
45
45
|
/* istanbul ignore if */
|
|
46
|
-
if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),
|
|
46
|
+
if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),Sf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=uf(),n=df(),r=pf(),i=mf(),a=hf(),o=gf(),s=_f(),c=yf(),l=bf(),u=xf();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),Cf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=q(),n=J(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),wf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=q(),n=J(),r=Wd(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),Tf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wf();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Ef=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r=Wd(),i=Cf();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),Df=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),Of=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=q(),n=J(),r=Wd();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
47
47
|
missingProperty: ${i},
|
|
48
48
|
depsCount: ${n},
|
|
49
|
-
deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),
|
|
49
|
+
deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),kf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),Af=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wd(),n=q(),r=Ld(),i=J();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;
|
|
50
50
|
/* istanbul ignore if */
|
|
51
|
-
if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),
|
|
51
|
+
if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),jf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xd(),n=Wd(),r=J(),i=Af();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Mf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wd(),n=q(),r=J(),i=J();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),Nf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=J();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),Pf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Wd().validateUnion,error:{message:`must match a schema in anyOf`}}})),Ff=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;
|
|
52
52
|
/* istanbul ignore if */
|
|
53
|
-
if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),
|
|
53
|
+
if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),If=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=J();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;
|
|
54
54
|
/* istanbul ignore if */
|
|
55
|
-
if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),jf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Mf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=J();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Nf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=_f(),n=yf(),r=vf(),i=bf(),a=xf(),o=Sf(),s=Cf(),c=wf(),l=Tf(),u=Ef(),d=Df(),f=Of(),p=kf(),m=Af(),h=jf(),g=Mf();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Pf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Ff=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Pf().default]})),If=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Lf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=nf(),n=gf(),r=Nf(),i=Ff(),a=If();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Rf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),zf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=Rf(),r=qd(),i=Kd(),a=J();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Bf=/* @__PURE__ */ T(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Vf=/* @__PURE__ */ T(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=$d(),r=Lf(),i=zf(),a=Bf(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=Wd();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=Gd();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=Kd();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Hf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ae,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:te},int64:{type:`number`,validate:ne},float:{type:`number`,validate:re},double:{type:`number`,validate:re},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=(/* @__PURE__ */ new Date(`2020-01-01T`+e)).valueOf(),r=(/* @__PURE__ */ new Date(`2020-01-01T`+t)).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let ee=-(2**31),b=2**31-1;function te(e){return Number.isInteger(e)&&e<=b&&e>=ee}function ne(e){return Number.isInteger(e)}function re(){return!0}let ie=/[^\\]\\Z/;function ae(e){if(ie.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Uf=/* @__PURE__ */ T((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Vf(),n=q(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Wf=/* @__PURE__ */ T(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Hf(),r=Uf(),i=q(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),Gf=/* @__PURE__ */ et(Vf(),1),Kf=/* @__PURE__ */ et(Wf(),1);function qf(){let e=new Gf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Kf.default)(e),e}var Jf=class{constructor(e){this._ajv=e??qf()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},Yf=class{constructor(e){this._client=e}async*callToolStream(e,t=Iu,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new K(G.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new K(G.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof K){yield{type:`error`,error:e};return}yield{type:`error`,error:new K(G.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function Xf(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function Zf(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}function Qf(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&Qf(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&Qf(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&Qf(n,t)}}function $f(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var ep=class extends Ed{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=/* @__PURE__ */ new Map,this._cachedKnownTaskTools=/* @__PURE__ */ new Set,this._cachedRequiredTaskTools=/* @__PURE__ */ new Set,this._listChangedDebounceTimers=/* @__PURE__ */ new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Jf,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,zu,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,Au,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,lu,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new Yf(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Od(this._capabilities,e)}setRequestHandler(e,t){let n=cs(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=ls(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=ss(ld,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new K(G.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=$f(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new K(G.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new K(G.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=ss(Ll,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new K(G.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=ss(fd,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new K(G.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{Qf(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=ss($u,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new K(G.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=ss(Ll,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new K(G.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=ss(i.tools||i.toolChoice?td:ed,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new K(G.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:Bc,capabilities:this._capabilities,clientInfo:this._clientInfo}},Tl,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!Vc.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){Xf(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&Zf(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},fl,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},_d,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},fl,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},ku,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},yu,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},nu,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},iu,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},cu,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},fl,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},fl,t)}async callTool(e,t=Iu,n){if(this.isToolTaskRequired(e.name))throw new K(G.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new K(G.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new K(G.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof K?e:new K(G.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},Fu,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=Bu.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},tp=/* @__PURE__ */ et((/* @__PURE__ */ T((e=>{
|
|
55
|
+
if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),Lf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=J(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Rf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=J();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),zf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Cf(),n=Tf(),r=wf(),i=Ef(),a=Df(),o=Of(),s=kf(),c=Af(),l=jf(),u=Mf(),d=Nf(),f=Pf(),p=Ff(),m=If(),h=Lf(),g=Rf();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Bf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Vf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Bf().default]})),Hf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Uf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lf(),n=Sf(),r=zf(),i=Vf(),a=Hf();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Wf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Gf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=q(),n=Wf(),r=$d(),i=Qd(),a=J();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Kf=/* @__PURE__ */ E(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),qf=/* @__PURE__ */ E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=of(),r=Uf(),i=Gf(),a=Kf(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=Xd();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=q();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=Zd();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=Qd();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Jf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ie,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:ee},int64:{type:`number`,validate:te},float:{type:`number`,validate:ne},double:{type:`number`,validate:ne},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=(/* @__PURE__ */ new Date(`2020-01-01T`+e)).valueOf(),r=(/* @__PURE__ */ new Date(`2020-01-01T`+t)).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function ee(e){return Number.isInteger(e)&&e<=x&&e>=b}function te(e){return Number.isInteger(e)}function ne(){return!0}let re=/[^\\]\\Z/;function ie(e){if(re.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Yf=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=qf(),n=q(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Xf=/* @__PURE__ */ E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Jf(),r=Yf(),i=q(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),Zf=/* @__PURE__ */ $e(qf(),1),Qf=/* @__PURE__ */ $e(Xf(),1);function $f(){let e=new Zf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Qf.default)(e),e}var ep=class{constructor(e){this._ajv=e??$f()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},tp=class{constructor(e){this._client=e}async*callToolStream(e,t=Hu,n){let r=this._client,i={...n,task:n?.task??(r.isToolTask(e.name)?{}:void 0)},a=r.requestStream({method:`tools/call`,params:e},t,i),o=r.getToolOutputValidator(e.name);for await(let t of a){if(t.type===`result`&&o){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new K(G.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=o(n.structuredContent);if(!e.valid){yield{type:`error`,error:new K(G.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof K){yield{type:`error`,error:e};return}yield{type:`error`,error:new K(G.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};function np(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function rp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}function ip(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&ip(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&ip(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&ip(n,t)}}function ap(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var op=class extends Md{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=/* @__PURE__ */ new Map,this._cachedKnownTaskTools=/* @__PURE__ */ new Set,this._cachedRequiredTaskTools=/* @__PURE__ */ new Set,this._listChangedDebounceTimers=/* @__PURE__ */ new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new ep,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,Gu,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,Iu,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,hu,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new tp(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Pd(this._capabilities,e)}setRequestHandler(e,t){let n=ps(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=ms(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);let i=r;return i===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=fs(hd,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new K(G.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=ap(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new K(G.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new K(G.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=fs(Ul,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new K(G.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=fs(vd,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new K(G.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{ip(u,l.content)}catch{}return l}):i===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=fs(ad,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new K(G.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=fs(Ul,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new K(G.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=fs(i.tools||i.toolChoice?sd:od,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new K(G.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:`initialize`,params:{protocolVersion:Kc,capabilities:this._capabilities,clientInfo:this._clientInfo}},jl,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!qc.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){np(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){this._capabilities&&rp(this._capabilities.tasks?.requests,e,`Client`)}async ping(e){return this.request({method:`ping`},vl,e)}async complete(e,t){return this.request({method:`completion/complete`,params:e},Cd,t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},vl,t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},Fu,t)}async listPrompts(e,t){return this.request({method:`prompts/list`,params:e},Tu,t)}async listResources(e,t){return this.request({method:`resources/list`,params:e},cu,t)}async listResourceTemplates(e,t){return this.request({method:`resources/templates/list`,params:e},uu,t)}async readResource(e,t){return this.request({method:`resources/read`,params:e},mu,t)}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},vl,t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},vl,t)}async callTool(e,t=Hu,n){if(this.isToolTaskRequired(e.name))throw new K(G.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:`tools/call`,params:e},t,n),i=this.getToolOutputValidator(e.name);if(i){if(!r.structuredContent&&!r.isError)throw new K(G.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let e=i(r.structuredContent);if(!e.valid)throw new K(G.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof K?e:new K(G.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return r}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:`tools/list`,params:e},Vu,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=Ku.safeParse(n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{let e=await r();s(null,e)}catch(e){let t=e instanceof Error?e:Error(String(e));s(t,null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},sp=/* @__PURE__ */ $e((/* @__PURE__ */ E((e=>{
|
|
56
56
|
/*!
|
|
57
57
|
* content-type
|
|
58
58
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
59
59
|
* MIT Licensed
|
|
60
60
|
*/
|
|
61
|
-
var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}})))(),1);function np(e){if(e)try{return tp.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function rp(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ip(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...rp(t.headers),...rp(r.headers)}:t.headers}):e}const ap=[301,302,303,307,308];function op(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port||e.hostname===t.hostname&&e.protocol===`http:`&&e.port===``&&t.protocol===`https:`&&t.port===``}function sp(e,t){let n=ap.includes(e.status)?e.headers.get(`location`):null;try{return n?new URL(n,t):void 0}catch{return}}function cp(e,t,n,r,i=0){let a=sp(r,t),o=r.status===307||r.status===308||(n?.method??`GET`).toUpperCase()===`GET`;if(!a||i===5||!o)return;let s=new URL(t);if((!a.username&&!a.password||a.username===s.username&&a.password===s.password)&&op(s,a))return Promise.resolve(r.body?.cancel()).then(()=>e(a,{...n,redirect:`manual`})).then(t=>cp(e,a,n,t,i+1)??t)}const lp=/* @__PURE__ */ new WeakSet;function up(e){let t=(t,n)=>(e??fetch)(t,n);return lp.add(t),t}function dp(e=fetch){return lp.has(e)?e:(t,n)=>n?.redirect===`error`||n?.redirect===`manual`?e(t,n):Promise.resolve(e(t,{...n,redirect:`manual`})).then(r=>cp(e,t,n,r)??r)}function fp(e,t){if(e.type===`opaqueredirect`)return`Redirect not followed: this runtime does not expose the redirect target`;let n=e.url||t,r=sp(e,n);if(r)return r.username=r.password=r.search=r.hash=``,r.protocol===`http:`&&new URL(n).protocol===`https:`?(r.protocol=`https:`,`Redirect to plain http not followed; try ${r.href} instead`):`Redirect to ${r.href} not followed`}let pp;pp=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function mp(e){return(await pp).getRandomValues(new Uint8Array(e))}async function hp(e){let t=``;for(;t.length<e;){let n=await mp(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function gp(e){return await hp(e)}async function _p(e){let t=await(await pp).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function vp(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gp(e);return{code_verifier:t,code_challenge:await _p(t)}}const yp=As().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Rc.custom,message:`URL must be parseable`,fatal:!0}),ir}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),bp=ac({resource:P().url(),authorization_servers:z(yp).optional(),jwks_uri:P().url().optional(),scopes_supported:z(P()).optional(),bearer_methods_supported:z(P()).optional(),resource_signing_alg_values_supported:z(P()).optional(),resource_name:P().optional(),resource_documentation:P().optional(),resource_policy_uri:P().url().optional(),resource_tos_uri:P().url().optional(),tls_client_certificate_bound_access_tokens:L().optional(),authorization_details_types_supported:z(P()).optional(),dpop_signing_alg_values_supported:z(P()).optional(),dpop_bound_access_tokens_required:L().optional()}),xp=ac({issuer:P(),authorization_endpoint:yp,token_endpoint:yp,registration_endpoint:yp.optional(),scopes_supported:z(P()).optional(),response_types_supported:z(P()),response_modes_supported:z(P()).optional(),grant_types_supported:z(P()).optional(),token_endpoint_auth_methods_supported:z(P()).optional(),token_endpoint_auth_signing_alg_values_supported:z(P()).optional(),service_documentation:yp.optional(),revocation_endpoint:yp.optional(),revocation_endpoint_auth_methods_supported:z(P()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z(P()).optional(),introspection_endpoint:P().optional(),introspection_endpoint_auth_methods_supported:z(P()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z(P()).optional(),code_challenge_methods_supported:z(P()).optional(),client_id_metadata_document_supported:L().optional()}),Sp=B({...ac({issuer:P(),authorization_endpoint:yp,token_endpoint:yp,userinfo_endpoint:yp.optional(),jwks_uri:yp,registration_endpoint:yp.optional(),scopes_supported:z(P()).optional(),response_types_supported:z(P()),response_modes_supported:z(P()).optional(),grant_types_supported:z(P()).optional(),acr_values_supported:z(P()).optional(),subject_types_supported:z(P()),id_token_signing_alg_values_supported:z(P()),id_token_encryption_alg_values_supported:z(P()).optional(),id_token_encryption_enc_values_supported:z(P()).optional(),userinfo_signing_alg_values_supported:z(P()).optional(),userinfo_encryption_alg_values_supported:z(P()).optional(),userinfo_encryption_enc_values_supported:z(P()).optional(),request_object_signing_alg_values_supported:z(P()).optional(),request_object_encryption_alg_values_supported:z(P()).optional(),request_object_encryption_enc_values_supported:z(P()).optional(),token_endpoint_auth_methods_supported:z(P()).optional(),token_endpoint_auth_signing_alg_values_supported:z(P()).optional(),display_values_supported:z(P()).optional(),claim_types_supported:z(P()).optional(),claims_supported:z(P()).optional(),service_documentation:P().optional(),claims_locales_supported:z(P()).optional(),ui_locales_supported:z(P()).optional(),claims_parameter_supported:L().optional(),request_parameter_supported:L().optional(),request_uri_parameter_supported:L().optional(),require_request_uri_registration:L().optional(),op_policy_uri:yp.optional(),op_tos_uri:yp.optional(),client_id_metadata_document_supported:L().optional()}).shape,...xp.pick({code_challenge_methods_supported:!0}).shape}),Cp=B({access_token:P(),id_token:P().optional(),token_type:P(),expires_in:zc().optional(),scope:P().optional(),refresh_token:P().optional(),issuer:P().optional().catch(void 0)}).strip(),wp=B({error:P(),error_description:P().optional(),error_uri:P().optional()}),Tp=yp.optional().or(U(``).transform(()=>void 0)),Ep=B({redirect_uris:z(yp),token_endpoint_auth_method:P().optional(),grant_types:z(P()).optional(),response_types:z(P()).optional(),client_name:P().optional(),client_uri:yp.optional(),logo_uri:Tp,scope:P().optional(),contacts:z(P()).optional(),tos_uri:Tp,policy_uri:P().optional(),jwks_uri:yp.optional(),jwks:$s().optional(),software_id:P().optional(),software_version:P().optional(),software_statement:P().optional()}).strip(),Dp=B({client_id:P(),client_secret:P().optional(),client_id_issued_at:I().optional(),client_secret_expires_at:I().optional(),issuer:P().optional().catch(void 0)}).strip(),Op=Ep.merge(Dp);B({error:P(),error_description:P().optional()}).strip(),B({token:P(),token_type_hint:P().optional()}).strip();function kp(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Ap({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var jp=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Mp=class extends jp{};Mp.errorCode=`invalid_request`;var Np=class extends jp{};Np.errorCode=`invalid_client`;var Pp=class extends jp{};Pp.errorCode=`invalid_grant`;var Fp=class extends jp{};Fp.errorCode=`unauthorized_client`;var Ip=class extends jp{};Ip.errorCode=`unsupported_grant_type`;var Lp=class extends jp{};Lp.errorCode=`invalid_scope`;var Rp=class extends jp{};Rp.errorCode=`access_denied`;var zp=class extends jp{};zp.errorCode=`server_error`;var Bp=class extends jp{};Bp.errorCode=`temporarily_unavailable`;var Vp=class extends jp{};Vp.errorCode=`unsupported_response_type`;var Hp=class extends jp{};Hp.errorCode=`unsupported_token_type`;var Up=class extends jp{};Up.errorCode=`invalid_token`;var Wp=class extends jp{};Wp.errorCode=`method_not_allowed`;var Gp=class extends jp{};Gp.errorCode=`too_many_requests`;var Kp=class extends jp{};Kp.errorCode=`invalid_client_metadata`;var qp=class extends jp{};qp.errorCode=`insufficient_scope`;var Jp=class extends jp{};Jp.errorCode=`invalid_target`;const Yp={[Mp.errorCode]:Mp,[Np.errorCode]:Np,[Pp.errorCode]:Pp,[Fp.errorCode]:Fp,[Ip.errorCode]:Ip,[Lp.errorCode]:Lp,[Rp.errorCode]:Rp,[zp.errorCode]:zp,[Bp.errorCode]:Bp,[Vp.errorCode]:Vp,[Hp.errorCode]:Hp,[Up.errorCode]:Up,[Wp.errorCode]:Wp,[Gp.errorCode]:Gp,[Kp.errorCode]:Kp,[qp.errorCode]:qp,[Jp.errorCode]:Jp};var Xp=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Zp(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Qp=`code`,$p=`S256`;function em(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Zp(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function tm(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:nm(i,a,n);return;case`client_secret_post`:rm(i,a,r);return;case`none`:im(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function nm(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function rm(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function im(e,t){t.set(`client_id`,e)}async function am(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=wp.parse(JSON.parse(n));return new(Yp[e]||zp)(t||``,r)}catch(r){let i=e instanceof Response?fp(e,e.url):void 0;return new zp(`${t?`HTTP ${t}: `:``}${i??`Invalid OAuth error response: ${r}. Raw body: ${n}`}`)}}function om(e,t){let[n,r]=[e,t];try{[n,r]=[new URL(e).href,new URL(t).href]}catch{}return n===r||n.endsWith(`/`)&&n.slice(0,-1)===r||r.endsWith(`/`)&&r.slice(0,-1)===n}function sm(e,t){if(e)return typeof e.issuer==`string`?om(e.issuer,t)?e:void 0:e.issuer==null?e:{...e,issuer:void 0}}const cm=Cp.omit({issuer:!0}),lm=Op.omit({issuer:!0});function um(e,t){return/* @__PURE__ */ Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function dm(e,t){try{return await fm(e,t)}catch(n){if(n instanceof Np||n instanceof Fp)return await e.invalidateCredentials?.(`all`),await fm(e,t);if(n instanceof Pp)return await e.invalidateCredentials?.(`tokens`),await fm(e,t);throw n}}async function fm(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await wm(c,{fetchFn:a}),!s)try{s=await _m(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await Tm(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=String(c),f=await mm(t,e,s),p=f&&s&&!e.validateResourceURL?s.resource:f,m=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,h=await Promise.resolve(e.clientInformation()),g=sm(h,d),_=e.saveClientInformation!==void 0&&!!e.redirectUrl;if(h&&!g&&!_)throw um(h,d);let v=g?.issuer==null?g:void 0,y=async()=>{try{v&&await e.saveClientInformation?.({...v,issuer:d})}catch{}};if(!g){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!pm(r))throw new Kp(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)g={client_id:r,issuer:d},await e.saveClientInformation?.(g);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);g={...await Mm(c,{metadata:l,clientMetadata:e.clientMetadata,scope:m,fetchFn:a}),issuer:d},await e.saveClientInformation(g)}}let ee=!e.redirectUrl;if(n!==void 0||ee){let t=await jm(e,c,{metadata:l,resource:p,authorizationCode:n,fetchFn:a});return await y(),await e.saveTokens({...t,issuer:d}),`AUTHORIZED`}let b=sm(await e.tokens(),d);if(b?.refresh_token&&b.issuer==null&&console.warn(`[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.`),b?.refresh_token)try{let t=await Am(c,{metadata:l,clientInformation:g,refreshToken:b.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await y(),await e.saveTokens({...t,issuer:d}),`AUTHORIZED`}catch(e){if(!(!(e instanceof jp)||e instanceof zp))throw e}let te=e.state?await e.state():void 0,{authorizationUrl:ne,codeVerifier:re}=await Dm(c,{metadata:l,clientInformation:g,state:te,redirectUrl:e.redirectUrl,scope:m,resource:p});return await e.saveCodeVerifier(re),await e.redirectToAuthorization(ne),`REDIRECT`}function pm(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function mm(e,t,n){let r=kp(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Ap({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function hm(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=gm(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=gm(e,`scope`)||void 0,s=gm(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function gm(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function _m(e,t,n=fetch){let r=await Sm(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return bp.parse(await r.json())}async function vm(e,t,n=fetch){try{return await dp(n)(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?vm(e,void 0,n):void 0;throw r}}function ym(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function bm(e,t,n=fetch){return await vm(e,{"MCP-Protocol-Version":t},n)}function xm(e,t){return!e||!e.ok&&e.status<500&&t!==`/`}async function Sm(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ym(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await bm(o,a,n);return!r?.metadataUrl&&xm(s,i.pathname)&&(s=await bm(new URL(`/.well-known/${t}`,i),a,n)),s}function Cm(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function wm(e,{fetchFn:t=fetch,protocolVersion:n=Bc}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=Cm(e);for(let{url:e,type:n}of i){let i=await vm(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?xp.parse(await i.json()):Sp.parse(await i.json())}}}async function Tm(e,t){let n,r;try{n=await _m(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await wm(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}function Em(e){return typeof e==`string`?e:e.href}async function Dm(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Qp))throw Error(`Incompatible auth server: does not support response type ${Qp}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes($p))throw Error(`Incompatible auth server: does not support code challenge method ${$p}`)}else s=new URL(`/authorize`,e);let c=await vp(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Qp),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,$p),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,Em(o)),{authorizationUrl:s,codeVerifier:l}}function Om(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function km(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,Em(a)),i?await i(c,n,s,t):r&&tm(em(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await dp(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await am(l);return cm.parse(await l.json())}async function Am(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await km(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function jm(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=async()=>{let n=await e.clientInformation(),r=sm(n,String(t));if(n&&!r)throw um(n,String(t));return r},s=await o(),c=e.clientMetadata.scope,l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(c)),!l){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);l=Om(i,await e.codeVerifier(),e.redirectUrl)}return s??=await o(),km(t,{metadata:n,tokenRequestParams:l,clientInformation:s,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function Mm(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await dp(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await am(o);return lm.parse(await o.json())}var Nm=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Pm(e){}function Fm(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Pm,onError:n=Pm,onRetry:r=Pm,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
62
|
-
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new
|
|
61
|
+
var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}})))(),1);function cp(e){if(e)try{return sp.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function lp(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function up(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...lp(t.headers),...lp(r.headers)}:t.headers}):e}const dp=[301,302,303,307,308];function fp(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port||e.hostname===t.hostname&&e.protocol===`http:`&&e.port===``&&t.protocol===`https:`&&t.port===``}function pp(e,t){let n=dp.includes(e.status)?e.headers.get(`location`):null;try{return n?new URL(n,t):void 0}catch{return}}function mp(e,t,n,r,i=0){let a=pp(r,t),o=r.status===307||r.status===308||(n?.method??`GET`).toUpperCase()===`GET`;if(!a||i===5||!o)return;let s=new URL(t);if((!a.username&&!a.password||a.username===s.username&&a.password===s.password)&&fp(s,a))return Promise.resolve(r.body?.cancel()).then(()=>e(a,{...n,redirect:`manual`})).then(t=>mp(e,a,n,t,i+1)??t)}const hp=/* @__PURE__ */ new WeakSet;function gp(e){let t=(t,n)=>(e??fetch)(t,n);return hp.add(t),t}function _p(e=fetch){return hp.has(e)?e:(t,n)=>n?.redirect===`error`||n?.redirect===`manual`?e(t,n):Promise.resolve(e(t,{...n,redirect:`manual`})).then(r=>mp(e,t,n,r)??r)}function vp(e,t){if(e.type===`opaqueredirect`)return`Redirect not followed: this runtime does not expose the redirect target`;let n=e.url||t,r=pp(e,n);if(r)return r.username=r.password=r.search=r.hash=``,r.protocol===`http:`&&new URL(n).protocol===`https:`?(r.protocol=`https:`,`Redirect to plain http not followed; try ${r.href} instead`):`Redirect to ${r.href} not followed`}let yp;yp=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function bp(e){return(await yp).getRandomValues(new Uint8Array(e))}async function xp(e){let t=``;for(;t.length<e;){let n=await bp(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function Sp(e){return await xp(e)}async function Cp(e){let t=await(await yp).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function wp(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Sp(e);return{code_verifier:t,code_challenge:await Cp(t)}}const Tp=Is().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Wc.custom,message:`URL must be parseable`,fatal:!0}),lr}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Ep=dc({resource:F().url(),authorization_servers:z(Tp).optional(),jwks_uri:F().url().optional(),scopes_supported:z(F()).optional(),bearer_methods_supported:z(F()).optional(),resource_signing_alg_values_supported:z(F()).optional(),resource_name:F().optional(),resource_documentation:F().optional(),resource_policy_uri:F().url().optional(),resource_tos_uri:F().url().optional(),tls_client_certificate_bound_access_tokens:L().optional(),authorization_details_types_supported:z(F()).optional(),dpop_signing_alg_values_supported:z(F()).optional(),dpop_bound_access_tokens_required:L().optional()}),Dp=dc({issuer:F(),authorization_endpoint:Tp,token_endpoint:Tp,registration_endpoint:Tp.optional(),scopes_supported:z(F()).optional(),response_types_supported:z(F()),response_modes_supported:z(F()).optional(),grant_types_supported:z(F()).optional(),token_endpoint_auth_methods_supported:z(F()).optional(),token_endpoint_auth_signing_alg_values_supported:z(F()).optional(),service_documentation:Tp.optional(),revocation_endpoint:Tp.optional(),revocation_endpoint_auth_methods_supported:z(F()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z(F()).optional(),introspection_endpoint:F().optional(),introspection_endpoint_auth_methods_supported:z(F()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z(F()).optional(),code_challenge_methods_supported:z(F()).optional(),client_id_metadata_document_supported:L().optional()}),Op=B({...dc({issuer:F(),authorization_endpoint:Tp,token_endpoint:Tp,userinfo_endpoint:Tp.optional(),jwks_uri:Tp,registration_endpoint:Tp.optional(),scopes_supported:z(F()).optional(),response_types_supported:z(F()),response_modes_supported:z(F()).optional(),grant_types_supported:z(F()).optional(),acr_values_supported:z(F()).optional(),subject_types_supported:z(F()),id_token_signing_alg_values_supported:z(F()),id_token_encryption_alg_values_supported:z(F()).optional(),id_token_encryption_enc_values_supported:z(F()).optional(),userinfo_signing_alg_values_supported:z(F()).optional(),userinfo_encryption_alg_values_supported:z(F()).optional(),userinfo_encryption_enc_values_supported:z(F()).optional(),request_object_signing_alg_values_supported:z(F()).optional(),request_object_encryption_alg_values_supported:z(F()).optional(),request_object_encryption_enc_values_supported:z(F()).optional(),token_endpoint_auth_methods_supported:z(F()).optional(),token_endpoint_auth_signing_alg_values_supported:z(F()).optional(),display_values_supported:z(F()).optional(),claim_types_supported:z(F()).optional(),claims_supported:z(F()).optional(),service_documentation:F().optional(),claims_locales_supported:z(F()).optional(),ui_locales_supported:z(F()).optional(),claims_parameter_supported:L().optional(),request_parameter_supported:L().optional(),request_uri_parameter_supported:L().optional(),require_request_uri_registration:L().optional(),op_policy_uri:Tp.optional(),op_tos_uri:Tp.optional(),client_id_metadata_document_supported:L().optional()}).shape,...Dp.pick({code_challenge_methods_supported:!0}).shape}),kp=B({access_token:F(),id_token:F().optional(),token_type:F(),expires_in:Gc().optional(),scope:F().optional(),refresh_token:F().optional(),issuer:F().optional().catch(void 0)}).strip(),Ap=B({error:F(),error_description:F().optional(),error_uri:F().optional()}),jp=Tp.optional().or(U(``).transform(()=>void 0)),Mp=B({redirect_uris:z(Tp),token_endpoint_auth_method:F().optional(),grant_types:z(F()).optional(),response_types:z(F()).optional(),client_name:F().optional(),client_uri:Tp.optional(),logo_uri:jp,scope:F().optional(),contacts:z(F()).optional(),tos_uri:jp,policy_uri:F().optional(),jwks_uri:Tp.optional(),jwks:ac().optional(),software_id:F().optional(),software_version:F().optional(),software_statement:F().optional()}).strip(),Np=B({client_id:F(),client_secret:F().optional(),client_id_issued_at:I().optional(),client_secret_expires_at:I().optional(),issuer:F().optional().catch(void 0)}).strip(),Pp=Mp.merge(Np);B({error:F(),error_description:F().optional()}).strip(),B({token:F(),token_type_hint:F().optional()}).strip();function Fp(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Ip({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var Lp=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Rp=class extends Lp{};Rp.errorCode=`invalid_request`;var zp=class extends Lp{};zp.errorCode=`invalid_client`;var Bp=class extends Lp{};Bp.errorCode=`invalid_grant`;var Vp=class extends Lp{};Vp.errorCode=`unauthorized_client`;var Hp=class extends Lp{};Hp.errorCode=`unsupported_grant_type`;var Up=class extends Lp{};Up.errorCode=`invalid_scope`;var Wp=class extends Lp{};Wp.errorCode=`access_denied`;var Gp=class extends Lp{};Gp.errorCode=`server_error`;var Kp=class extends Lp{};Kp.errorCode=`temporarily_unavailable`;var qp=class extends Lp{};qp.errorCode=`unsupported_response_type`;var Jp=class extends Lp{};Jp.errorCode=`unsupported_token_type`;var Yp=class extends Lp{};Yp.errorCode=`invalid_token`;var Xp=class extends Lp{};Xp.errorCode=`method_not_allowed`;var Zp=class extends Lp{};Zp.errorCode=`too_many_requests`;var Qp=class extends Lp{};Qp.errorCode=`invalid_client_metadata`;var $p=class extends Lp{};$p.errorCode=`insufficient_scope`;var em=class extends Lp{};em.errorCode=`invalid_target`;const tm={[Rp.errorCode]:Rp,[zp.errorCode]:zp,[Bp.errorCode]:Bp,[Vp.errorCode]:Vp,[Hp.errorCode]:Hp,[Up.errorCode]:Up,[Wp.errorCode]:Wp,[Gp.errorCode]:Gp,[Kp.errorCode]:Kp,[qp.errorCode]:qp,[Jp.errorCode]:Jp,[Yp.errorCode]:Yp,[Xp.errorCode]:Xp,[Zp.errorCode]:Zp,[Qp.errorCode]:Qp,[$p.errorCode]:$p,[em.errorCode]:em};var nm=class extends Error{constructor(e){super(e??`Unauthorized`)}};function rm(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const im=`code`,am=`S256`;function om(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&rm(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function sm(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:cm(i,a,n);return;case`client_secret_post`:lm(i,a,r);return;case`none`:um(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function cm(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function lm(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function um(e,t){t.set(`client_id`,e)}async function dm(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=Ap.parse(JSON.parse(n));return new(tm[e]||Gp)(t||``,r)}catch(r){let i=e instanceof Response?vp(e,e.url):void 0;return new Gp(`${t?`HTTP ${t}: `:``}${i??`Invalid OAuth error response: ${r}. Raw body: ${n}`}`)}}function fm(e,t){let[n,r]=[e,t];try{[n,r]=[new URL(e).href,new URL(t).href]}catch{}return n===r||n.endsWith(`/`)&&n.slice(0,-1)===r||r.endsWith(`/`)&&r.slice(0,-1)===n}function pm(e,t){if(e)return typeof e.issuer==`string`?fm(e.issuer,t)?e:void 0:e.issuer==null?e:{...e,issuer:void 0}}const mm=kp.omit({issuer:!0}),hm=Pp.omit({issuer:!0});function gm(e,t){return/* @__PURE__ */ Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function _m(e,t){try{return await vm(e,t)}catch(n){if(n instanceof zp||n instanceof Vp)return await e.invalidateCredentials?.(`all`),await vm(e,t);if(n instanceof Bp)return await e.invalidateCredentials?.(`tokens`),await vm(e,t);throw n}}async function vm(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await Am(c,{fetchFn:a}),!s)try{s=await Cm(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await jm(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=String(c),f=await bm(t,e,s),p=f&&s&&!e.validateResourceURL?s.resource:f,m=r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,h=await Promise.resolve(e.clientInformation()),g=pm(h,d),_=e.saveClientInformation!==void 0&&!!e.redirectUrl;if(h&&!g&&!_)throw gm(h,d);let v=g?.issuer==null?g:void 0,y=async()=>{try{v&&await e.saveClientInformation?.({...v,issuer:d})}catch{}};if(!g){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!ym(r))throw new Qp(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)g={client_id:r,issuer:d},await e.saveClientInformation?.(g);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);g={...await Rm(c,{metadata:l,clientMetadata:e.clientMetadata,scope:m,fetchFn:a}),issuer:d},await e.saveClientInformation(g)}}let b=!e.redirectUrl;if(n!==void 0||b){let t=await Lm(e,c,{metadata:l,resource:p,authorizationCode:n,fetchFn:a});return await y(),await e.saveTokens({...t,issuer:d}),`AUTHORIZED`}let x=pm(await e.tokens(),d);if(x?.refresh_token&&x.issuer==null&&console.warn(`[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.`),x?.refresh_token)try{let t=await Im(c,{metadata:l,clientInformation:g,refreshToken:x.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await y(),await e.saveTokens({...t,issuer:d}),`AUTHORIZED`}catch(e){if(!(!(e instanceof Lp)||e instanceof Gp))throw e}let ee=e.state?await e.state():void 0,{authorizationUrl:te,codeVerifier:ne}=await Nm(c,{metadata:l,clientInformation:g,state:ee,redirectUrl:e.redirectUrl,scope:m,resource:p});return await e.saveCodeVerifier(ne),await e.redirectToAuthorization(te),`REDIRECT`}function ym(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function bm(e,t,n){let r=Fp(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Ip({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function xm(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Sm(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Sm(e,`scope`)||void 0,s=Sm(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Sm(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function Cm(e,t,n=fetch){let r=await Om(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Ep.parse(await r.json())}async function wm(e,t,n=fetch){try{return await _p(n)(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?wm(e,void 0,n):void 0;throw r}}function Tm(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Em(e,t,n=fetch){return await wm(e,{"MCP-Protocol-Version":t},n)}function Dm(e,t){return!e||!e.ok&&e.status<500&&t!==`/`}async function Om(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Tm(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Em(o,a,n);return!r?.metadataUrl&&Dm(s,i.pathname)&&(s=await Em(new URL(`/.well-known/${t}`,i),a,n)),s}function km(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function Am(e,{fetchFn:t=fetch,protocolVersion:n=Kc}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=km(e);for(let{url:e,type:n}of i){let i=await wm(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?Dp.parse(await i.json()):Op.parse(await i.json())}}}async function jm(e,t){let n,r;try{n=await Cm(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await Am(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}function Mm(e){return typeof e==`string`?e:e.href}async function Nm(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(im))throw Error(`Incompatible auth server: does not support response type ${im}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(am))throw Error(`Incompatible auth server: does not support code challenge method ${am}`)}else s=new URL(`/authorize`,e);let c=await wp(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,im),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,am),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,Mm(o)),{authorizationUrl:s,codeVerifier:l}}function Pm(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Fm(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,Mm(a)),i?await i(c,n,s,t):r&&sm(om(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await _p(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await dm(l);return mm.parse(await l.json())}async function Im(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await Fm(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function Lm(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=async()=>{let n=await e.clientInformation(),r=pm(n,String(t));if(n&&!r)throw gm(n,String(t));return r},s=await o(),c=e.clientMetadata.scope,l;if(e.prepareTokenRequest&&(l=await e.prepareTokenRequest(c)),!l){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);l=Pm(i,await e.codeVerifier(),e.redirectUrl)}return s??=await o(),Fm(t,{metadata:n,tokenRequestParams:l,clientInformation:s,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function Rm(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await _p(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await dm(o);return hm.parse(await o.json())}var zm=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Bm(e){}function Vm(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Bm,onError:n=Bm,onRetry:r=Bm,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
62
|
+
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new zm(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
|
|
63
63
|
`,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
|
|
64
|
-
`,n);continue}let i=e.charCodeAt(n);if(
|
|
64
|
+
`,n);continue}let i=e.charCodeAt(n);if(Hm(e,n,i)){let i=e.charCodeAt(n+5)===32?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===10){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
|
|
65
65
|
`,n);continue}u=d===0?a:`${u}
|
|
66
|
-
${a}`,d++}else
|
|
66
|
+
${a}`,d++}else Um(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
|
|
67
67
|
`,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
|
|
68
|
-
`,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(
|
|
69
|
-
${i}`,d++;return}if(
|
|
70
|
-
${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Nm(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Nm(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function ee(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:ee}}function Im(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Lm(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Rm=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=Fm({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}};const zm={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Bm=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Vm=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=ip(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy===`follow`,this._followRedirects&&(this._fetch=up(this._fetch),this._fetchWithInit=up(this._fetchWithInit)),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??zm}_unfollowedRedirect(e,t){let n=fp(e,t);return n&&!this._followRedirects?`${n} (redirectPolicy: 'same-origin')`:n}async _authThenStart(){if(!this._authProvider)throw new Xp(`No auth provider`);let e;try{e=await dm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Xp;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=rp(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=this._fetch??fetch,i={method:`GET`,headers:n,signal:this._abortController?.signal},a=await r(this._url,this._followRedirects?i:{...i,redirect:`manual`}),o=this._followRedirects?void 0:cp(r,this._url,i,a);if(o&&(a=await o),!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new Bm(a.status,`Failed to open SSE stream: ${this._unfollowedRedirect(a,this._url)??a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(/* @__PURE__ */ Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(/* @__PURE__ */ Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Rm({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=dl.parse(JSON.parse(e.data));cl(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(/* @__PURE__ */ Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(/* @__PURE__ */ Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Xp(`No auth provider`);if(await dm(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Xp(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:il(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await dp(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Bm(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=hm(o);if(this._resourceMetadataUrl=t,this._scope=n,await dm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Xp;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=hm(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Bm(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await dm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Xp;return this.send(e)}}throw new Bm(o.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(o,this._url)??t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Dl(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`),u=np(l);if(c){if(u===`text/event-stream`)this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(u===`application/json`){let e=await o.json(),t=Array.isArray(e)?e.map(e=>dl.parse(e)):[dl.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Bm(-1,`Unexpected content type: ${l}`)}else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await dp(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Bm(n.status,`Failed to terminate session: ${this._unfollowedRedirect(n,this._url)??n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},Hm=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(Gm(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(Gm(this),t)}};function Um(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Wm(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Wm).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Wm(e.cause)}`:e.message:`${e}`}function Gm(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Km=e=>{throw TypeError(e)},qm=(e,t,n)=>t.has(e)||Km(`Cannot `+n),Y=(e,t,n)=>(qm(e,t,`read from private field`),n?n.call(e):t.get(e)),Jm=(e,t,n)=>t.has(e)?Km(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),X=(e,t,n,r)=>(qm(e,t,`write to private field`),t.set(e,n),n),Ym=(e,t,n)=>(qm(e,t,`access private method`),n),Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh=class extends EventTarget{constructor(e,t){super(),Jm(this,lh),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Jm(this,Xm),Jm(this,Zm),Jm(this,Qm),Jm(this,$m),Jm(this,eh),Jm(this,th),Jm(this,nh),Jm(this,rh,null),Jm(this,ih),Jm(this,ah),Jm(this,oh,null),Jm(this,sh,null),Jm(this,ch,null),Jm(this,dh,async e=>{var t;Y(this,ah).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Ym(this,lh,gh).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?X(this,Qm,new URL(e.url)):X(this,Qm,void 0),i!==200){Ym(this,lh,gh).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Ym(this,lh,gh).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(Y(this,Xm)===this.CLOSED)return;X(this,Xm,this.OPEN);let o=new Event(`open`);if((t=Y(this,ch))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Ym(this,lh,gh).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&Y(this,ah).feed(s.decode(t,{stream:!e})),e&&(l=!1,Y(this,ah).reset(),Ym(this,lh,_h).call(this))}while(l)}),Jm(this,fh,e=>{X(this,ih,void 0),e.name!==`AbortError`&&e.type!==`aborted`&&Ym(this,lh,_h).call(this,Wm(e))}),Jm(this,mh,e=>{typeof e.id==`string`&&X(this,rh,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:Y(this,Qm)?Y(this,Qm).origin:Y(this,Zm).origin,lastEventId:e.id||``});Y(this,sh)&&(!e.event||e.event===`message`)&&Y(this,sh).call(this,t),this.dispatchEvent(t)}),Jm(this,hh,e=>{X(this,th,e)}),Jm(this,vh,()=>{X(this,nh,void 0),Y(this,Xm)===this.CONNECTING&&Ym(this,lh,uh).call(this)});try{if(e instanceof URL)X(this,Zm,e);else if(typeof e==`string`)X(this,Zm,new URL(e,bh()));else throw Error(`Invalid URL`)}catch{throw Um(`An invalid or illegal string was specified`)}X(this,ah,Fm({onEvent:Y(this,mh),onRetry:Y(this,hh)})),X(this,Xm,this.CONNECTING),X(this,th,3e3),X(this,eh,t?.fetch??globalThis.fetch),X(this,$m,t?.withCredentials??!1),Ym(this,lh,uh).call(this)}get readyState(){return Y(this,Xm)}get url(){return Y(this,Zm).href}get withCredentials(){return Y(this,$m)}get onerror(){return Y(this,oh)}set onerror(e){X(this,oh,e)}get onmessage(){return Y(this,sh)}set onmessage(e){X(this,sh,e)}get onopen(){return Y(this,ch)}set onopen(e){X(this,ch,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){Y(this,nh)&&clearTimeout(Y(this,nh)),Y(this,Xm)!==this.CLOSED&&(Y(this,ih)&&Y(this,ih).abort(),X(this,Xm,this.CLOSED),X(this,ih,void 0))}};Xm=/* @__PURE__ */ new WeakMap,Zm=/* @__PURE__ */ new WeakMap,Qm=/* @__PURE__ */ new WeakMap,$m=/* @__PURE__ */ new WeakMap,eh=/* @__PURE__ */ new WeakMap,th=/* @__PURE__ */ new WeakMap,nh=/* @__PURE__ */ new WeakMap,rh=/* @__PURE__ */ new WeakMap,ih=/* @__PURE__ */ new WeakMap,ah=/* @__PURE__ */ new WeakMap,oh=/* @__PURE__ */ new WeakMap,sh=/* @__PURE__ */ new WeakMap,ch=/* @__PURE__ */ new WeakMap,lh=/* @__PURE__ */ new WeakSet,uh=function(){X(this,Xm,this.CONNECTING),X(this,ih,new AbortController),Y(this,eh)(Y(this,Zm),Ym(this,lh,ph).call(this)).then(Y(this,dh)).catch(Y(this,fh))},dh=/* @__PURE__ */ new WeakMap,fh=/* @__PURE__ */ new WeakMap,ph=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...Y(this,rh)?{"Last-Event-ID":Y(this,rh)}:void 0},cache:`no-store`,signal:Y(this,ih)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},mh=/* @__PURE__ */ new WeakMap,hh=/* @__PURE__ */ new WeakMap,gh=function(e,t){var n;Y(this,Xm)!==this.CLOSED&&X(this,Xm,this.CLOSED);let r=new Hm(`error`,{code:t,message:e});(n=Y(this,oh))==null||n.call(this,r),this.dispatchEvent(r)},_h=function(e,t){var n;if(Y(this,Xm)===this.CLOSED)return;X(this,Xm,this.CONNECTING);let r=new Hm(`error`,{code:t,message:e});(n=Y(this,oh))==null||n.call(this,r),this.dispatchEvent(r),X(this,nh,setTimeout(Y(this,vh),Y(this,th)))},vh=/* @__PURE__ */ new WeakMap,yh.CONNECTING=0,yh.OPEN=1,yh.CLOSED=2;function bh(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}var xh=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},Sh=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=ip(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy===`follow`,this._followRedirects&&(this._fetch=up(this._fetch),this._fetchWithInit=up(this._fetchWithInit))}_unfollowedRedirect(e,t){let n=fp(e,t);return n&&!this._followRedirects?`${n} (redirectPolicy: 'same-origin')`:n}async _authThenStart(){if(!this._authProvider)throw new Xp(`No auth provider`);let e;try{e=await dm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Xp;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=rp(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch,t=this._followRedirects?e:dp(e),n;return new Promise((e,r)=>{this._eventSource=new yh(this._url.href,{...this._eventSourceInit,fetch:async(e,r)=>{let i=await this._commonHeaders();i.set(`Accept`,`text/event-stream`);let a=await t(e,{...r,headers:i});if(n=this._unfollowedRedirect(a,e),a.status===401&&a.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=hm(a);this._resourceMetadataUrl=e,this._scope=t}return a}}),this._abortController=new AbortController,this._eventSource.onerror=t=>{if(t.code===401&&this._authProvider){this._authThenStart().then(e,r);return}let i=new xh(t.code,n??t.message,t);r(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,t=>{let n=t;try{if(this._endpoint=new URL(n.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),this.onerror?.(e),this.close();return}e()}),this._eventSource.onmessage=e=>{let t=e,n;try{n=dl.parse(JSON.parse(t.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(n)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Xp(`No auth provider`);if(await dm(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Xp(`Failed to authorize`)}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw Error(`Not connected`);try{let t=await this._commonHeaders();t.set(`content-type`,`application/json`);let n={...this._requestInit,method:`POST`,headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},r=await dp(this._fetch??fetch)(this._endpoint,n);if(!r.ok){let t=await r.text().catch(()=>null);if(r.status===401&&this._authProvider){let{resourceMetadataUrl:t,scope:n}=hm(r);if(this._resourceMetadataUrl=t,this._scope=n,await dm(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Xp;return this.send(e)}throw Error(`Error POSTing to endpoint (HTTP ${r.status}): ${this._unfollowedRedirect(r,this._endpoint)??t}`)}await r.body?.cancel()}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}},Ch=class{adapter;constructor(e,t,n){this.adapter=new Oh({deps:e,url:t,authToken:n,transport:`streamable`})}initialize(){return this.adapter.initialize()}listTools(){return this.adapter.listTools()}callTool(e,t){return this.adapter.callTool(e,t)}close(){this.adapter.close()}};function wh(e,t,n){if(e instanceof D)return e;if(e instanceof K){let t=Th(e);return e.code===G.ConnectionClosed&&n?.localCloseFired?new D(t||`MCP connection closed.`,E.NETWORK):new D(`MCP error (${e.code}): ${t}`,E.GENERAL)}if(e instanceof Bm){let t=e.code;return new D(`MCP request failed: ${t}`,E.GENERAL,void 0,{api:{httpStatus:typeof t==`number`?t:void 0},cause:e})}if(e instanceof xh&&t&&t.status===e.code){let n=`MCP request failed: ${t.status} ${t.statusText}`;return t.body&&(n+=` - ${t.body.slice(0,500)}`),new D(n,E.GENERAL,void 0,{api:{httpStatus:t.status},cause:e})}return e}function Th(e){let t=`MCP error ${e.code}: `;return e.message.startsWith(t)?e.message.slice(t.length):e.message}function Eh(e,t,n){return async(r,i)=>{let a=i?.method??`GET`,o=typeof r==`string`?r:r.href;if(e.settings.verbose&&(console.error(`> ${a} ${o}`),typeof i?.body==`string`))try{let e=JSON.parse(i.body);e.method&&console.error(`> Method: ${e.method}`)}catch{}let s=await gn.fetch(r,i);if(e.settings.verbose&&console.error(`< ${s.status} ${s.statusText}`),!s.ok&&a===`POST`&&!Dh(s.status)){let e=`MCP request failed: ${s.status} ${s.statusText}`;try{let t=await s.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new D(e,E.GENERAL)}if(t===`sse`&&n&&!s.ok&&a===`GET`&&!Dh(s.status)){let e=``;try{e=await s.text()}catch{}n({status:s.status,statusText:s.statusText,body:e})}return s}}function Dh(e){return e>=300&&e<400}var Oh=class{deps;url;authToken;kind;serviceSource;client;transport;connecting;sseGetFailure;transportClosed=!1;constructor(e){this.deps=e.deps,this.url=e.url,this.authToken=e.authToken,this.kind=e.transport,this.serviceSource=e.serviceSource}async initialize(){if(!this.authToken)throw new D(`This command needs a model-domain API key.`,E.AUTH);return this.connecting||=this.connect().catch(e=>{throw this.connecting=void 0,this.mapTransportError(e)}),this.connecting}async listTools(){let e=await this.requireClient();try{return(await this.withLocalTimeout(e.listTools(void 0,this.requestOptions()))).tools}catch(e){throw this.mapTransportError(e)}}async callTool(e,t){let n=await this.requireClient();try{let r=await this.withLocalTimeout(n.callTool({name:e,arguments:t},void 0,this.requestOptions()));if(!Array.isArray(r.content))throw new D(`MCP tool returned an unexpected result shape.`,E.GENERAL);return r}catch(e){throw this.mapTransportError(e)}}close(){let e=this.transport;this.client=void 0,this.transport=void 0,this.connecting=void 0,this.sseGetFailure=void 0,e&&e.close().catch(()=>void 0)}mapTransportError(e){return wh(e,this.sseGetFailure,{localCloseFired:this.transportClosed})}async connect(){let e={"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...kn(this.deps.identity,this.serviceSource),Authorization:`Bearer ${this.authToken}`},t=Eh(this.deps,this.kind,e=>{this.sseGetFailure=e}),n=new URL(this.url);this.transportClosed=!1;let r=this.kind===`sse`?new Sh(n,{requestInit:{headers:e},fetch:t}):new Vm(n,{requestInit:{headers:e},fetch:t});r.onclose=()=>{this.transportClosed=!0};let i=new ep({name:this.deps.identity.clientName,version:this.deps.identity.version},{capabilities:{}});this.transport=r;let a=i.connect(r,this.requestOptions());a.catch(()=>void 0);let o,s=new Promise((e,t)=>{o=setTimeout(()=>t(new D(`MCP session handshake timed out after ${this.deps.settings.timeout}s.`,E.TIMEOUT)),this.deps.settings.timeout*1e3)});try{await Promise.race([a,s])}catch(e){throw this.transport=void 0,await r.close().catch(()=>void 0),e}finally{o&&clearTimeout(o)}if(this.transport!==r)throw await r.close().catch(()=>void 0),new D(`MCP connection was closed during the handshake.`,E.NETWORK);if(this.client=i,this.deps.settings.verbose){let e=this.kind===`sse`?`MCP SSE`:`MCP`,t=r instanceof Vm?r.sessionId??`no session`:`no session`;console.error(`[${e}] Session initialized: ${t}`),console.error(`[${e}] Server: ${JSON.stringify(i.getServerVersion()??{})}`)}}async requireClient(){if(await this.initialize(),!this.client)throw new D(`MCP client is not connected.`,E.GENERAL);return this.client}requestOptions(){return{timeout:2147483647}}async withLocalTimeout(e){let t=this.deps.settings.timeout,n,r=new Promise((e,r)=>{n=setTimeout(()=>{r(new D(`MCP request timed out after ${t}s.`,E.TIMEOUT))},t*1e3)});try{return await Promise.race([e,r])}finally{n&&clearTimeout(n)}}};function kh(e){return`/api/v1/mcps/${e}/mcp`}function Ah(e){return`/api/v1/mcps/${e}/sse`}function jh(e){return e instanceof D&&/^MCP request failed:\s*405\b/i.test(e.message)}function Mh(e){return e instanceof D&&/^MCP request failed:\s*(405|404)\b/i.test(e.message)}async function Nh(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o,serviceSource:s}=e;if(o){let e=new Oh({deps:t,url:o,authToken:n,transport:`streamable`,serviceSource:s});try{return await e.initialize(),{client:e,url:o}}catch(e){if(!Mh(e))throw e}let r=new Oh({deps:t,url:o,authToken:n,transport:`sse`,serviceSource:s});try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let c=new Oh({deps:t,url:r,authToken:n,transport:`streamable`,serviceSource:s});try{return await c.initialize(),{client:c,url:r}}catch(e){if(!jh(e)||a===`WebSearch`)throw e}let l=new Oh({deps:t,url:i,authToken:n,transport:`sse`,serviceSource:s});try{return await l.initialize(),{client:l,url:i}}catch(e){throw l.close(),e}}var Ph=class e{deps;constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new D(`This command needs a model-domain API key.`,E.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new D(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,E.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}bailianMcpRegistrationHeaders(){return{Authorization:`Bearer ${this.requireApi().token}`,...kn(this.deps.identity)}}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():this.baseUrl)+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return Mn(this.http,this.toOpts(e))}requestJson(e){return In(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return tr(e)?nr(e,this.requireApi().token,t,{signal:n.signal,baseUrl:this.url(``,n.defaultBaseUrl),identity:this.deps.identity,timeout:this.deps.settings.timeout}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return tr(e)?this.usesTokenPlanEndpoint()?Promise.resolve(Zn(e)):this.uploadFile(e,t,n):Promise.resolve(e)}usesTokenPlanEndpoint(){try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}usesTokenPlanConnection(){return this.usesTokenPlanEndpoint()||dn(this.deps.apiCred?.token??``)===`token-plan`}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Oh({deps:this.http,url:t,authToken:this.deps.apiCred?.token,transport:`streamable`})}connectBailianMcp(e,t,n){return this.requireApi(),Nh({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(kh(e)),sseUrl:this.url(Ah(e)),serverCode:e,urlOverride:t,serviceSource:n})}withConsoleSwitchAgent(t){return new e({...this.deps,settings:{...this.deps.settings,consoleSwitchAgent:t},consoleCred:this.deps.consoleCred?{...this.deps.consoleCred,switchAgent:t}:void 0})}async console(e,t){if(!this.deps.consoleCred)throw new D(`This command needs a console access token.`,E.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await Sn(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof D)||e.exitCode!==E.AUTH||!e.message.includes(`not logged in`))throw e;let t=this.deps.consoleCred,i,a=await zh({identity:this.deps.identity,settings:{...this.deps.settings,consoleRegion:t.region,consoleSite:t.site,consoleSwitchAgent:t.switchAgent},baseUrl:this.deps.baseUrl,validateToken:async e=>{i=await Sn({...t,token:e},r,n,this.deps.settings)}});if(!a)throw e;return this.deps.consoleCred={...t,token:a},i}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?Ln(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=Rn({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${Cn(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${Cn(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await gn.fetch(i,{method:e.method,headers:{...a,...kn(this.deps.identity)},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new D(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,E.GENERAL)}if(!s.ok||l.Success===!1)throw new D(`${l.Code||s.status} - ${l.Message||s.statusText}`,E.GENERAL);return l}};const Fh=/* @__PURE__ */ new Map([[`cn-beijing`,`modelstudio.cn-beijing.aliyuncs.com`],[`ap-southeast-1`,`modelstudio.ap-southeast-1.aliyuncs.com`]]);function Ih(e,t){let n=e.consoleRegion;if(!n){let e;try{e=new URL(t).hostname}catch{}n=e===`dashscope.aliyuncs.com`?`cn-beijing`:e===`dashscope-intl.aliyuncs.com`?`ap-southeast-1`:e?.match(/^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/)?.[1]}if(!n||!Fh.has(n))throw new D(`Cannot resolve a supported CLI token region. / 无法确定受支持的 CLI token 地域。`,E.USAGE,`Set console_region to cn-beijing or ap-southeast-1. / 请配置 console_region 为 cn-beijing 或 ap-southeast-1。`);return{region:n,site:e.consoleSite??`domestic`,switchAgent:e.consoleSwitchAgent}}async function Lh(e,t){let n=await Sn(e,t.timeout,{api:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,data:{}},t);if(n?.data?.success!==!0)throw new D(`Console token validation did not return success. / 控制台 token 校验未返回成功结果。`,E.GENERAL,void 0,{rawResponse:JSON.stringify(n)})}async function Rh(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Ph({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=Ih(n,r),l=Fh.get(c.region),u=await s.openApiQueryJson({host:l,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}});if(typeof u.cliAccessToken!=`string`||!u.cliAccessToken.trim())throw new D(`CLI token response is missing cliAccessToken. / CLI token 响应缺少有效的 cliAccessToken。`,E.GENERAL);return{...u,cliAccessToken:u.cliAccessToken.trim()}}async function zh(e){let t=e.settings.configName,n=Zt(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
|
|
71
|
-
`);let a=(await Rh({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i,securityToken:n.security_token})).cliAccessToken;e.validateToken?await e.validateToken(a):await Lh({...Ih(e.settings,e.baseUrl),token:a},e.settings);let o=Zt(t);return o.access_token=a,await Qt(o,t),a}function Bh(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new nt(`Workspace ID must contain only letters, digits, hyphens or underscores. / Workspace ID 只能包含字母、数字、连字符或下划线。`);return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function Vh(e){return Bh(e,``)}function Hh(e,t,n){let r;try{r=new URL(e)}catch{throw new nt(`Invalid ParseX base URL. / ParseX Base URL 无效。`)}let i=[`localhost`,`127.0.0.1`,`[::1]`].includes(r.hostname),a=r.pathname.replace(/\/+$/,``);if(r.protocol!==`https:`&&!(r.protocol===`http:`&&i)||r.username||r.password||r.search||r.hash||a)throw new nt(`ParseX base URL must be an HTTPS origin (HTTP is allowed only on loopback). / ParseX Base URL 必须为 HTTPS 源站(仅本机回环地址允许 HTTP)。`);let o=r.hostname.endsWith(`.cn-beijing.pre-maas.aliyuncs.com`)?`/api/v2/apps/pre-parse-x`:`/api/v2/apps/parse-x`;return`${r.origin}${o}/${t}/${n}`}function Uh(){return`/compatible-mode/v1/chat/completions`}function Wh(){return`/compatible-mode/v1/batches`}function Gh(e){return`${Wh()}/${encodeURIComponent(e)}`}function Kh(e){return`${Gh(e)}/cancel`}function qh(e){return`/compatible-mode/v1/files/${encodeURIComponent(e)}/content`}function Jh(){return`https://batch.dashscope.aliyuncs.com`}function Yh(){return`/compatible-mode/v1/responses`}function Xh(){return`/compatible-mode/v1/systemone`}function Zh(){return`/api/v1/services/aigc/image-generation/generation`}function Qh(){return`/api/v1/services/aigc/multimodal-generation/generation`}function $h(){return`/api/v1/services/aigc/text2image/image-synthesis`}function eg(){return`/api/v1/services/aigc/image2image/image-synthesis`}function tg(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function ng(){return`/api/v1/services/aigc/image2video/video-synthesis`}function rg(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function ig(){return`/api/v1/models/limits`}function ag(){return`/api/v1/models/permissions`}function og(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function sg(e,t){return Bh(e,t)}function cg(){return`/api/v2/apps/memory/add-async`}function lg(e){return`/api/v2/apps/memory/events/${encodeURIComponent(e)}`}function ug(){return`/api/v2/apps/memory/memory_nodes/search`}function dg(){return`/api/v2/apps/memory/memory_nodes`}function fg(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function pg(e){return`/api/v2/apps/memory/skill/export/${encodeURIComponent(e)}`}function mg(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function hg(){return`/api/v1/services/audio/asr/transcription`}function gg(){return`/api/v1/services/audio/asr/customization`}function _g(){return`/api/v2/apps/memory/profile_schemas`}function vg(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}`}function yg(e){return`${vg(e)}/user_profile`}function bg(e){return`${vg(e)}/profile_values`}function xg(e,t=`cn-beijing`){return`https://${e}.${t}.maas.aliyuncs.com`}function Sg(e){return Bh(e,`/api/v1/indices/knowledge/search`)}function Cg(e){return Bh(e,`/api/v2/apps/knowledge/chat`)}function wg(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}const Tg=`/api/v1/agentstudio/security`;function Eg(e){return`${e}${Tg}/overview`}function Dg(e){return`${e}${Tg}/agent_logs`}function Og(){return`/api/v1/mcps/WebSearch/mcp`}function kg(){return`/compatible-mode/v1/files`}function Ag(){return`/api/v1/files`}function jg(e){return`/api/v1/files/${encodeURIComponent(e)}`}function Mg(){return`/api/v1/fine-tunes`}function Ng(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Pg(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Fg(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Ig(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function Lg(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Rg(){return`/api/v1/fine-tunes/compress/templates`}function zg(){return`/api/v1/fine-tunes/compress/jobs`}function Bg(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}`}function Vg(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/cancel`}function Hg(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/logs`}function Ug(){return`/api/v1/deployments`}function Wg(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Gg(e){return`${Wg(e)}/capacity-instances`}function Kg(e,t){return`${Gg(e)}/${encodeURIComponent(t)}`}function qg(e,t){return`${Kg(e,t)}/scale`}function Jg(e,t){return`${Kg(e,t)}/renew`}function Yg(e){return`${Wg(e)}/update-overflowstrategy`}function Xg(e,t){return`${Wg(e)}/capacity-operations/${encodeURIComponent(t)}`}function Zg(e){return`${Wg(e)}/scale`}function Qg(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function $g(){return`/api/v1/deployments/models`}function e_(e,t){return Bh(e,t)}function t_(){return`/api/v1/agentstudio/files`}function n_(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function r_(e){return`/api/v1/agentstudio/sandbox${e}`}function i_(e,t){return n_(e)+r_(t)}const a_={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function o_(e){return`${a_.sandboxes}/${encodeURIComponent(e)}`}function s_(e,t){return`${o_(e)}/${t}`}function c_(e){return`${a_.templates}/${encodeURIComponent(e)}`}function l_(e,t){return`${c_(e)}/builds/${encodeURIComponent(t)}/status`}const u_={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFileDetails:`/api/v1/indices/rag/list/index/file/details`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},d_=[`qwen-image`,`wan2.7-image`,`z-image`],f_=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function p_(e,t){return t.some(t=>e.startsWith(t))}function m_(e){return p_(e,d_)||e.startsWith(`wan2.6-image`)}function h_(e){return p_(e,d_)}function g_(e){return p_(e,f_)}function __(e){return/^wanx-v1(?:-|$)/i.test(e)}function v_(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||h_(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||__(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function y_(e){return/wan2\.5-i2i/i.test(e)}function b_(e){return/imageedit/i.test(e)}function x_(e){return e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:__(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:v_(e)?`wan-legacy`:`wan26`}function S_(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function C_(e,t){return{...e,sizeProfile:x_(t),promptExtendDefault:S_(t)}}function w_(e){return h_(e)?C_({kind:`sync-multimodal`,path:Qh(),useSync:!0,inputStyle:`messages`},e):v_(e)?C_({kind:`async-text2image`,path:$h(),useSync:!1,inputStyle:`prompt`},e):C_({kind:`async-image-generation`,path:Zh(),useSync:!1,inputStyle:`messages`},e)}function T_(e){return g_(e)?C_({kind:`sync-multimodal`,path:Qh(),useSync:!0,inputStyle:`messages`},e):b_(e)?C_({kind:`async-image2image`,path:eg(),useSync:!1,inputStyle:`function-base-image`},e):y_(e)?C_({kind:`async-image2image`,path:eg(),useSync:!1,inputStyle:`prompt-images`},e):C_({kind:`async-image-generation`,path:Zh(),useSync:!1,inputStyle:`messages`},e)}function E_(e){return/realtime|streaming/i.test(e)}function D_(e){return/filetrans/i.test(e)}function O_(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const k_=[`fun-asr-flash`,`qwen-audio`];function A_(e){return E_(e)||D_(e)?!1:!!(e.startsWith(k_[0])||e.startsWith(k_[1])&&/asr-flash/i.test(e))}function j_(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||D_(e)||E_(e)||A_(e))}function M_(e){if(E_(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(D_(e)){let t=O_(e);return{kind:`async-filetrans`,path:hg(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return A_(e)?{kind:`sync-flash`,path:Qh(),useSync:!0,flashFamily:`input-audio`}:j_(e)?{kind:`sync-flash`,path:Qh(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:hg(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function N_(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function P_(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function F_(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function I_(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:N_(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of P_(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function L_(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function R_(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}const z_={12000090:`STS credentials unavailable — retry in a moment`,12000091:`Service-linked role creation failed — retry`,12000092:`Use the primary account to create the service-linked role`,12000093:`Cloud security service is unavailable — retry later`,12000094:`Alert query failed — treat as no data`},B_=new Set(Object.values(st));function V_(e){return B_.has(e.replace(/\/+$/,``))}function H_(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function U_(...e){for(let t of e)if(typeof t==`string`&&t.length>0)return t}function W_(e,t,n){let r=e??`unknown`,i=e===void 0&&t===void 0?`\nUnexpected response body (truncated): ${n.slice(0,800)}`:``;throw new D(`Security API failed: ${r} - ${t??`no message`}${i}`,E.GENERAL,z_[r],{rawResponse:n.slice(0,500)})}function G_(e,t){let n;try{n=JSON.parse(e)}catch{throw new D(`Security API returned non-JSON response (${t??`unknown type`}).`,E.GENERAL,void 0,{rawResponse:e.slice(0,500)})}let r=H_(n),i=r?H_(r.data):void 0,a=i?H_(i.DataV2):void 0;if(a){let t=H_(a.data),n=Array.isArray(a.ret)?a.ret.map(e=>String(e)):[],o=n.length===0||n.some(e=>e.startsWith(`SUCCESS`)),s=U_(i?.errorCode,r?.errorCode),c=U_(i?.errorMsg,r?.errorMsg)??(o?void 0:n.join(`; `));return(r?.successResponse===!1||i?.success===!1||t?.success===!1||t?.failed===!0||!o||s!==void 0)&&W_(s,c,e),(t?t.data:void 0)??null}if(r&&`success`in r)return r.success||W_(U_(r.errorCode),U_(r.errorMsg),e),r.data??null;if(r){let t=U_(i?.errorCode,r.errorCode),n=U_(i?.errorMsg,r.errorMsg);(r.successResponse===!1||i?.success===!1||t!==void 0)&&W_(t,n,e)}if(r)return r;W_(void 0,void 0,e)}async function K_(e,t){let n=await e.request({path:t,method:`GET`});return G_(await n.text(),n.headers.get(`content-type`))}function q_(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function J_(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Y_(e){return async(t,n={})=>{let r=J_(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),q_(r))for(let[t,n]of Object.entries(kn(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${Cn(e.replace(/^Bearer /,``))}`)}let a=await gn.fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const X_=`2024-08-16`;function Z_(e){return`bailiancontrol.${e}.aliyuncs.com`}function Q_(e){return new Ph({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function $_(e){return Q_(e).openApiJson({host:Z_(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:X_,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function ev(e){return Q_(e).openApiJson({host:Z_(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:X_,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function tv(e){return Q_(e).openApiJson({host:Z_(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:X_,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const nv={image:`TextGenerateImage`,video:`VideoGenerate`,speech:`TextGenerateSpeech`,asr:`SpeechGenerateText`},rv={imageGen:`bailian_image_gen`,imageEdit:`bailian_image_edit`,textToVideoSubmit:`bailian_text_to_video_submit_task`,imageToVideoSubmit:`bailian_image_to_video_submit_task`,videoFetchResult:`bailian_text_to_video_fetch_result`,tts:`bailian_tts`,speechToText:`bailian_speech_to_text`};function iv(e){let t=e.content.map(e=>e.text).filter(e=>typeof e==`string`&&e.length>0).join(`
|
|
72
|
-
`);if(e.isError)throw new D(`Tool error: ${t}`,E.GENERAL);if(t.length===0)throw new D(`MCP tool returned no text content.`,E.GENERAL);let n;try{n=JSON.parse(t)}catch(e){throw new D(`Failed to parse MCP tool result: ${e.message}`,E.GENERAL)}if(!n||typeof n!=`object`||Array.isArray(n))throw new D(`MCP tool returned an unexpected payload shape.`,E.GENERAL);return n}function av(e){return{prompt:e.prompt,...e.size===void 0?{}:{size:e.size},...e.n===void 0?{}:{n:e.n},...e.negativePrompt===void 0?{}:{negative_prompt:e.negativePrompt},...e.promptExtend===void 0?{}:{prompt_extend:e.promptExtend}}}function ov(e){return{image_url:e.imageUrl,prompt:e.prompt,...e.negativePrompt===void 0?{}:{negative_prompt:e.negativePrompt}}}function sv(e){return{...e.prompt===void 0?{}:{prompt:e.prompt},...e.duration===void 0?{}:{duration:e.duration},...e.resolution===void 0?{}:{resolution:e.resolution},...e.ratio===void 0?{}:{ratio:e.ratio}}}function cv(e){return{...e.firstFrameUrl===void 0?{}:{first_frame_url:e.firstFrameUrl},...e.prompt===void 0?{}:{prompt:e.prompt},...e.duration===void 0?{}:{duration:e.duration},...e.resolution===void 0?{}:{resolution:e.resolution}}}function lv(e){return{task_id:e}}function uv(e){return{text:e.text,...e.voice===void 0?{}:{voice:e.voice}}}function dv(e){return{file_urls:e}}const fv={"1:1":`1328*1328`,"3:4":`1104*1472`,"4:3":`1472*1104`,"9:16":`928*1664`,"16:9":`1664*928`};function pv(e){let t=/^(\d+)[*xX](\d+)$/.exec(e.trim());return t?`${t[1]}*${t[2]}`:fv[e.trim()]}const mv=[`电商直播男`,`电商直播女`,`温柔女声`,`沉稳男声`,`英文男声`,`英文女生`,`老年女声`,`老年男声`,`童声男`,`童声女`];function hv(e){return mv.includes(e)}function gv(e){if(typeof e==`string`&&e.length>0)return e;if(e&&typeof e==`object`){let t=e.url;if(typeof t==`string`&&t.length>0)return t}}function _v(e){let t=e.results;if(!Array.isArray(t))throw new D("MCP image result is missing a `results` array.",E.GENERAL);return t.map(gv).filter(e=>e!==void 0)}function vv(e){let t=e.result;if(typeof t!=`string`||t.length===0)throw new D(`MCP TTS result is missing an audio URL.`,E.GENERAL);let n=typeof e.request_id==`string`?e.request_id:void 0;return{audioUrl:t,...n===void 0?{}:{requestId:n}}}function yv(e){let t=e.task_id;if(typeof t!=`string`||t.length===0)throw new D(`MCP video submit result is missing a task_id.`,E.GENERAL);return t}function bv(e){let t=typeof e.task_status==`string`?e.task_status:`UNKNOWN`,n=typeof e.video_url==`string`&&e.video_url.length>0?e.video_url:void 0,r=typeof e.task_id==`string`?e.task_id:void 0,i=typeof e.message==`string`&&e.message.length>0?e.message:void 0,a=typeof e.code==`string`&&e.code.length>0?e.code:void 0;return{taskStatus:t,...n===void 0?{}:{videoUrl:n},...r===void 0?{}:{taskId:r},...i===void 0?{}:{message:i},...a===void 0?{}:{code:a}}}function xv(e){let t=e.results;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function Sv(e){let t=e,n=!1;t.endsWith(`\r`)&&(n=!0,t=t.slice(0,-1)),t=t.replace(/\r\n/g,`
|
|
68
|
+
`,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(Hm(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
|
|
69
|
+
${i}`,d++;return}if(Um(e,t,r)){f=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===32?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
|
|
70
|
+
${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new zm(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new zm(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function Hm(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Um(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Wm=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=Vm({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}};const Gm={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Km=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},qm=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=up(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy===`follow`,this._followRedirects&&(this._fetch=gp(this._fetch),this._fetchWithInit=gp(this._fetchWithInit)),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Gm}_unfollowedRedirect(e,t){let n=vp(e,t);return n&&!this._followRedirects?`${n} (redirectPolicy: 'same-origin')`:n}async _authThenStart(){if(!this._authProvider)throw new nm(`No auth provider`);let e;try{e=await _m(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new nm;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=lp(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=this._fetch??fetch,i={method:`GET`,headers:n,signal:this._abortController?.signal},a=await r(this._url,this._followRedirects?i:{...i,redirect:`manual`}),o=this._followRedirects?void 0:mp(r,this._url,i,a);if(o&&(a=await o),!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new Km(a.status,`Failed to open SSE stream: ${this._unfollowedRedirect(a,this._url)??a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(/* @__PURE__ */ Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(/* @__PURE__ */ Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Wm({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=_l.parse(JSON.parse(e.data));ml(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(/* @__PURE__ */ Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(/* @__PURE__ */ Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new nm(`No auth provider`);if(await _m(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new nm(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:ul(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await _p(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Km(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=xm(o);if(this._resourceMetadataUrl=t,this._scope=n,await _m(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new nm;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=xm(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Km(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await _m(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new nm;return this.send(e)}}throw new Km(o.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(o,this._url)??t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),Nl(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`),u=cp(l);if(c){if(u===`text/event-stream`)this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(u===`application/json`){let e=await o.json(),t=Array.isArray(e)?e.map(e=>_l.parse(e)):[_l.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Km(-1,`Unexpected content type: ${l}`)}else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await _p(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Km(n.status,`Failed to terminate session: ${this._unfollowedRedirect(n,this._url)??n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},Jm=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(Zm(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(Zm(this),t)}};function Ym(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Xm(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Xm).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Xm(e.cause)}`:e.message:`${e}`}function Zm(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Qm=e=>{throw TypeError(e)},$m=(e,t,n)=>t.has(e)||Qm(`Cannot `+n),Y=(e,t,n)=>($m(e,t,`read from private field`),n?n.call(e):t.get(e)),eh=(e,t,n)=>t.has(e)?Qm(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),X=(e,t,n,r)=>($m(e,t,`write to private field`),t.set(e,n),n),th=(e,t,n)=>($m(e,t,`access private method`),n),nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th=class extends EventTarget{constructor(e,t){super(),eh(this,hh),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,eh(this,nh),eh(this,rh),eh(this,ih),eh(this,ah),eh(this,oh),eh(this,sh),eh(this,ch),eh(this,lh,null),eh(this,uh),eh(this,dh),eh(this,fh,null),eh(this,ph,null),eh(this,mh,null),eh(this,_h,async e=>{var t;Y(this,dh).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){th(this,hh,Sh).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?X(this,ih,new URL(e.url)):X(this,ih,void 0),i!==200){th(this,hh,Sh).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){th(this,hh,Sh).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(Y(this,nh)===this.CLOSED)return;X(this,nh,this.OPEN);let o=new Event(`open`);if((t=Y(this,mh))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){th(this,hh,Sh).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&Y(this,dh).feed(s.decode(t,{stream:!e})),e&&(l=!1,Y(this,dh).reset(),th(this,hh,Ch).call(this))}while(l)}),eh(this,vh,e=>{X(this,uh,void 0),e.name!==`AbortError`&&e.type!==`aborted`&&th(this,hh,Ch).call(this,Xm(e))}),eh(this,bh,e=>{typeof e.id==`string`&&X(this,lh,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:Y(this,ih)?Y(this,ih).origin:Y(this,rh).origin,lastEventId:e.id||``});Y(this,ph)&&(!e.event||e.event===`message`)&&Y(this,ph).call(this,t),this.dispatchEvent(t)}),eh(this,xh,e=>{X(this,sh,e)}),eh(this,wh,()=>{X(this,ch,void 0),Y(this,nh)===this.CONNECTING&&th(this,hh,gh).call(this)});try{if(e instanceof URL)X(this,rh,e);else if(typeof e==`string`)X(this,rh,new URL(e,Eh()));else throw Error(`Invalid URL`)}catch{throw Ym(`An invalid or illegal string was specified`)}X(this,dh,Vm({onEvent:Y(this,bh),onRetry:Y(this,xh)})),X(this,nh,this.CONNECTING),X(this,sh,3e3),X(this,oh,t?.fetch??globalThis.fetch),X(this,ah,t?.withCredentials??!1),th(this,hh,gh).call(this)}get readyState(){return Y(this,nh)}get url(){return Y(this,rh).href}get withCredentials(){return Y(this,ah)}get onerror(){return Y(this,fh)}set onerror(e){X(this,fh,e)}get onmessage(){return Y(this,ph)}set onmessage(e){X(this,ph,e)}get onopen(){return Y(this,mh)}set onopen(e){X(this,mh,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){Y(this,ch)&&clearTimeout(Y(this,ch)),Y(this,nh)!==this.CLOSED&&(Y(this,uh)&&Y(this,uh).abort(),X(this,nh,this.CLOSED),X(this,uh,void 0))}};nh=/* @__PURE__ */ new WeakMap,rh=/* @__PURE__ */ new WeakMap,ih=/* @__PURE__ */ new WeakMap,ah=/* @__PURE__ */ new WeakMap,oh=/* @__PURE__ */ new WeakMap,sh=/* @__PURE__ */ new WeakMap,ch=/* @__PURE__ */ new WeakMap,lh=/* @__PURE__ */ new WeakMap,uh=/* @__PURE__ */ new WeakMap,dh=/* @__PURE__ */ new WeakMap,fh=/* @__PURE__ */ new WeakMap,ph=/* @__PURE__ */ new WeakMap,mh=/* @__PURE__ */ new WeakMap,hh=/* @__PURE__ */ new WeakSet,gh=function(){X(this,nh,this.CONNECTING),X(this,uh,new AbortController),Y(this,oh)(Y(this,rh),th(this,hh,yh).call(this)).then(Y(this,_h)).catch(Y(this,vh))},_h=/* @__PURE__ */ new WeakMap,vh=/* @__PURE__ */ new WeakMap,yh=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...Y(this,lh)?{"Last-Event-ID":Y(this,lh)}:void 0},cache:`no-store`,signal:Y(this,uh)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},bh=/* @__PURE__ */ new WeakMap,xh=/* @__PURE__ */ new WeakMap,Sh=function(e,t){var n;Y(this,nh)!==this.CLOSED&&X(this,nh,this.CLOSED);let r=new Jm(`error`,{code:t,message:e});(n=Y(this,fh))==null||n.call(this,r),this.dispatchEvent(r)},Ch=function(e,t){var n;if(Y(this,nh)===this.CLOSED)return;X(this,nh,this.CONNECTING);let r=new Jm(`error`,{code:t,message:e});(n=Y(this,fh))==null||n.call(this,r),this.dispatchEvent(r),X(this,ch,setTimeout(Y(this,wh),Y(this,sh)))},wh=/* @__PURE__ */ new WeakMap,Th.CONNECTING=0,Th.OPEN=1,Th.CLOSED=2;function Eh(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}var Dh=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},Oh=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=up(t?.fetch,t?.requestInit),this._followRedirects=t?.redirectPolicy===`follow`,this._followRedirects&&(this._fetch=gp(this._fetch),this._fetchWithInit=gp(this._fetchWithInit))}_unfollowedRedirect(e,t){let n=vp(e,t);return n&&!this._followRedirects?`${n} (redirectPolicy: 'same-origin')`:n}async _authThenStart(){if(!this._authProvider)throw new nm(`No auth provider`);let e;try{e=await _m(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new nm;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=lp(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch,t=this._followRedirects?e:_p(e),n;return new Promise((e,r)=>{this._eventSource=new Th(this._url.href,{...this._eventSourceInit,fetch:async(e,r)=>{let i=await this._commonHeaders();i.set(`Accept`,`text/event-stream`);let a=await t(e,{...r,headers:i});if(n=this._unfollowedRedirect(a,e),a.status===401&&a.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=xm(a);this._resourceMetadataUrl=e,this._scope=t}return a}}),this._abortController=new AbortController,this._eventSource.onerror=t=>{if(t.code===401&&this._authProvider){this._authThenStart().then(e,r);return}let i=new Dh(t.code,n??t.message,t);r(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,t=>{let n=t;try{if(this._endpoint=new URL(n.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),this.onerror?.(e),this.close();return}e()}),this._eventSource.onmessage=e=>{let t=e,n;try{n=_l.parse(JSON.parse(t.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(n)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new nm(`No auth provider`);if(await _m(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new nm(`Failed to authorize`)}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw Error(`Not connected`);try{let t=await this._commonHeaders();t.set(`content-type`,`application/json`);let n={...this._requestInit,method:`POST`,headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},r=await _p(this._fetch??fetch)(this._endpoint,n);if(!r.ok){let t=await r.text().catch(()=>null);if(r.status===401&&this._authProvider){let{resourceMetadataUrl:t,scope:n}=xm(r);if(this._resourceMetadataUrl=t,this._scope=n,await _m(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new nm;return this.send(e)}throw Error(`Error POSTing to endpoint (HTTP ${r.status}): ${this._unfollowedRedirect(r,this._endpoint)??t}`)}await r.body?.cancel()}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}},kh=class{adapter;constructor(e,t,n){this.adapter=new Ph({deps:e,url:t,authToken:n,transport:`streamable`})}initialize(){return this.adapter.initialize()}listTools(){return this.adapter.listTools()}callTool(e,t){return this.adapter.callTool(e,t)}close(){this.adapter.close()}};function Ah(e,t,n){if(e instanceof O)return e;if(e instanceof K){let t=jh(e);return e.code===G.ConnectionClosed&&n?.localCloseFired?new O(t||`MCP connection closed.`,D.NETWORK):new O(`MCP error (${e.code}): ${t}`,D.GENERAL)}if(e instanceof Km){let t=e.code;return new O(`MCP request failed: ${t}`,D.GENERAL,void 0,{api:{httpStatus:typeof t==`number`?t:void 0},cause:e})}if(e instanceof Dh&&t&&t.status===e.code){let n=`MCP request failed: ${t.status} ${t.statusText}`;return t.body&&(n+=` - ${t.body.slice(0,500)}`),new O(n,D.GENERAL,void 0,{api:{httpStatus:t.status},cause:e})}return e}function jh(e){let t=`MCP error ${e.code}: `;return e.message.startsWith(t)?e.message.slice(t.length):e.message}function Mh(e,t,n){return async(r,i)=>{let a=i?.method??`GET`,o=typeof r==`string`?r:r.href,s;if(typeof i?.body==`string`)try{let e=JSON.parse(i.body);typeof e.method==`string`&&(s=e.method)}catch{}yn(e,a,o,{rpc_method:s});let c=await Sn.fetch(r,i);if(bn(e,c),!c.ok&&a===`POST`&&!Nh(c.status)){let e=`MCP request failed: ${c.status} ${c.statusText}`;try{let t=await c.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new O(e,D.GENERAL)}if(t===`sse`&&n&&!c.ok&&a===`GET`&&!Nh(c.status)){let e=``;try{e=await c.text()}catch{}n({status:c.status,statusText:c.statusText,body:e})}return c}}function Nh(e){return e>=300&&e<400}var Ph=class{deps;url;authToken;kind;serviceSource;client;transport;connecting;sseGetFailure;transportClosed=!1;constructor(e){this.deps=e.deps,this.url=e.url,this.authToken=e.authToken,this.kind=e.transport,this.serviceSource=e.serviceSource}async initialize(){if(!this.authToken)throw new O(`This command needs a model-domain API key.`,D.AUTH);return this.connecting||=this.connect().catch(e=>{throw this.connecting=void 0,this.mapTransportError(e)}),this.connecting}async listTools(){let e=await this.requireClient();try{return(await this.withLocalTimeout(e.listTools(void 0,this.requestOptions()))).tools}catch(e){throw this.mapTransportError(e)}}async callTool(e,t){let n=await this.requireClient();try{let r=await this.withLocalTimeout(n.callTool({name:e,arguments:t},void 0,this.requestOptions()));if(!Array.isArray(r.content))throw new O(`MCP tool returned an unexpected result shape.`,D.GENERAL);return r}catch(e){throw this.mapTransportError(e)}}close(){let e=this.transport;this.client=void 0,this.transport=void 0,this.connecting=void 0,this.sseGetFailure=void 0,e&&e.close().catch(()=>void 0)}mapTransportError(e){return Ah(e,this.sseGetFailure,{localCloseFired:this.transportClosed})}async connect(){let e={"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...Pn(this.deps.identity,this.serviceSource),Authorization:`Bearer ${this.authToken}`},t=Mh(this.deps,this.kind,e=>{this.sseGetFailure=e}),n=new URL(this.url);this.transportClosed=!1;let r=this.kind===`sse`?new Oh(n,{requestInit:{headers:e},fetch:t}):new qm(n,{requestInit:{headers:e},fetch:t});r.onclose=()=>{this.transportClosed=!0};let i=new op({name:this.deps.identity.clientName,version:this.deps.identity.version},{capabilities:{}});this.transport=r;let a=i.connect(r,this.requestOptions());a.catch(()=>void 0);let o,s=new Promise((e,t)=>{o=setTimeout(()=>t(new O(`MCP session handshake timed out after ${this.deps.settings.timeout}s.`,D.TIMEOUT)),this.deps.settings.timeout*1e3)});try{await Promise.race([a,s])}catch(e){throw this.transport=void 0,await r.close().catch(()=>void 0),e}finally{o&&clearTimeout(o)}if(this.transport!==r)throw await r.close().catch(()=>void 0),new O(`MCP connection was closed during the handshake.`,D.NETWORK);this.client=i;let c=i.getServerVersion();this.deps.debug?.({message:{"en-US":`MCP session initialized`,"zh-CN":`MCP 会话已初始化`},details:{transport:this.kind,has_session_id:r instanceof qm&&!!r.sessionId,server_name:c?.name,server_version:c?.version}})}async requireClient(){if(await this.initialize(),!this.client)throw new O(`MCP client is not connected.`,D.GENERAL);return this.client}requestOptions(){return{timeout:2147483647}}async withLocalTimeout(e){let t=this.deps.settings.timeout,n,r=new Promise((e,r)=>{n=setTimeout(()=>{r(new O(`MCP request timed out after ${t}s.`,D.TIMEOUT))},t*1e3)});try{return await Promise.race([e,r])}finally{n&&clearTimeout(n)}}};function Fh(e){return`/api/v1/mcps/${e}/mcp`}function Ih(e){return`/api/v1/mcps/${e}/sse`}function Lh(e){return e instanceof O&&/^MCP request failed:\s*405\b/i.test(e.message)}function Rh(e){return e instanceof O&&/^MCP request failed:\s*(405|404)\b/i.test(e.message)}async function zh(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o,serviceSource:s}=e;if(o){let e=new Ph({deps:t,url:o,authToken:n,transport:`streamable`,serviceSource:s});try{return await e.initialize(),{client:e,url:o}}catch(e){if(!Rh(e))throw e}let r=new Ph({deps:t,url:o,authToken:n,transport:`sse`,serviceSource:s});try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let c=new Ph({deps:t,url:r,authToken:n,transport:`streamable`,serviceSource:s});try{return await c.initialize(),{client:c,url:r}}catch(e){if(!Lh(e)||a===`WebSearch`)throw e}let l=new Ph({deps:t,url:i,authToken:n,transport:`sse`,serviceSource:s});try{return await l.initialize(),{client:l,url:i}}catch(e){throw l.close(),e}}var Bh=class e{deps;consoleTokenPersisted;consoleRefresh;constructor(e){this.deps=e,this.consoleTokenPersisted=e.consoleCred?.source===`config`}withSwitchAgent(t){let n=new e({...this.deps,settings:{...this.deps.settings,consoleSwitchAgent:t},consoleCred:this.deps.consoleCred?{...this.deps.consoleCred,switchAgent:t}:void 0});return n.consoleTokenPersisted=this.consoleTokenPersisted,n}async request(e,t){let n=this.deps.consoleCred;if(!n){let n=new O(`This command needs a console access token.`,D.AUTH);if(!this.deps.resolveConsoleOpenApiCredential)throw n;return this.refreshConsole(e,t,n)}try{return await this.requestConsole(n,e,t)}catch(r){if(!(r instanceof at)||r.reason!==`expired-console-session`)throw r;return this.refreshConsole(e,t,r,n)}}async requestConsole(e,t,n){return await On(e,this.deps.settings.timeout,{api:t,data:n},{debug:this.deps.debug,recoveryHint:this.deps.consoleRecoveryHint})}async refreshConsole(e,t,n,r){if(this.deps.consoleCred&&this.deps.consoleCred!==r)return this.requestConsole(this.deps.consoleCred,e,t);let i=this.consoleRefresh;(!i||i.previous!==r)&&(i={previous:r,promise:this.exchangeConsoleToken(r),users:0},this.consoleRefresh=i),i.users++;try{let a=await i.promise.catch(e=>{throw e instanceof at&&e.reason===`missing-openapi-pair`?n:e});if(!a)throw n;let o=await this.requestConsole(a.credential,e,t);return i.commit??=(async()=>{this.deps.consoleCred===r&&(a.persist&&await qh(a.credential.token,this.deps.settings.configName),this.consoleTokenPersisted=a.persist,this.deps.consoleCred=a.credential)})(),await i.commit,o}finally{i.users--,i.users===0&&this.consoleRefresh===i&&(this.consoleRefresh=void 0)}}async exchangeConsoleToken(e){let t=this.deps.resolveConsoleOpenApiCredential?.(),n=e??Uh(this.deps.settings,this.deps.baseUrl),r=this.consoleTokenPersisted&&e?.source===`config`&&(!t||t.source===`config`),i=await Kh({identity:this.deps.identity,settings:{...this.deps.settings,consoleRegion:n.region,consoleSite:n.site,consoleSwitchAgent:n.switchAgent},debug:this.deps.debug,baseUrl:this.deps.baseUrl,credential:t,persist:!1,validateToken:async()=>{}});return i?{credential:{...n,token:i,source:t?.source??e?.source??`config`},persist:r}:null}},Vh=class e{deps;consoleSession;constructor(e){this.deps=e,this.consoleSession=new Bh(e)}get http(){return{identity:this.deps.identity,settings:this.deps.settings,debug:this.deps.debug}}requireApi(){if(!this.deps.apiCred)throw new O(`This command needs a model-domain API key.`,D.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new O(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,D.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}bailianMcpRegistrationHeaders(){return{Authorization:`Bearer ${this.requireApi().token}`,...Pn(this.deps.identity)}}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():this.baseUrl)+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return Ln(this.http,this.toOpts(e))}requestJson(e){return Vn(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return or(e)?sr(e,this.requireApi().token,t,{signal:n.signal,baseUrl:this.url(``,n.defaultBaseUrl),identity:this.deps.identity,timeout:this.deps.settings.timeout}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return or(e)?this.usesTokenPlanEndpoint()?Promise.resolve(nr(e)):this.uploadFile(e,t,n):Promise.resolve(e)}usesTokenPlanEndpoint(){try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}usesTokenPlanConnection(){return this.usesTokenPlanEndpoint()||mn(this.deps.apiCred?.token??``)===`token-plan`}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Ph({deps:this.http,url:t,authToken:this.deps.apiCred?.token,transport:`streamable`})}connectBailianMcp(e,t,n){return this.requireApi(),zh({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Fh(e)),sseUrl:this.url(Ih(e)),serverCode:e,urlOverride:t,serviceSource:n})}withConsoleSwitchAgent(t){let n=new e({...this.deps,settings:{...this.deps.settings,consoleSwitchAgent:t}});return n.consoleSession=this.consoleSession.withSwitchAgent(t),n}console(e,t){return this.consoleSession.request(e,t)}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?Hn(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=Un({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});yn(this.http,e.method,i,{action:e.action,version:e.version});let o=this.deps.settings.timeout*1e3,s=await Sn.fetch(i,{method:e.method,headers:{...a,...Pn(this.deps.identity)},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();bn(this.http,s);let l;try{l=JSON.parse(c)}catch{throw new O(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,D.GENERAL)}if(!s.ok||l.Success===!1)throw new O(`${l.Code||s.status} - ${l.Message||s.statusText}`,D.GENERAL);return l}};const Hh=/* @__PURE__ */ new Map([[`cn-beijing`,`modelstudio.cn-beijing.aliyuncs.com`],[`ap-southeast-1`,`modelstudio.ap-southeast-1.aliyuncs.com`]]);function Uh(e,t){let n=e.consoleRegion;if(!n){let e;try{e=new URL(t).hostname}catch{}n=e===`dashscope.aliyuncs.com`?`cn-beijing`:e===`dashscope-intl.aliyuncs.com`?`ap-southeast-1`:e?.match(/^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/)?.[1]}if(!n||!Hh.has(n))throw new O(`Cannot resolve a supported CLI token region. / 无法确定受支持的 CLI token 地域。`,D.USAGE,`Set console_region to cn-beijing or ap-southeast-1. / 请配置 console_region 为 cn-beijing 或 ap-southeast-1。`);return{region:n,site:e.consoleSite??`domestic`,switchAgent:e.consoleSwitchAgent}}async function Wh(e,t,n={}){let r=await On(e,t.timeout,{api:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,data:{}},n);if(r?.data?.success!==!0)throw new O(`Console token validation did not return success. / 控制台 token 校验未返回成功结果。`,D.GENERAL,void 0,{rawResponse:JSON.stringify(r)})}async function Gh(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Vh({identity:t,settings:n,debug:e.debug,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=Uh(n,r),l=Hh.get(c.region),u=await s.openApiQueryJson({host:l,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}});if(typeof u.cliAccessToken!=`string`||!u.cliAccessToken.trim())throw new O(`CLI token response is missing cliAccessToken. / CLI token 响应缺少有效的 cliAccessToken。`,D.GENERAL);return{...u,cliAccessToken:u.cliAccessToken.trim()}}async function Kh(e){let t=e.settings.configName,n=e.credential?void 0:$t(t),r=e.credential?.accessKeyId??n?.access_key_id,i=e.credential?.accessKeySecret??n?.access_key_secret;if(!r||!i)return null;e.debug?.({message:{"en-US":`Refreshing access token`,"zh-CN":`正在刷新访问令牌`}});let a=(await Gh({identity:e.identity,settings:e.settings,debug:e.debug,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i,securityToken:e.credential?e.credential.securityToken:n?.security_token})).cliAccessToken;return e.validateToken?await e.validateToken(a):await Wh({...Uh(e.settings,e.baseUrl),token:a},e.settings,{debug:e.debug}),(e.persist??(!e.credential||e.credential.source===`config`))&&await qh(a,t),a}async function qh(e,t){let n=$t(t);n.access_token=e,await en(n,t)}function Jh(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new rt(`Workspace ID must contain only letters, digits, hyphens or underscores. / Workspace ID 只能包含字母、数字、连字符或下划线。`);return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function Yh(e){return Jh(e,``)}function Xh(e,t,n){let r;try{r=new URL(e)}catch{throw new rt(`Invalid ParseX base URL. / ParseX Base URL 无效。`)}let i=[`localhost`,`127.0.0.1`,`[::1]`].includes(r.hostname),a=r.pathname.replace(/\/+$/,``);if(r.protocol!==`https:`&&!(r.protocol===`http:`&&i)||r.username||r.password||r.search||r.hash||a)throw new rt(`ParseX base URL must be an HTTPS origin (HTTP is allowed only on loopback). / ParseX Base URL 必须为 HTTPS 源站(仅本机回环地址允许 HTTP)。`);let o=r.hostname.endsWith(`.cn-beijing.pre-maas.aliyuncs.com`)?`/api/v2/apps/pre-parse-x`:`/api/v2/apps/parse-x`;return`${r.origin}${o}/${t}/${n}`}function Zh(){return`/compatible-mode/v1/chat/completions`}function Qh(){return`/compatible-mode/v1/batches`}function $h(e){return`${Qh()}/${encodeURIComponent(e)}`}function eg(e){return`${$h(e)}/cancel`}function tg(e){return`/compatible-mode/v1/files/${encodeURIComponent(e)}/content`}function ng(){return`https://batch.dashscope.aliyuncs.com`}function rg(){return`/compatible-mode/v1/responses`}function ig(){return`/compatible-mode/v1/systemone`}function ag(){return`/api/v1/services/aigc/image-generation/generation`}function og(){return`/api/v1/services/aigc/multimodal-generation/generation`}function sg(){return`/api/v1/services/aigc/text2image/image-synthesis`}function cg(){return`/api/v1/services/aigc/image2image/image-synthesis`}function lg(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function ug(){return`/api/v1/services/aigc/image2video/video-synthesis`}function dg(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function fg(){return`/api/v1/models/limits`}function pg(){return`/api/v1/models/permissions`}function mg(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function hg(e,t){return Jh(e,t)}function gg(){return`/api/v2/apps/memory/add-async`}function _g(e){return`/api/v2/apps/memory/events/${encodeURIComponent(e)}`}function vg(){return`/api/v2/apps/memory/memory_nodes/search`}function yg(){return`/api/v2/apps/memory/memory_nodes`}function bg(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function xg(e){return`/api/v2/apps/memory/skill/export/${encodeURIComponent(e)}`}function Sg(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function Cg(){return`/api/v1/services/audio/asr/transcription`}function wg(){return`/api/v1/services/audio/asr/customization`}function Tg(){return`/api/v2/apps/memory/profile_schemas`}function Eg(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}`}function Dg(e){return`${Eg(e)}/user_profile`}function Og(e){return`${Eg(e)}/profile_values`}function kg(e,t=`cn-beijing`){return`https://${e}.${t}.maas.aliyuncs.com`}function Ag(e){return Jh(e,`/api/v1/indices/knowledge/search`)}function jg(e){return Jh(e,`/api/v2/apps/knowledge/chat`)}function Mg(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}const Ng=`/api/v1/agentstudio/security`;function Pg(e){return`${e}${Ng}/overview`}function Fg(e){return`${e}${Ng}/agent_logs`}function Ig(){return`/api/v1/mcps/WebSearch/mcp`}function Lg(){return`/compatible-mode/v1/files`}function Rg(){return`/api/v1/files`}function zg(e){return`/api/v1/files/${encodeURIComponent(e)}`}function Bg(){return`/api/v1/fine-tunes`}function Vg(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Hg(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Ug(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Wg(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}const Gg=`https://dashscope.aliyuncs.com/api/v1/custom_models/import`;function Kg(){return Gg}function qg(e){return`${Gg}/${encodeURIComponent(e)}`}function Jg(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Yg(){return`/api/v1/fine-tunes/compress/templates`}function Xg(){return`/api/v1/fine-tunes/compress/jobs`}function Zg(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}`}function Qg(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/cancel`}function $g(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/logs`}function e_(){return`/api/v1/deployments`}function t_(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function n_(e){return`${t_(e)}/capacity-instances`}function r_(e,t){return`${n_(e)}/${encodeURIComponent(t)}`}function i_(e,t){return`${r_(e,t)}/scale`}function a_(e,t){return`${r_(e,t)}/renew`}function o_(e){return`${t_(e)}/update-overflowstrategy`}function s_(e,t){return`${t_(e)}/capacity-operations/${encodeURIComponent(t)}`}function c_(e){return`${t_(e)}/scale`}function l_(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function u_(){return`/api/v1/deployments/models`}function d_(e,t){return Jh(e,t)}function f_(){return`/api/v1/agentstudio/files`}function p_(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function m_(e){return`/api/v1/agentstudio/sandbox${e}`}function h_(e,t){return p_(e)+m_(t)}const g_={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function __(e){return`${g_.sandboxes}/${encodeURIComponent(e)}`}function v_(e,t){return`${__(e)}/${t}`}function y_(e){return`${g_.templates}/${encodeURIComponent(e)}`}function b_(e,t){return`${y_(e)}/builds/${encodeURIComponent(t)}/status`}const x_={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFileDetails:`/api/v1/indices/rag/list/index/file/details`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},S_=[`qwen-image`,`wan2.7-image`,`z-image`],C_=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function w_(e,t){return t.some(t=>e.startsWith(t))}function T_(e){return w_(e,S_)||e.startsWith(`wan2.6-image`)}function E_(e){return w_(e,S_)}function D_(e){return w_(e,C_)}function O_(e){return/^wanx-v1(?:-|$)/i.test(e)}function k_(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||E_(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||O_(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function A_(e){return/wan2\.5-i2i/i.test(e)}function j_(e){return/imageedit/i.test(e)}function M_(e){return e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:O_(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:k_(e)?`wan-legacy`:`wan26`}function N_(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function P_(e,t){return{...e,sizeProfile:M_(t),promptExtendDefault:N_(t)}}function F_(e){return E_(e)?P_({kind:`sync-multimodal`,path:og(),useSync:!0,inputStyle:`messages`},e):k_(e)?P_({kind:`async-text2image`,path:sg(),useSync:!1,inputStyle:`prompt`},e):P_({kind:`async-image-generation`,path:ag(),useSync:!1,inputStyle:`messages`},e)}function I_(e){return D_(e)?P_({kind:`sync-multimodal`,path:og(),useSync:!0,inputStyle:`messages`},e):j_(e)?P_({kind:`async-image2image`,path:cg(),useSync:!1,inputStyle:`function-base-image`},e):A_(e)?P_({kind:`async-image2image`,path:cg(),useSync:!1,inputStyle:`prompt-images`},e):P_({kind:`async-image-generation`,path:ag(),useSync:!1,inputStyle:`messages`},e)}function L_(e){return/realtime|streaming/i.test(e)}function R_(e){return/filetrans/i.test(e)}function z_(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const B_=[`fun-asr-flash`,`qwen-audio`];function V_(e){return L_(e)||R_(e)?!1:!!(e.startsWith(B_[0])||e.startsWith(B_[1])&&/asr-flash/i.test(e))}function H_(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||R_(e)||L_(e)||V_(e))}function U_(e){if(L_(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(R_(e)){let t=z_(e);return{kind:`async-filetrans`,path:Cg(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return V_(e)?{kind:`sync-flash`,path:og(),useSync:!0,flashFamily:`input-audio`}:H_(e)?{kind:`sync-flash`,path:og(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:Cg(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function W_(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function G_(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function K_(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function q_(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:W_(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of G_(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function J_(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function Y_(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}const X_={12000090:`STS credentials unavailable — retry in a moment`,12000091:`Service-linked role creation failed — retry`,12000092:`Use the primary account to create the service-linked role`,12000093:`Cloud security service is unavailable — retry later`,12000094:`Alert query failed — treat as no data`},Z_=new Set(Object.values(lt));function Q_(e){return Z_.has(e.replace(/\/+$/,``))}function $_(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function ev(...e){for(let t of e)if(typeof t==`string`&&t.length>0)return t}function tv(e,t,n){let r=e??`unknown`,i=e===void 0&&t===void 0?`\nUnexpected response body (truncated): ${n.slice(0,800)}`:``;throw new O(`Security API failed: ${r} - ${t??`no message`}${i}`,D.GENERAL,X_[r],{rawResponse:n.slice(0,500)})}function nv(e,t){let n;try{n=JSON.parse(e)}catch{throw new O(`Security API returned non-JSON response (${t??`unknown type`}).`,D.GENERAL,void 0,{rawResponse:e.slice(0,500)})}let r=$_(n),i=r?$_(r.data):void 0,a=i?$_(i.DataV2):void 0;if(a){let t=$_(a.data),n=Array.isArray(a.ret)?a.ret.map(e=>String(e)):[],o=n.length===0||n.some(e=>e.startsWith(`SUCCESS`)),s=ev(i?.errorCode,r?.errorCode),c=ev(i?.errorMsg,r?.errorMsg)??(o?void 0:n.join(`; `));return(r?.successResponse===!1||i?.success===!1||t?.success===!1||t?.failed===!0||!o||s!==void 0)&&tv(s,c,e),(t?t.data:void 0)??null}if(r&&`success`in r)return r.success||tv(ev(r.errorCode),ev(r.errorMsg),e),r.data??null;if(r){let t=ev(i?.errorCode,r.errorCode),n=ev(i?.errorMsg,r.errorMsg);(r.successResponse===!1||i?.success===!1||t!==void 0)&&tv(t,n,e)}if(r)return r;tv(void 0,void 0,e)}async function rv(e,t){let n=await e.request({path:t,method:`GET`});return nv(await n.text(),n.headers.get(`content-type`))}function iv(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function av(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function ov(e){return async(t,n={})=>{let r=av(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),iv(r))for(let[t,n]of Object.entries(Pn(e.identity)))i.set(t,n);yn(e,n.method??(t instanceof Request?t.method:`GET`),r);let a=await Sn.fetch(t,{...n,headers:i});return bn(e,a),a}}const sv=`2024-08-16`;function cv(e){return`bailiancontrol.${e}.aliyuncs.com`}function lv(e){return new Vh({identity:e.identity,settings:e.settings,debug:e.debug,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function uv(e){return lv(e).openApiJson({host:cv(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:sv,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function dv(e){return lv(e).openApiJson({host:cv(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:sv,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function fv(e){return lv(e).openApiJson({host:cv(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:sv,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const pv={image:`TextGenerateImage`,video:`VideoGenerate`,speech:`TextGenerateSpeech`,asr:`SpeechGenerateText`},mv={imageGen:`bailian_image_gen`,imageEdit:`bailian_image_edit`,textToVideoSubmit:`bailian_text_to_video_submit_task`,imageToVideoSubmit:`bailian_image_to_video_submit_task`,videoFetchResult:`bailian_text_to_video_fetch_result`,tts:`bailian_tts`,speechToText:`bailian_speech_to_text`};function hv(e){let t=e.content.map(e=>e.text).filter(e=>typeof e==`string`&&e.length>0).join(`
|
|
71
|
+
`);if(e.isError)throw new O(`Tool error: ${t}`,D.GENERAL);if(t.length===0)throw new O(`MCP tool returned no text content.`,D.GENERAL);let n;try{n=JSON.parse(t)}catch(e){throw new O(`Failed to parse MCP tool result: ${e.message}`,D.GENERAL)}if(!n||typeof n!=`object`||Array.isArray(n))throw new O(`MCP tool returned an unexpected payload shape.`,D.GENERAL);return n}function gv(e){return{prompt:e.prompt,...e.size===void 0?{}:{size:e.size},...e.n===void 0?{}:{n:e.n},...e.negativePrompt===void 0?{}:{negative_prompt:e.negativePrompt},...e.promptExtend===void 0?{}:{prompt_extend:e.promptExtend}}}function _v(e){return{image_url:e.imageUrl,prompt:e.prompt,...e.negativePrompt===void 0?{}:{negative_prompt:e.negativePrompt}}}function vv(e){return{...e.prompt===void 0?{}:{prompt:e.prompt},...e.duration===void 0?{}:{duration:e.duration},...e.resolution===void 0?{}:{resolution:e.resolution},...e.ratio===void 0?{}:{ratio:e.ratio}}}function yv(e){return{...e.firstFrameUrl===void 0?{}:{first_frame_url:e.firstFrameUrl},...e.prompt===void 0?{}:{prompt:e.prompt},...e.duration===void 0?{}:{duration:e.duration},...e.resolution===void 0?{}:{resolution:e.resolution}}}function bv(e){return{task_id:e}}function xv(e){return{text:e.text,...e.voice===void 0?{}:{voice:e.voice}}}function Sv(e){return{file_urls:e}}const Cv={"1:1":`1328*1328`,"3:4":`1104*1472`,"4:3":`1472*1104`,"9:16":`928*1664`,"16:9":`1664*928`};function wv(e){let t=/^(\d+)[*xX](\d+)$/.exec(e.trim());return t?`${t[1]}*${t[2]}`:Cv[e.trim()]}const Tv=[`电商直播男`,`电商直播女`,`温柔女声`,`沉稳男声`,`英文男声`,`英文女生`,`老年女声`,`老年男声`,`童声男`,`童声女`];function Ev(e){return Tv.includes(e)}function Dv(e){if(typeof e==`string`&&e.length>0)return e;if(e&&typeof e==`object`){let t=e.url;if(typeof t==`string`&&t.length>0)return t}}function Ov(e){let t=e.results;if(!Array.isArray(t))throw new O("MCP image result is missing a `results` array.",D.GENERAL);return t.map(Dv).filter(e=>e!==void 0)}function kv(e){let t=e.result;if(typeof t!=`string`||t.length===0)throw new O(`MCP TTS result is missing an audio URL.`,D.GENERAL);let n=typeof e.request_id==`string`?e.request_id:void 0;return{audioUrl:t,...n===void 0?{}:{requestId:n}}}function Av(e){let t=e.task_id;if(typeof t!=`string`||t.length===0)throw new O(`MCP video submit result is missing a task_id.`,D.GENERAL);return t}function jv(e){let t=typeof e.task_status==`string`?e.task_status:`UNKNOWN`,n=typeof e.video_url==`string`&&e.video_url.length>0?e.video_url:void 0,r=typeof e.task_id==`string`?e.task_id:void 0,i=typeof e.message==`string`&&e.message.length>0?e.message:void 0,a=typeof e.code==`string`&&e.code.length>0?e.code:void 0;return{taskStatus:t,...n===void 0?{}:{videoUrl:n},...r===void 0?{}:{taskId:r},...i===void 0?{}:{message:i},...a===void 0?{}:{code:a}}}function Mv(e){let t=e.results;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function Nv(e){let t=e,n=!1;t.endsWith(`\r`)&&(n=!0,t=t.slice(0,-1)),t=t.replace(/\r\n/g,`
|
|
73
72
|
`).replace(/\r/g,`
|
|
74
73
|
`);let r=t.split(`
|
|
75
|
-
`),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function
|
|
74
|
+
`),i=r.pop()??``;return{lines:r,rest:n?`${i}\r`:i}}function Pv(e,t,n){if(e===``)return t.data===void 0?{event:{}}:{event:{},completed:{data:t.data,event:t.event,id:t.id}};if(e.startsWith(`:`))return{event:t};let r=e.indexOf(`:`);if(r===-1)return{event:t};let i=e.slice(0,r),a=e.slice(r+1).trimStart(),o={...t};switch(i){case`data`:if(o.data=o.data===void 0?a:`${o.data}\n${a}`,o.data.length>n)throw new O(`SSE event exceeded the maximum buffer size.`,D.GENERAL);break;case`event`:o.event=a;break;case`id`:o.id=a}return{event:o}}async function*Fv(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16777216;try{let e={};for(;;){let{done:a,value:o}=await t.read();if(a){if(r.length>0){let t=r.replace(/\r\n/g,`
|
|
76
75
|
`).replace(/\r/g,`
|
|
77
76
|
`).split(`
|
|
78
|
-
`);r=t.pop()??``;for(let n of t){let t=Cv(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new D(`SSE stream exceeded the maximum buffer size.`,E.GENERAL);let{lines:s,rest:c}=Sv(r);r=c;for(let t of s){let n=Cv(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Cv(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}const Tv=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Ev=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Dv(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function Ov(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Dv(await e(Tv,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function kv(e,t={}){let n=t.pageSize??50,r=await Ov(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await Ov(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Av(e,t){return(await Ov(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function jv(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=Dv(await e(Tv,{input:u}));return{total:d.total??0,groups:d.list??[]}}function Mv(e){return e.flatMap(e=>e.items??[])}async function Nv(e,t={}){let n=t.pageSize??50,r=await jv(e,{...t,pageNo:1,pageSize:n}),i=Math.max(1,Math.ceil(r.total/n)),a=[];for(let e=2;e<=i;e++)a.push(e);let o=await Promise.all(a.map(r=>jv(e,{...t,pageNo:r,pageSize:n})));return Mv([r.groups,...o.map(e=>e.groups)].flat())}async function Pv(e,t){return(Dv(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const Fv=[`name`,`key`,`default`,`tip`,`range`];function Iv(e){return e.map(e=>{let t={};for(let n of Fv)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Lv(e,t){let n=Dv(await e(Ev,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Iv(e):null}catch{return null}return Array.isArray(n)?Iv(n):null}function Rv(e){return{read:()=>Zt(e),async write(t){let n=Zt(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?at(String(r)):r;await Qt(n,e)},async unset(t){let n=Zt(e);for(let e of t)delete n[e];await Qt(n,e)},profiles:()=>en(),activate:e=>rn(e),validateActivation:e=>nn(e),get path(){return Pt()}}}async function zv(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=t.fileBlob?.size??l(r).size,s=m(r),c=t.fileBlob??await new Response(oe.toWeb(n(r))).blob(),u=new FormData;u.append(`file`,c,s),u.append(`purpose`,i);let d=await e.requestJson({path:kg(),method:`POST`,body:u,signal:a});if(d.id)return{file_id:d.id,name:d.filename??s,size:d.bytes??o,purpose:d.purpose??i,gmt_create:d.created_at?(/* @__PURE__ */ new Date(d.created_at*1e3)).toISOString():void 0,request_id:d.request_id};let f=d.data?.failed_uploads;if(Array.isArray(f)&&f.length>0){let e=f[0]??{};throw new D(e.message??`Upload failed without a service message. / 上传失败,服务端未提供错误消息。`,E.GENERAL,void 0,{api:{httpStatus:200,apiCode:e.code,requestId:d.request_id},rawResponse:JSON.stringify(d)})}throw new D(`Upload response for ${s} has no usable file ID. / ${s} 的上传响应缺少可用文件 ID。`,E.GENERAL,`Success cannot be verified; inspect the file list before retrying. / 无法验证上传成功,请先检查文件列表,再决定是否重试。`,{api:{httpStatus:200,requestId:d.request_id},rawResponse:JSON.stringify(d)})}async function Bv(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Ag(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Vv(e,t,n){return e.requestJson({path:jg(t),method:`GET`,signal:n})}async function Hv(e,t,n){let r=await e.request({path:jg(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const Uv=209715200,Wv=314572800,Gv=314572800,Kv=2147483648;function qv(e,t=Uv){if(!i(e))throw new D(`File not found: ${e}`,E.USAGE);let n=l(e);if(!n.isFile())throw new D(`Not a regular file: ${e}`,E.USAGE);if(n.size===0)throw new D(`File is empty: ${e}`,E.USAGE);if(n.size>t)throw new D(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,E.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function Z(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function Jv(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`decision`||t===`tts`||t===`image`||t===`video`)return t;throw new D(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,E.USAGE,`Omit --schema to auto-detect per record (state/questions → decision, chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, first_frame_path/video_path → video, else ChatML). / 省略 --schema 可逐条自动识别。`)}function Yv(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=/* @__PURE__ */ new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const Xv=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),Zv=.1;function Qv(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<Zv||a>10)&&i.push(Z(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${Zv} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(Z(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(Z(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function $v(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(Z(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(Z(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(Z(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(Z(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(Z(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(Z(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(Z(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(Z(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...Qv(s,Array.isArray(e),t,o))}}}return r}function ey(e,t,n){let r=[];if(!Array.isArray(e))return r.push(Z(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(Z(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(Z(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(Z(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(Z(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(Z(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(Z(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function ty(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(Z(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!Xv.has(a))&&r.push(Z(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(Z(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...$v(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(Z(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...ey(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(Z(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(Z(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function ny(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(Z(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(Z(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,o=-1,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...ty(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(Z(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(Z(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(Z(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(Z(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(Z(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(Z(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;ry(a)&&n.push(Z(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(Z(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];i&&`loss_weight`in i&&(l(i.loss_weight,`messages[${e}].loss_weight`),(i.role!==`assistant`||e!==o)&&n.push(Z(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(Z(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function ry(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const iy={name:`chatml`,detect:()=>!0,inspect:ny};function ay(e,t){let n=[];if(!(`text`in e))return n.push(Z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const oy={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:ay};function sy(e,t){let n=ny(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(a&&typeof a==`object`)for(let e of[`image`,`video`])e in a&&r.push(Z(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(Z(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(Z(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(Z(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(Z(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(Z(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...ty(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...ty(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const cy={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:sy},ly=[`choice`,`noul`,`score`],uy=255,dy=2,fy=255,py=/* @__PURE__ */ new Set([`true`,`false`]);function my(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hy(e){return typeof e==`string`&&e.trim().length>0}function gy(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function _y(e,t=`state`){return hy(e)||Array.isArray(e)&&e.length>0||my(e)&&Object.keys(e).length>0?[]:[gy(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function vy(e,t){let n=`${t}.criteria`;if(!my(e))return[gy(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must be an option-to-description object.`,`"${n}" 必须是“选项名到描述”的对象。`)];let r=Object.keys(e).length;if(r<1||r>255)return[gy(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must contain 1-255 options (got ${r}).`,`"${n}" 必须包含 1-255 个选项(当前 ${r} 个)。`)];for(let[t,r]of Object.entries(e))if(!hy(t)||!hy(r))return[gy(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function yy(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!hy(e))?[gy(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must be an array of non-empty level descriptions, from low to high.`,`"${n}" 必须是从低到高排列、由非空等级描述组成的数组。`)]:e.length<2||e.length>255?[gy(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function by(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return my(e)&&Object.entries(e).every(([e,t])=>py.has(e)&&typeof t==`string`)?[]:[gy(`DECISION_INVALID_NOUL_CRITERIA`,n,`"${n}" is optional; when provided it must be an object with only "true" / "false" string descriptions.`,`"${n}" 为可选项;填写时必须是只包含 "true" / "false" 字符串描述的对象。`)]}function xy(e,t){if(!my(e))return[gy(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(gy(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...vy(e.criteria,t)):e.type===`noul`?n.push(...by(e.criteria,t)):e.type===`score`?n.push(...yy(e.criteria,t)):n.push(gy(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function Sy(e,t=`questions`){return my(e)&&Object.keys(e).length>0?[]:[gy(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function Cy(e,t=`questions`){return hy(e)?[]:[gy(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function wy(e,t=`questions`){let n=Sy(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=Cy(n,t);if(e.length>0){r.push(...e);continue}r.push(...xy(i,`${t}.${n}`))}return r}function Ty(e,t,n,r){return Z(`error`,e,t,{line:n,path:r})}function Ey(e,t){return Ty(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function Dy(e,t,n,r){if(!my(e))return[Ty(`DECISION_INVALID_TARGET`,`"${r}" must be an object containing a complete probability distribution. / "${r}" 必须是包含完整概率分布的对象。`,n,r)];let i=Object.keys(e).sort(),a=[...t].sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return[Ty(`DECISION_INVALID_TARGET_KEYS`,`"${r}" must contain exactly these keys: ${a.join(`, `)}. / "${r}" 必须且只能包含这些键:${a.join(`, `)}。`,n,r)];let o=0;for(let t of a){let i=e[t];if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>1)return[Ty(`DECISION_INVALID_TARGET_PROBABILITY`,`"${r}.${t}" must be a finite number in [0, 1]. / "${r}.${t}" 必须是 [0, 1] 范围内的有限数字。`,n,`${r}.${t}`)];o+=i}return Math.abs(o-1)>1e-6?[Ty(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function Oy(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[Ty(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:Dy(e.target,r,t,`${n}.target`)}function ky(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:Dy(e.target,[`true`,`false`],t,`${n}.target`):[Ty(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function Ay(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[Ty(`DECISION_INVALID_SCORE_LABEL`,`"${n}.label" must be an integer from 0 to ${r-1}. / "${n}.label" 必须是 0 到 ${r-1} 之间的整数。`,t,`${n}.label`)];let i=Array.from({length:r},(e,t)=>String(t));return e.target===void 0?[]:Dy(e.target,i,t,`${n}.target`)}function jy(e,t){let n=_y(e.state).map(e=>Ey(e,t)),r=e.questions,i=Sy(r);if(i.length>0)return n.push(...i.map(e=>Ey(e,t))),n;for(let[e,i]of Object.entries(r)){let r=Cy(e);if(r.length>0){n.push(...r.map(e=>Ey(e,t)));continue}let a=`questions.${e}`,o=xy(i,a);if(o.length>0){n.push(...o.map(e=>Ey(e,t)));continue}let s=i;s.type===`choice`?n.push(...Oy(s,t,a)):s.type===`noul`?n.push(...ky(s,t,a)):n.push(...Ay(s,t,a))}return n}const My={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:jy};function Ny(e,t){let n=[];if(!(`wav_fn`in e))n.push(Z(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(Z(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(Z(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(Z(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(Z(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(Z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Py={name:`tts`,detect:e=>`wav_fn`in e,inspect:Ny},Fy=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function Iy(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Ly(e){return/^[\x20-\x7E]+$/.test(e)}function Ry(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(Z(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(Z(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(Z(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Iy(r);Fy.has(e)||n.push(Z(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Fy].join(`, `)}.`,{line:t,path:`img_path`})),Ly(r)||n.push(Z(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(Z(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(Z(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Iy(r);Fy.has(e)||n.push(Z(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Fy].join(`, `)}.`,{line:t,path:`input_img`})),Ly(r)||n.push(Z(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const zy={name:`image`,detect:e=>`img_path`in e,inspect:Ry},By=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Vy=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function Hy(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function Uy(e){return/^[\x20-\x7E]+$/.test(e)}function Wy(e,t,n,r,i,a){if(!(n in t)){r&&e.push(Z(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(Z(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(Z(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Hy(o);i.has(s)||e.push(Z(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),Uy(o)||e.push(Z(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Gy(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Wy(n,e,`first_frame_path`,!0,By,t),Wy(n,e,`last_frame_path`,!1,By,t),Wy(n,e,`video_path`,!1,Vy,t),n}const Ky=[Py,zy,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Gy},My,cy,oy,iy];function qy(e,t){return t===void 0?Ky.find(t=>t.detect(e))??iy:Ky.find(e=>e.name===t)||iy}async function Jy(e,t){let r=n(e,{encoding:`utf8`}),i=se({input:r,crlfDelay:1/0}),a=[],o=0,s=0;for await(let e of i){if(t?.aborted)break;o++;let n=e.trim();if(n.length===0){s++;continue}a.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&a.push(Z(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function Yy(e,t,r,i,a){let o=r?null:new Set(Yv(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=se({input:l,crlfDelay:1/0}),d=0;for await(let e of u){if(a?.aborted)break;if(d++,o&&!o.has(d))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(Z(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...Xy(n,d,i))}return{sampled:c,issues:s}}function Xy(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[Z(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return qy(r,n).inspect(r,t)}const Zy={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await Jy(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[Z(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await Yy(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function Qy(e,t){return new Promise((n,r)=>{le.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(/* @__PURE__ */ Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function $y(e){return new Promise((t,n)=>{le.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}const eb=/^[a-zA-Z0-9_-]+$/;function tb(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function nb(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function rb(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||nb(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=tb(n),i=n.slice(e.length);e.length>0&&!eb.test(e)&&t.length<10&&t.push(Z(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(Z(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=tb(i);if(a.length>120&&t.length<10&&t.push(Z(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(Z(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(Z(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function ib(e,t,n){let{entry:i,zipfile:a}=await Qy(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??/* @__PURE__ */ Error(`Failed to open entry stream`));return}let s=r(n);ce(o,s).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function ab(e,t=100){let r=n(e,{encoding:`utf8`}),i=se({input:r,crlfDelay:1/0}),a=[],o=0;for await(let e of i){if(o++,a.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&a.push(e.wav_fn),typeof e.img_path==`string`&&a.push(e.img_path),typeof e.input_img==`string`&&a.push(e.input_img),typeof e.first_frame_path==`string`&&a.push(e.first_frame_path),typeof e.last_frame_path==`string`&&a.push(e.last_frame_path),typeof e.video_path==`string`&&a.push(e.video_path),typeof e.image_fn==`string`&&a.push(e.image_fn),typeof e.video_fn==`string`&&a.push(e.video_fn)}catch{}}return{refs:a,totalLines:o}}const ob={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await $y(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[Z(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[Z(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(Z(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(Z(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=rb(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(Z(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||nb(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return Fy.has(n)});e.length<25&&r.push(Z(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ie(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await ib(e,_,y)}catch(t){return r.push(Z(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let ee=await Zy.validate(y,t);if(r.push(...ee.errors),i.push(...ee.warnings),ee.valid){let{refs:e}=await ab(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(Z(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:ee.stats.totalRecords??o.length,sampledRecords:ee.stats.sampledRecords,durationMs:Date.now()-n}}}};async function sb(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return cb(e);if(t===`.zip`)return lb(e);throw new D(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,E.USAGE)}async function cb(e){let t=await db(e);if(!t)throw new D(`JSONL file is empty or contains only blank lines: ${e}`,E.USAGE);let n=ub(t);return n===`unknown`?`text`:n}async function lb(e){let t=await fb(e,`data.jsonl`);if(!t)throw new D(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,E.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=ub(t);if(n===`unknown`)throw new D(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,E.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function ub(e){let t;try{t=JSON.parse(e)}catch{throw new D(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,E.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new D(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,E.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function db(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=se({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function fb(e,t){return Qy(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new D(`Failed to read "${t}" from ZIP: ${e?.message}`,E.USAGE));return}let o=se({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const pb=[Zy,ob];function mb(e){let t=h(e).toLowerCase(),n=pb.find(e=>e.extensions.includes(t));if(!n){let e=pb.flatMap(e=>e.extensions).join(`, `);throw new D(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,E.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function hb(e){pb.some(t=>t.format===e.format)||pb.push(e)}async function gb(e,t={}){let{bytes:n}=qv(e,t.maxBytes??209715200),r=await mb(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function _b(){return pb.map(e=>({format:e.format,extensions:[...e.extensions]}))}function vb(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}const yb=[`/v1/chat/completions`,`/v1/embeddings`,`/v1/chat/ds-test`],bb=[`validating`,`in_progress`,`finalizing`,`completed`,`failed`,`expired`,`cancelling`,`cancelled`],xb=/* @__PURE__ */ new Set([`completed`,`failed`,`expired`,`cancelled`]),Sb=524288e3,Cb=6291456,wb=5e4;function Q(e,t){throw new nt(`${e}\n${t}`)}function Tb(e){if(e instanceof D)return e;let t=e?.code;return new D(`Batch file I/O failed${t?` (${t})`:``}.\nBatch 文件读写失败${t?`(${t})`:``}。`,E.GENERAL,t===`ENOENT`?`Check the file and parent directory paths. / 请检查文件及父目录路径。`:t===`EEXIST`?`Output exists; use --force to replace it. / 输出已存在,使用 --force 覆盖。`:`Check file permissions and available disk space. / 请检查文件权限与磁盘空间。`,{cause:e})}function Eb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Db(e){return yb.includes(e)||Q(`Unsupported Batch endpoint: ${e}`,`不支持的 Batch endpoint:${e}`),e}async function*Ob(e){let t=typeof e==`string`?fe(e):e instanceof Blob?we.fromWeb(e.stream()):e;try{for await(let e of t)yield e}catch(e){throw Tb(e)}}async function*kb(e,t=1/0,n=Cb){let r=Buffer.alloc(0),i=0,a=new TextDecoder(`utf-8`,{fatal:!0}),o=e=>{try{return a.decode(e)}catch{return Q(`Invalid UTF-8 input.`,`输入不是有效 UTF-8。`)}};for await(let a of Ob(e)){i+=a.byteLength,i>t&&Q(`File exceeds ${t} bytes.`,`文件超过 ${t} 字节。`);let e=Buffer.concat([r,a]),s=0,c=e.indexOf(10,s);for(;c!==-1;){let t=c-s;t>n&&Q(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`),yield{text:o(e.subarray(s,c)).replace(/\r$/,``),bytes:t+1},s=c+1,c=e.indexOf(10,s)}r=Buffer.from(e.subarray(s)),r.byteLength>n&&Q(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`)}r.length&&(yield{text:o(r),bytes:r.length})}function Ab(e,t=!1){if(typeof e==`string`&&t){if(/^data:[^,]+;base64,/i.test(e))return;let t;try{t=new URL(e)}catch{return Q(`Media must use a public HTTP(S) or base64 data URL.`,`媒体必须使用公网 HTTP(S) 或 base64 data URL。`)}let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,``),r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(n),i=r?parseInt(r[1],16):0,a=r?parseInt(r[2],16):0,o=r?[i>>8,i&255,a>>8,a&255].join(`.`):n,s=n===`localhost`||n.endsWith(`.localhost`)||Ce(o)===4&&/^(0|10|127|169\.254|172\.(1[6-9]|2\d|3[01])|192\.168)(\.|$)/.test(o)||Ce(n)===6&&/^(::1$|::$|f[cd]|fe[89ab])/.test(n);(![`http:`,`https:`].includes(t.protocol)||s)&&Q(`Media URLs must not use local/private addresses.`,`媒体 URL 不得使用本地或私网地址。`)}else if(Array.isArray(e))for(let n of e)Ab(n,t);else if(Eb(e))for(let[n,r]of Object.entries(e))Ab(r,[`image_url`,`video_url`,`audio_url`,`file_url`,`image`,`video`].includes(n)||t&&n===`url`)}var jb=class{ids=/* @__PURE__ */ new Set;thinking;report={records:0,bytes:0,model:``,endpoint:`/v1/chat/completions`,warnings:[]};warn(e){this.report.warnings.includes(e)||this.report.warnings.push(e)}add(e,t){let n=this.report.records+1,r=e=>Q(`Invalid or inconsistent ${e} at record ${n}.`,`第 ${n} 条记录的 ${e} 无效或不一致。`);Eb(e)||r(`JSON object`);let i=e,a=i.custom_id;(typeof a!=`string`||!a.trim()||Array.from(a).length>256||this.ids.has(a))&&r(`custom_id`),i.method!==`POST`&&r(`method=POST`);let o=Db(String(i.url));Eb(i.body)||r(`body`);let s=i.body;if((typeof s.model!=`string`||!s.model.trim())&&r(`body.model`),s.enable_thinking!==void 0&&typeof s.enable_thinking!=`boolean`&&r(`enable_thinking`),this.report.records&&(this.report.model!==s.model||this.report.endpoint!==o||this.thinking!==s.enable_thinking)&&r(`model/url/enable_thinking`),o===`/v1/embeddings`){let e=e=>typeof e==`string`&&!!e.trim(),t=e=>Array.isArray(e)&&e.length>0&&e.every(e=>Number.isInteger(e)&&e>=0);e(s.input)||t(s.input)||Array.isArray(s.input)&&s.input.length>0&&(s.input.every(e)||s.input.every(t))||r(`body.input`)}else(!Array.isArray(s.messages)||!s.messages.length||s.messages.some(e=>!Eb(e)||typeof e.role!=`string`||!e.role.trim()||typeof e.content!=`string`&&!(Array.isArray(e.content)&&e.content.length>0&&e.content.every(Eb))&&!(Array.isArray(e.tool_calls)&&e.tool_calls.length>0&&e.tool_calls.every(Eb))))&&r(`body.messages`);Ab(s),Eb(s.extra_body)&&(`enable_thinking`in s.extra_body||`thinking_budget`in s.extra_body)&&this.warn(`Place enable_thinking/thinking_budget at body top level, not extra_body. / enable_thinking/thinking_budget 应放在 body 顶层,而非 extra_body。`),t>6291456&&r(`line <=6 MiB`),t>1048576&&this.warn(`Line exceeds 1 MiB; documentation differs (1/6 MiB), compatibility is not guaranteed. / 单行超过 1 MiB,文档存在 1/6 MiB 差异,不保证兼容。`),this.ids.add(a),this.report.records++,this.report.bytes+=t,this.report.model=s.model,this.report.endpoint=o,this.thinking=s.enable_thinking,(this.report.records>5e4||this.report.bytes>524288e3)&&r(`50000 records / 500 MiB`),s.model===`batch-test-model`&&(this.report.records>100||this.report.bytes>1048576)&&r(`batch-test-model: 100 records / 1 MiB`)}finish(){return this.report.records||Q(`Batch input is empty.`,`Batch 输入为空。`),this.report}};async function Mb(e){let t=new jb,n=0;for await(let r of kb(e,Sb)){n++;let e;try{e=JSON.parse(r.text)}catch{Q(`Invalid JSONL at line ${n}.`,`第 ${n} 行不是有效 JSONL。`)}t.add(e,r.bytes)}return t.finish()}async function Nb(e){let t=[],n=0;for await(let r of Ob(e))n+=r.byteLength,n>524288e3&&Q(`File exceeds 500 MiB.`,`文件超过 500 MiB。`),t.push(r);return new Blob(t)}function Pb(e,t,n){return e.requestJson({path:Wh(),method:`POST`,body:t,signal:n})}function Fb(e,t,n){return e.requestJson({path:Gh(t),signal:n})}function Ib(e,t,n){return e.requestJson({path:Kh(t),method:`POST`,signal:n})}function Lb(e,t={},n){let r=new URLSearchParams;for(let[e,n]of Object.entries(t))n!==void 0&&r.set(e,Array.isArray(n)?n.join(`,`):String(n));return e.requestJson({path:Wh()+(r.size?`?${r.toString()}`:``),signal:n})}function Rb(e,t,n){return e.request({path:qh(t),signal:n})}function zb(e){let t=e.url(Uh(),Jh),n=new URL(t).hostname.toLowerCase(),r=new URL(e.baseUrl).hostname.toLowerCase();return(e.usesTokenPlanEndpoint()||/^dashscope(?:-intl|-us)?\.aliyuncs\.com$/.test(n)||/^dashscope-(?:intl|us)\.aliyuncs\.com$/.test(r))&&Q(`--batch needs the Batch host, not a realtime/international/Token Plan endpoint; configure --base-url explicitly.`,`--batch 不能使用实时、国际站或 Token Plan 端点,请显式配置 Batch --base-url。`),t}async function Bb(e,t,n=!1){let r=ke(e),i=ke(Ee(r),`.${Te(r)}.${Be()}.tmp`),a,o=e=>{throw Tb(e)};try{await Pe(Ee(r),{recursive:!0}).catch(o),a=await Fe(i,`wx`,384).catch(o);for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e,n=0;for(;n<t.byteLength;){let e=await a.write(t,n,t.byteLength-n).catch(o);n+=e.bytesWritten}}await a.sync().catch(o),await a.close().catch(o),a=void 0,n?await Le(i,r).catch(o):await Ne(i,r).catch(o)}finally{await a?.close().catch(()=>{}),await Re(i).catch(()=>{})}}async function Vb(e){let t=Db(e.endpoint??`/v1/chat/completions`);(ke(e.file)===ke(e.outputFile)||e.bodyFile&&ke(e.bodyFile)===ke(e.outputFile))&&Q(`Output must differ from input/body file.`,`输出路径必须与输入及 body 文件不同。`),e.model.trim()||Q(`Model must not be empty.`,`模型不能为空。`);let n=e.idColumn??`custom_id`,r=e.inputColumn??`content`,i={};if(e.bodyFile){let t;try{t=await Ie(e.bodyFile,`utf8`)}catch(e){throw Tb(e)}try{let e=JSON.parse(t);if(!Eb(e))throw Error();i=e}catch{Q(`--body-file must contain a JSON object.`,`--body-file 必须包含 JSON 对象。`)}}[`model`,`messages`,`input`].some(e=>e in i)&&Q(`--body-file cannot define model/messages/input.`,`--body-file 不得定义 model/messages/input。`),t===`/v1/embeddings`&&(e.system!==void 0||`enable_thinking`in i||`thinking_budget`in i)&&Q(`System/thinking parameters do not apply to embeddings.`,`向量请求不适用系统提示词或思考参数。`);let a=new jb,o=[],s=[],c;async function*l(){let t=new TextDecoder(`utf8`,{fatal:!0}),n=0;for await(let r of Ob(e.file)){n+=r.byteLength,n>524288e3&&Q(`CSV exceeds 500 MiB.`,`CSV 超过 500 MiB。`);try{yield t.decode(r,{stream:!0})}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}try{yield t.decode()}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}async function*u(){let u=we.from(l()),d=je({bom:!0,max_record_size:6291456,columns:e=>((new Set(e).size!==e.length||!e.includes(n)||!e.includes(r))&&Q(`CSV requires unique headers and mapped ID/input columns.`,`CSV 表头必须唯一并包含映射的 ID/输入列。`),s=e.filter(e=>e!==n&&e!==r),e)});u.on(`error`,e=>d.destroy(e)),u.pipe(d);let f=0;try{for await(let s of d){f++;let c=s;c[r]?.trim()||Q(`Empty CSV input at record ${f}.`,`CSV 第 ${f} 条记录输入为空。`);let l={...i,model:e.model};t===`/v1/embeddings`?(l.input=c[r],l.encoding_format??=`float`):l.messages=[...e.system===void 0?[]:[{role:`system`,content:e.system}],{role:`user`,content:c[r]}];let u={custom_id:c[n],method:`POST`,url:t,body:l},d=JSON.stringify(u)+`
|
|
79
|
-
`;a.add(u,Buffer.byteLength(d)),e.dryRun&&o.length<2&&o.push(u),yield d}c=a.finish()}catch(e){throw e instanceof Error&&e.name===`Error`&&`code`in e&&String(e.code).startsWith(`CSV_`)&&Q(`Invalid CSV near record ${f+1}: ${e.message}`,`第 ${f+1} 条记录附近 CSV 格式错误:${e.message}`),
|
|
80
|
-
`)}}function
|
|
77
|
+
`);r=t.pop()??``;for(let n of t){let t=Pv(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new O(`SSE stream exceeded the maximum buffer size.`,D.GENERAL);let{lines:s,rest:c}=Nv(r);r=c;for(let t of s){let n=Pv(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=Pv(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}const Iv=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Lv=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Rv(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function zv(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Rv(await e(Iv,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function Bv(e,t={}){let n=t.pageSize??50,r=await zv(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await zv(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Vv(e,t){return(await zv(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Hv(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=Rv(await e(Iv,{input:u}));return{total:d.total??0,groups:d.list??[]}}function Uv(e){return e.flatMap(e=>e.items??[])}async function Wv(e,t={}){let n=t.pageSize??50,r=await Hv(e,{...t,pageNo:1,pageSize:n}),i=Math.max(1,Math.ceil(r.total/n)),a=[];for(let e=2;e<=i;e++)a.push(e);let o=await Promise.all(a.map(r=>Hv(e,{...t,pageNo:r,pageSize:n})));return Uv([r.groups,...o.map(e=>e.groups)].flat())}async function Gv(e,t){return(Rv(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const Kv=[`name`,`key`,`default`,`tip`,`range`];function qv(e){return e.map(e=>{let t={};for(let n of Kv)e[n]!==void 0&&(t[n]=e[n]);return t})}async function Jv(e,t){let n=Rv(await e(Lv,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?qv(e):null}catch{return null}return Array.isArray(n)?qv(n):null}function Yv(e){return{read:()=>$t(e),async write(t){let n=$t(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?st(String(r)):r;await en(n,e)},async unset(t){let n=$t(e);for(let e of t)delete n[e];await en(n,e)},profiles:()=>nn(),activate:e=>on(e),validateActivation:e=>an(e),get path(){return It()}}}const Xv=`{{commandPrefix}}`;function Zv(e,t=[],n=[]){return{bin:e.commandInvocation?.bin??e.binName,path:[...e.commandInvocation?.path??[],...t],args:[...n]}}function Qv(e,t=``){let n=typeof e==`string`?e:[e.commandInvocation?.bin??e.binName,...e.commandInvocation?.path??[]].join(` `);return t?`${n} ${t}`:n}function $v(e=``){return Qv(Xv,e)}function ey(e,t){return e.split(Xv).join(Qv(t))}async function ty(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=t.fileBlob?.size??l(r).size,s=m(r),c=t.fileBlob??await new Response(ae.toWeb(n(r))).blob(),u=new FormData;u.append(`file`,c,s),u.append(`purpose`,i);let d=await e.requestJson({path:Lg(),method:`POST`,body:u,signal:a});if(d.id)return{file_id:d.id,name:d.filename??s,size:d.bytes??o,purpose:d.purpose??i,gmt_create:d.created_at?(/* @__PURE__ */ new Date(d.created_at*1e3)).toISOString():void 0,request_id:d.request_id};let f=d.data?.failed_uploads;if(Array.isArray(f)&&f.length>0){let e=f[0]??{};throw new O(e.message??`Upload failed without a service message. / 上传失败,服务端未提供错误消息。`,D.GENERAL,void 0,{api:{httpStatus:200,apiCode:e.code,requestId:d.request_id},rawResponse:JSON.stringify(d)})}throw new O(`Upload response for ${s} has no usable file ID. / ${s} 的上传响应缺少可用文件 ID。`,D.GENERAL,`Success cannot be verified; inspect the file list before retrying. / 无法验证上传成功,请先检查文件列表,再决定是否重试。`,{api:{httpStatus:200,requestId:d.request_id},rawResponse:JSON.stringify(d)})}async function ny(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Rg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ry(e,t,n){return e.requestJson({path:zg(t),method:`GET`,signal:n})}async function iy(e,t,n){let r=await e.request({path:zg(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const ay=209715200,oy=314572800,sy=314572800,cy=2147483648;function ly(e,t=ay){if(!i(e))throw new O(`File not found: ${e}`,D.USAGE);let n=l(e);if(!n.isFile())throw new O(`Not a regular file: ${e}`,D.USAGE);if(n.size===0)throw new O(`File is empty: ${e}`,D.USAGE);if(n.size>t)throw new O(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,D.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function Z(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function uy(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`decision`||t===`tts`||t===`image`||t===`video`)return t;throw new O(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,D.USAGE,`Omit --schema to auto-detect per record (state/questions → decision, chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, first_frame_path/video_path → video, else ChatML). / 省略 --schema 可逐条自动识别。`)}function dy(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=/* @__PURE__ */ new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const fy=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),py=.1;function my(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<py||a>10)&&i.push(Z(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${py} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(Z(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(Z(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function hy(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(Z(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(Z(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(Z(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(Z(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(Z(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(Z(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(Z(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(Z(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...my(s,Array.isArray(e),t,o))}}}return r}function gy(e,t,n){let r=[];if(!Array.isArray(e))return r.push(Z(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(Z(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(Z(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(Z(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(Z(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(Z(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(Z(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function _y(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(Z(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!fy.has(a))&&r.push(Z(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(Z(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...hy(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(Z(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...gy(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(Z(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(Z(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function vy(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(Z(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(Z(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,o=-1,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(..._y(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(Z(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(Z(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(Z(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(Z(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(Z(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(Z(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;yy(a)&&n.push(Z(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(Z(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];i&&`loss_weight`in i&&(l(i.loss_weight,`messages[${e}].loss_weight`),(i.role!==`assistant`||e!==o)&&n.push(Z(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(Z(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function yy(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const by={name:`chatml`,detect:()=>!0,inspect:vy};function xy(e,t){let n=[];if(!(`text`in e))return n.push(Z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const Sy={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:xy};function Cy(e,t){let n=vy(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(a&&typeof a==`object`)for(let e of[`image`,`video`])e in a&&r.push(Z(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(Z(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(Z(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(Z(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(Z(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(Z(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(..._y(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(..._y(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(Z(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const wy={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Cy},Ty=[`choice`,`noul`,`score`],Ey=255,Dy=2,Oy=255,ky=/* @__PURE__ */ new Set([`true`,`false`]);function Ay(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jy(e){return typeof e==`string`&&e.trim().length>0}function My(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function Ny(e,t=`state`){return jy(e)||Array.isArray(e)&&e.length>0||Ay(e)&&Object.keys(e).length>0?[]:[My(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function Py(e,t){let n=`${t}.criteria`;if(!Ay(e))return[My(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must be an option-to-description object.`,`"${n}" 必须是“选项名到描述”的对象。`)];let r=Object.keys(e).length;if(r<1||r>255)return[My(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must contain 1-255 options (got ${r}).`,`"${n}" 必须包含 1-255 个选项(当前 ${r} 个)。`)];for(let[t,r]of Object.entries(e))if(!jy(t)||!jy(r))return[My(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function Fy(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!jy(e))?[My(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must be an array of non-empty level descriptions, from low to high.`,`"${n}" 必须是从低到高排列、由非空等级描述组成的数组。`)]:e.length<2||e.length>255?[My(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function Iy(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return Ay(e)&&Object.entries(e).every(([e,t])=>ky.has(e)&&typeof t==`string`)?[]:[My(`DECISION_INVALID_NOUL_CRITERIA`,n,`"${n}" is optional; when provided it must be an object with only "true" / "false" string descriptions.`,`"${n}" 为可选项;填写时必须是只包含 "true" / "false" 字符串描述的对象。`)]}function Ly(e,t){if(!Ay(e))return[My(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(My(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...Py(e.criteria,t)):e.type===`noul`?n.push(...Iy(e.criteria,t)):e.type===`score`?n.push(...Fy(e.criteria,t)):n.push(My(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function Ry(e,t=`questions`){return Ay(e)&&Object.keys(e).length>0?[]:[My(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function zy(e,t=`questions`){return jy(e)?[]:[My(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function By(e,t=`questions`){let n=Ry(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=zy(n,t);if(e.length>0){r.push(...e);continue}r.push(...Ly(i,`${t}.${n}`))}return r}function Vy(e,t,n,r){return Z(`error`,e,t,{line:n,path:r})}function Hy(e,t){return Vy(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function Uy(e,t,n,r){if(!Ay(e))return[Vy(`DECISION_INVALID_TARGET`,`"${r}" must be an object containing a complete probability distribution. / "${r}" 必须是包含完整概率分布的对象。`,n,r)];let i=Object.keys(e).sort(),a=[...t].sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return[Vy(`DECISION_INVALID_TARGET_KEYS`,`"${r}" must contain exactly these keys: ${a.join(`, `)}. / "${r}" 必须且只能包含这些键:${a.join(`, `)}。`,n,r)];let o=0;for(let t of a){let i=e[t];if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>1)return[Vy(`DECISION_INVALID_TARGET_PROBABILITY`,`"${r}.${t}" must be a finite number in [0, 1]. / "${r}.${t}" 必须是 [0, 1] 范围内的有限数字。`,n,`${r}.${t}`)];o+=i}return Math.abs(o-1)>1e-6?[Vy(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function Wy(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[Vy(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:Uy(e.target,r,t,`${n}.target`)}function Gy(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:Uy(e.target,[`true`,`false`],t,`${n}.target`):[Vy(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function Ky(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[Vy(`DECISION_INVALID_SCORE_LABEL`,`"${n}.label" must be an integer from 0 to ${r-1}. / "${n}.label" 必须是 0 到 ${r-1} 之间的整数。`,t,`${n}.label`)];let i=Array.from({length:r},(e,t)=>String(t));return e.target===void 0?[]:Uy(e.target,i,t,`${n}.target`)}function qy(e,t){let n=Ny(e.state).map(e=>Hy(e,t)),r=e.questions,i=Ry(r);if(i.length>0)return n.push(...i.map(e=>Hy(e,t))),n;for(let[e,i]of Object.entries(r)){let r=zy(e);if(r.length>0){n.push(...r.map(e=>Hy(e,t)));continue}let a=`questions.${e}`,o=Ly(i,a);if(o.length>0){n.push(...o.map(e=>Hy(e,t)));continue}let s=i;s.type===`choice`?n.push(...Wy(s,t,a)):s.type===`noul`?n.push(...Gy(s,t,a)):n.push(...Ky(s,t,a))}return n}const Jy={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:qy};function Yy(e,t){let n=[];if(!(`wav_fn`in e))n.push(Z(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(Z(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(Z(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(Z(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(Z(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(Z(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(Z(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(Z(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Xy={name:`tts`,detect:e=>`wav_fn`in e,inspect:Yy},Zy=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function Qy(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function $y(e){return/^[\x20-\x7E]+$/.test(e)}function eb(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(Z(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(Z(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(Z(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=Qy(r);Zy.has(e)||n.push(Z(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Zy].join(`, `)}.`,{line:t,path:`img_path`})),$y(r)||n.push(Z(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(Z(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(Z(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=Qy(r);Zy.has(e)||n.push(Z(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...Zy].join(`, `)}.`,{line:t,path:`input_img`})),$y(r)||n.push(Z(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const tb={name:`image`,detect:e=>`img_path`in e,inspect:eb},nb=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),rb=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function ib(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function ab(e){return/^[\x20-\x7E]+$/.test(e)}function ob(e,t,n,r,i,a){if(!(n in t)){r&&e.push(Z(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(Z(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(Z(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=ib(o);i.has(s)||e.push(Z(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),ab(o)||e.push(Z(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function sb(e,t){let n=[];if(!(`prompt`in e))n.push(Z(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(Z(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(Z(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return ob(n,e,`first_frame_path`,!0,nb,t),ob(n,e,`last_frame_path`,!1,nb,t),ob(n,e,`video_path`,!1,rb,t),n}const cb=[Xy,tb,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:sb},Jy,wy,Sy,by];function lb(e,t){return t===void 0?cb.find(t=>t.detect(e))??by:cb.find(e=>e.name===t)||by}async function ub(e,t){let r=n(e,{encoding:`utf8`}),i=oe({input:r,crlfDelay:1/0}),a=[],o=0,s=0;for await(let e of i){if(t?.aborted)break;o++;let n=e.trim();if(n.length===0){s++;continue}a.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&a.push(Z(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function db(e,t,r,i,a){let o=r?null:new Set(dy(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=oe({input:l,crlfDelay:1/0}),d=0;for await(let e of u){if(a?.aborted)break;if(d++,o&&!o.has(d))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(Z(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...fb(n,d,i))}return{sampled:c,issues:s}}function fb(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[Z(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return lb(r,n).inspect(r,t)}const pb={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await ub(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[Z(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await db(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function mb(e,t){return new Promise((n,r)=>{ce.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(/* @__PURE__ */ Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function hb(e){return new Promise((t,n)=>{ce.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}const gb=/^[a-zA-Z0-9_-]+$/;function _b(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function vb(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function yb(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||vb(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=_b(n),i=n.slice(e.length);e.length>0&&!gb.test(e)&&t.length<10&&t.push(Z(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(Z(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=_b(i);if(a.length>120&&t.length<10&&t.push(Z(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(Z(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(Z(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function bb(e,t,n){let{entry:i,zipfile:a}=await mb(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??/* @__PURE__ */ Error(`Failed to open entry stream`));return}let s=r(n);se(o,s).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function xb(e,t=100){let r=n(e,{encoding:`utf8`}),i=oe({input:r,crlfDelay:1/0}),a=[],o=0;for await(let e of i){if(o++,a.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&a.push(e.wav_fn),typeof e.img_path==`string`&&a.push(e.img_path),typeof e.input_img==`string`&&a.push(e.input_img),typeof e.first_frame_path==`string`&&a.push(e.first_frame_path),typeof e.last_frame_path==`string`&&a.push(e.last_frame_path),typeof e.video_path==`string`&&a.push(e.video_path),typeof e.image_fn==`string`&&a.push(e.image_fn),typeof e.video_fn==`string`&&a.push(e.video_fn)}catch{}}return{refs:a,totalLines:o}}const Sb={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await hb(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[Z(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[Z(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(Z(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(Z(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=yb(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(Z(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||vb(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return Zy.has(n)});e.length<25&&r.push(Z(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${re(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await bb(e,_,y)}catch(t){return r.push(Z(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await pb.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await xb(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(Z(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Cb(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return wb(e);if(t===`.zip`)return Tb(e);throw new O(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,D.USAGE)}async function wb(e){let t=await Db(e);if(!t)throw new O(`JSONL file is empty or contains only blank lines: ${e}`,D.USAGE);let n=Eb(t);return n===`unknown`?`text`:n}async function Tb(e){let t=await Ob(e,`data.jsonl`);if(!t)throw new O(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,D.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Eb(t);if(n===`unknown`)throw new O(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,D.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Eb(e){let t;try{t=JSON.parse(e)}catch{throw new O(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,D.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new O(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,D.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Db(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=oe({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function Ob(e,t){return mb(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new O(`Failed to read "${t}" from ZIP: ${e?.message}`,D.USAGE));return}let o=oe({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const kb=[pb,Sb];function Ab(e){let t=h(e).toLowerCase(),n=kb.find(e=>e.extensions.includes(t));if(!n){let e=kb.flatMap(e=>e.extensions).join(`, `);throw new O(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,D.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function jb(e){kb.some(t=>t.format===e.format)||kb.push(e)}async function Mb(e,t={}){let{bytes:n}=ly(e,t.maxBytes??209715200),r=await Ab(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Nb(){return kb.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Pb(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}const Fb=[`/v1/chat/completions`,`/v1/embeddings`,`/v1/chat/ds-test`],Ib=[`validating`,`in_progress`,`finalizing`,`completed`,`failed`,`expired`,`cancelling`,`cancelled`],Lb=/* @__PURE__ */ new Set([`completed`,`failed`,`expired`,`cancelled`]),Rb=524288e3,zb=6291456,Bb=5e4;function Q(e,t){throw new rt(`${e}\n${t}`)}function Vb(e){if(e instanceof O)return e;let t=e?.code;return new O(`Batch file I/O failed${t?` (${t})`:``}.\nBatch 文件读写失败${t?`(${t})`:``}。`,D.GENERAL,t===`ENOENT`?`Check the file and parent directory paths. / 请检查文件及父目录路径。`:t===`EEXIST`?`Output exists; use --force to replace it. / 输出已存在,使用 --force 覆盖。`:`Check file permissions and available disk space. / 请检查文件权限与磁盘空间。`,{cause:e})}function Hb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ub(e){return Fb.includes(e)||Q(`Unsupported Batch endpoint: ${e}`,`不支持的 Batch endpoint:${e}`),e}async function*Wb(e){let t=typeof e==`string`?de(e):e instanceof Blob?Ce.fromWeb(e.stream()):e;try{for await(let e of t)yield e}catch(e){throw Vb(e)}}async function*Gb(e,t=1/0,n=zb){let r=Buffer.alloc(0),i=0,a=new TextDecoder(`utf-8`,{fatal:!0}),o=e=>{try{return a.decode(e)}catch{return Q(`Invalid UTF-8 input.`,`输入不是有效 UTF-8。`)}};for await(let a of Wb(e)){i+=a.byteLength,i>t&&Q(`File exceeds ${t} bytes.`,`文件超过 ${t} 字节。`);let e=Buffer.concat([r,a]),s=0,c=e.indexOf(10,s);for(;c!==-1;){let t=c-s;t>n&&Q(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`),yield{text:o(e.subarray(s,c)).replace(/\r$/,``),bytes:t+1},s=c+1,c=e.indexOf(10,s)}r=Buffer.from(e.subarray(s)),r.byteLength>n&&Q(`JSONL line exceeds 6 MiB.`,`JSONL 单行超过 6 MiB。`)}r.length&&(yield{text:o(r),bytes:r.length})}function Kb(e,t=!1){if(typeof e==`string`&&t){if(/^data:[^,]+;base64,/i.test(e))return;let t;try{t=new URL(e)}catch{return Q(`Media must use a public HTTP(S) or base64 data URL.`,`媒体必须使用公网 HTTP(S) 或 base64 data URL。`)}let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,``),r=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(n),i=r?parseInt(r[1],16):0,a=r?parseInt(r[2],16):0,o=r?[i>>8,i&255,a>>8,a&255].join(`.`):n,s=n===`localhost`||n.endsWith(`.localhost`)||Se(o)===4&&/^(0|10|127|169\.254|172\.(1[6-9]|2\d|3[01])|192\.168)(\.|$)/.test(o)||Se(n)===6&&/^(::1$|::$|f[cd]|fe[89ab])/.test(n);(![`http:`,`https:`].includes(t.protocol)||s)&&Q(`Media URLs must not use local/private addresses.`,`媒体 URL 不得使用本地或私网地址。`)}else if(Array.isArray(e))for(let n of e)Kb(n,t);else if(Hb(e))for(let[n,r]of Object.entries(e))Kb(r,[`image_url`,`video_url`,`audio_url`,`file_url`,`image`,`video`].includes(n)||t&&n===`url`)}var qb=class{ids=/* @__PURE__ */ new Set;thinking;report={records:0,bytes:0,model:``,endpoint:`/v1/chat/completions`,warnings:[]};warn(e){this.report.warnings.includes(e)||this.report.warnings.push(e)}add(e,t){let n=this.report.records+1,r=e=>Q(`Invalid or inconsistent ${e} at record ${n}.`,`第 ${n} 条记录的 ${e} 无效或不一致。`);Hb(e)||r(`JSON object`);let i=e,a=i.custom_id;(typeof a!=`string`||!a.trim()||Array.from(a).length>256||this.ids.has(a))&&r(`custom_id`),i.method!==`POST`&&r(`method=POST`);let o=Ub(String(i.url));Hb(i.body)||r(`body`);let s=i.body;if((typeof s.model!=`string`||!s.model.trim())&&r(`body.model`),s.enable_thinking!==void 0&&typeof s.enable_thinking!=`boolean`&&r(`enable_thinking`),this.report.records&&(this.report.model!==s.model||this.report.endpoint!==o||this.thinking!==s.enable_thinking)&&r(`model/url/enable_thinking`),o===`/v1/embeddings`){let e=e=>typeof e==`string`&&!!e.trim(),t=e=>Array.isArray(e)&&e.length>0&&e.every(e=>Number.isInteger(e)&&e>=0);e(s.input)||t(s.input)||Array.isArray(s.input)&&s.input.length>0&&(s.input.every(e)||s.input.every(t))||r(`body.input`)}else(!Array.isArray(s.messages)||!s.messages.length||s.messages.some(e=>!Hb(e)||typeof e.role!=`string`||!e.role.trim()||typeof e.content!=`string`&&!(Array.isArray(e.content)&&e.content.length>0&&e.content.every(Hb))&&!(Array.isArray(e.tool_calls)&&e.tool_calls.length>0&&e.tool_calls.every(Hb))))&&r(`body.messages`);Kb(s),Hb(s.extra_body)&&(`enable_thinking`in s.extra_body||`thinking_budget`in s.extra_body)&&this.warn(`Place enable_thinking/thinking_budget at body top level, not extra_body. / enable_thinking/thinking_budget 应放在 body 顶层,而非 extra_body。`),t>6291456&&r(`line <=6 MiB`),t>1048576&&this.warn(`Line exceeds 1 MiB; documentation differs (1/6 MiB), compatibility is not guaranteed. / 单行超过 1 MiB,文档存在 1/6 MiB 差异,不保证兼容。`),this.ids.add(a),this.report.records++,this.report.bytes+=t,this.report.model=s.model,this.report.endpoint=o,this.thinking=s.enable_thinking,(this.report.records>5e4||this.report.bytes>524288e3)&&r(`50000 records / 500 MiB`),s.model===`batch-test-model`&&(this.report.records>100||this.report.bytes>1048576)&&r(`batch-test-model: 100 records / 1 MiB`)}finish(){return this.report.records||Q(`Batch input is empty.`,`Batch 输入为空。`),this.report}};async function Jb(e){let t=new qb,n=0;for await(let r of Gb(e,Rb)){n++;let e;try{e=JSON.parse(r.text)}catch{Q(`Invalid JSONL at line ${n}.`,`第 ${n} 行不是有效 JSONL。`)}t.add(e,r.bytes)}return t.finish()}async function Yb(e){let t=[],n=0;for await(let r of Wb(e))n+=r.byteLength,n>524288e3&&Q(`File exceeds 500 MiB.`,`文件超过 500 MiB。`),t.push(r);return new Blob(t)}function Xb(e,t,n){return e.requestJson({path:Qh(),method:`POST`,body:t,signal:n})}function Zb(e,t,n){return e.requestJson({path:$h(t),signal:n})}function Qb(e,t,n){return e.requestJson({path:eg(t),method:`POST`,signal:n})}function $b(e,t={},n){let r=new URLSearchParams;for(let[e,n]of Object.entries(t))n!==void 0&&r.set(e,Array.isArray(n)?n.join(`,`):String(n));return e.requestJson({path:Qh()+(r.size?`?${r.toString()}`:``),signal:n})}function ex(e,t,n){return e.request({path:tg(t),signal:n})}function tx(e){let t=e.url(Zh(),ng),n=new URL(t).hostname.toLowerCase(),r=new URL(e.baseUrl).hostname.toLowerCase();return(e.usesTokenPlanEndpoint()||/^dashscope(?:-intl|-us)?\.aliyuncs\.com$/.test(n)||/^dashscope-(?:intl|us)\.aliyuncs\.com$/.test(r))&&Q(`--batch needs the Batch host, not a realtime/international/Token Plan endpoint; configure --base-url explicitly.`,`--batch 不能使用实时、国际站或 Token Plan 端点,请显式配置 Batch --base-url。`),t}async function nx(e,t,n=!1){let r=Oe(e),i=Oe(Te(r),`.${we(r)}.${ze()}.tmp`),a,o=e=>{throw Vb(e)};try{await Ne(Te(r),{recursive:!0}).catch(o),a=await Pe(i,`wx`,384).catch(o);for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e,n=0;for(;n<t.byteLength;){let e=await a.write(t,n,t.byteLength-n).catch(o);n+=e.bytesWritten}}await a.sync().catch(o),await a.close().catch(o),a=void 0,n?await Ie(i,r).catch(o):await Me(i,r).catch(o)}finally{await a?.close().catch(()=>{}),await Le(i).catch(()=>{})}}async function rx(e){let t=Ub(e.endpoint??`/v1/chat/completions`);(Oe(e.file)===Oe(e.outputFile)||e.bodyFile&&Oe(e.bodyFile)===Oe(e.outputFile))&&Q(`Output must differ from input/body file.`,`输出路径必须与输入及 body 文件不同。`),e.model.trim()||Q(`Model must not be empty.`,`模型不能为空。`);let n=e.idColumn??`custom_id`,r=e.inputColumn??`content`,i={};if(e.bodyFile){let t;try{t=await Fe(e.bodyFile,`utf8`)}catch(e){throw Vb(e)}try{let e=JSON.parse(t);if(!Hb(e))throw Error();i=e}catch{Q(`--body-file must contain a JSON object.`,`--body-file 必须包含 JSON 对象。`)}}[`model`,`messages`,`input`].some(e=>e in i)&&Q(`--body-file cannot define model/messages/input.`,`--body-file 不得定义 model/messages/input。`),t===`/v1/embeddings`&&(e.system!==void 0||`enable_thinking`in i||`thinking_budget`in i)&&Q(`System/thinking parameters do not apply to embeddings.`,`向量请求不适用系统提示词或思考参数。`);let a=new qb,o=[],s=[],c;async function*l(){let t=new TextDecoder(`utf8`,{fatal:!0}),n=0;for await(let r of Wb(e.file)){n+=r.byteLength,n>524288e3&&Q(`CSV exceeds 500 MiB.`,`CSV 超过 500 MiB。`);try{yield t.decode(r,{stream:!0})}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}try{yield t.decode()}catch{Q(`CSV must be UTF-8.`,`CSV 必须是 UTF-8。`)}}async function*u(){let u=Ce.from(l()),d=Ae({bom:!0,max_record_size:6291456,columns:e=>((new Set(e).size!==e.length||!e.includes(n)||!e.includes(r))&&Q(`CSV requires unique headers and mapped ID/input columns.`,`CSV 表头必须唯一并包含映射的 ID/输入列。`),s=e.filter(e=>e!==n&&e!==r),e)});u.on(`error`,e=>d.destroy(e)),u.pipe(d);let f=0;try{for await(let s of d){f++;let c=s;c[r]?.trim()||Q(`Empty CSV input at record ${f}.`,`CSV 第 ${f} 条记录输入为空。`);let l={...i,model:e.model};t===`/v1/embeddings`?(l.input=c[r],l.encoding_format??=`float`):l.messages=[...e.system===void 0?[]:[{role:`system`,content:e.system}],{role:`user`,content:c[r]}];let u={custom_id:c[n],method:`POST`,url:t,body:l},d=JSON.stringify(u)+`
|
|
78
|
+
`;a.add(u,Buffer.byteLength(d)),e.dryRun&&o.length<2&&o.push(u),yield d}c=a.finish()}catch(e){throw e instanceof Error&&e.name===`Error`&&`code`in e&&String(e.code).startsWith(`CSV_`)&&Q(`Invalid CSV near record ${f+1}: ${e.message}`,`第 ${f+1} 条记录附近 CSV 格式错误:${e.message}`),Vb(e)}finally{u.destroy(),d.destroy()}}if(e.dryRun)for await(let e of u());else await nx(e.outputFile,u(),e.force);return{...c,output_file:Oe(e.outputFile),ignored_columns:s,...e.dryRun?{samples:o}:{}}}const ix=[`custom_id`,`model`,`request_id`,`status_code`,`content`,`embedding`,`error_code`,`error_message`,`prompt_tokens`,`completion_tokens`,`total_tokens`];function ax(e){return Hb(e)?e:{}}function ox(e){let t=e==null?``:typeof e==`string`?e:JSON.stringify(e);return/^[\s\x00-\x1f]*[=+@-]/.test(t)?`'${t}`:t}function sx(e){return typeof e==`number`&&Number.isFinite(e)?e:``}function cx(e){let t=ax(e),n=ax(t.response),r=ax(n.body),i=ax(t.error??r.error),a=ax(r.usage),o=ax(ax(Array.isArray(r.choices)?r.choices[0]:void 0).message),s=Array.isArray(r.data)?r.data.map(e=>{let t=ax(e);return{index:t.index,embedding:t.embedding}}):void 0;return{recognized:Array.isArray(r.choices)||Array.isArray(r.data)||`code`in i||`message`in i,row:{custom_id:ox(t.custom_id),model:ox(r.model),request_id:ox(n.request_id),status_code:sx(n.status_code),content:ox(o.content),embedding:ox(s),error_code:ox(i.code),error_message:ox(i.message),prompt_tokens:sx(a.prompt_tokens),completion_tokens:sx(a.completion_tokens),total_tokens:sx(a.total_tokens)}}}async function lx(e,t,n=!1){let r=0,i=0;async function*a(){yield``+je([],{columns:[...ix],header:!0});for(let t of e)for await(let e of Gb(t,1/0,1/0)){if(!e.text.trim())continue;let n;try{n=JSON.parse(e.text)}catch{Q(`Invalid result JSONL at ${t}:${r+1}.`,`结果 JSONL 格式错误:${t}:${r+1}。`)}let a=cx(n);r++,a.recognized||i++,yield je([a.row],{columns:[...ix]})}}return await nx(t,a(),n),{records:r,unknown_records:i}}function ux(e){let t=e===`zh-CN`?`请介绍一下自己`:`Introduce yourself`,n={custom_id:`req-001`,method:`POST`,url:`/v1/chat/completions`,body:{model:`qwen-plus`,messages:[{role:`user`,content:t}]}},r={custom_id:`req-001`,method:`POST`,url:`/v1/embeddings`,body:{model:`text-embedding-v4`,input:t,encoding_format:`float`}},i={custom_id:`req-001`,method:`POST`,url:`/v1/chat/completions`,body:{model:`qwen-vl-plus`,messages:[{role:`user`,content:[{type:`text`,text:t},{type:`image_url`,image_url:{url:`https://example.com/image.jpg`}}]}]}},a={custom_id:`req-001`,response:{request_id:`request-001`,status_code:200,body:{model:`qwen-plus`,choices:[{message:{role:`assistant`,content:e===`zh-CN`?`你好`:`Hello`}}],usage:{prompt_tokens:10,completion_tokens:2,total_tokens:12}}},error:null};return{csv:`custom_id,content\nreq-001,${t}\nreq-002,2+2?`,chat:n,embedding:r,vision:i,defaults:{enable_thinking:!1,max_tokens:1024},success:a,failure:{custom_id:`req-002`,response:null,error:{code:`ExampleError`,message:`Example service error`}}}}function dx(e){let t=t=>{let n=ux(t);if(e===`prepare`||e===`convert`)return`input.csv:\n${n.csv}\n\ninput.jsonl:\n${JSON.stringify(n.chat)}\n\ndefaults.json (--body-file):\n${JSON.stringify(n.defaults)}`;if(e===`create`)return`Chat JSONL:\n${JSON.stringify(n.chat)}\n\nEmbedding JSONL:\n${JSON.stringify(n.embedding)}\n\nMultimodal JSONL (${t===`zh-CN`?`请替换示例公网图片 URL`:`replace the example public image URL`}):\n${JSON.stringify(n.vision)}`;let r=je([n.success,n.failure].map(e=>cx(e).row),{columns:[...ix],header:!0});return`result.jsonl:\n${JSON.stringify(n.success)}\n\nerror.jsonl (${t===`zh-CN`?`示意包络,真实服务需联调`:`illustrative envelope; verify with the service`}):\n${JSON.stringify(n.failure)}\n\nresult.csv:\n${r}`};return{"en-US":t(`en-US`),"zh-CN":t(`zh-CN`)}}const fx=`decision-model-preview`,px=[`cn-beijing`,`ap-southeast-1`],mx=`cn-beijing`,hx=[`label`,`target`];function gx(e){if(!Ay(e))return e;let t=e.questions;return Ay(t)&&typeof t.type!=`string`?t:e}function _x(e){if(!Ay(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!Ay(r)){t[n]=r;continue}let e={...r};for(let t of hx)delete e[t];t[n]=e}return t}async function vx(e,t,n,r){let i=await e.requestJson({path:Xh(t,n,`submit`),method:`POST`,body:r});if(typeof i?.data?.biz_id!=`string`||!i.data.biz_id.trim())throw new O(`ParseX response is missing data.biz_id; submission may have succeeded. / ParseX 响应缺少 data.biz_id,任务可能已提交成功。`,void 0,`Check the task before submitting again. / 请核对任务后再决定是否重新提交。`,{api:{requestId:i?.request_id}});return i}async function yx(e,t,n,r,i){let a=await e.requestJson({path:Xh(t,n,`result`),method:`POST`,body:r,signal:i});if(typeof a?.data?.status!=`string`||!a.data.status.trim())throw new O(`ParseX response is missing data.status. / ParseX 响应缺少 data.status。`,void 0,void 0,{api:{requestId:a?.request_id}});return a}async function bx(e,t,n,r,i){let a=new AbortController,o=()=>a.abort(i.signal?.reason);i.signal?.aborted?o():i.signal?.addEventListener(`abort`,o,{once:!0});let s=setTimeout(()=>a.abort(new O(`ParseX polling timed out. / ParseX 轮询超时。`,D.TIMEOUT,`The remote task was not cancelled; query the same biz_id: ${r.biz_id}. / 未取消远端任务,请使用同一 biz_id 继续查询。`)),i.pollTimeout*1e3);try{for(;;){a.signal.throwIfAborted();try{let o=await yx(e,t,n,r,a.signal);if(a.signal.throwIfAborted(),i.progress?.(o),o.data.status===`success`||o.data.status===`failed`)return o}catch(e){if(a.signal.aborted||!(e instanceof O)||e.api?.apiCode!==`ResultNotReady`)throw e}await Be(i.interval*1e3,void 0,{signal:a.signal})}}catch(e){throw a.signal.aborted?a.signal.reason:e}finally{clearTimeout(s),i.signal?.removeEventListener(`abort`,o)}}async function xx(e,t,n){return e.requestJson({path:Bg(),method:`POST`,body:t,signal:n})}async function Sx(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status),t.model&&n.set(`model`,t.model);let r=Bg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Cx(e,t,n){return e.requestJson({path:Vg(t),method:`GET`,signal:n})}async function wx(e,t,n){return e.requestJson({path:Hg(t),method:`POST`,signal:n})}async function Tx(e,t,n){return e.requestJson({path:Vg(t),method:`DELETE`,signal:n})}async function Ex(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=Ug(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Dx(e,t,n){return e.requestJson({path:Wg(t),method:`GET`,signal:n})}async function Ox(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${Jg(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function kx(e,t){let n=new URLSearchParams;for(let[e,r]of Object.entries(t))r!==void 0&&r!==``&&n.set(e,String(r));return n.toString()?`${e}?${n.toString()}`:e}async function Ax(e,t={}){return e.requestJson({path:kx(Yg(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function jx(e,t,n){return e.requestJson({path:Xg(),method:`POST`,body:t,signal:n})}async function Mx(e,t={}){let n=kx(Xg(),{status:t.status,model:t.model,template_id:t.templateId,quant_spec:t.quantSpec,quant_method:t.quantMethod,start_time:t.startTime,end_time:t.endTime,search_key:t.searchKey,select_key:t.selectKey,sort_order:t.sortOrder,page_no:t.pageNo,page_size:t.pageSize});return e.requestJson({path:n,method:`GET`,signal:t.signal})}async function Nx(e,t,n){return e.requestJson({path:Zg(t),method:`GET`,signal:n})}async function Px(e,t,n={}){return e.requestJson({path:kx($g(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function Fx(e,t,n){return e.requestJson({path:Qg(t),method:`POST`,signal:n})}async function Ix(e,t,n){return e.requestJson({path:Zg(t),method:`DELETE`,signal:n})}const Lx={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},Rx=Object.keys(Lx),zx=`sft-lora`;function Bx(e){return e in Lx}function Vx(e){let{method:t,variant:n}=Lx[e];return{method:t,variant:n}}function Hx(e,t){if(!e)return!1;let{method:n,variant:r}=Lx[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function Ux(e){return e?Rx.filter(t=>Hx(e,t)):[]}async function Wx(e,t,n={}){return await Vv(En(e,n),t)}const Gx=`INSUFFICIENT_SAMPLES`;function Kx(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:Gx,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
|
|
79
|
+
`)}}function qx(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function Jx(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return Mb(e,{...r,schema:n})},resolveHyperParameters(e,t){return qx(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const Yx=Jx(`sft`,`sft`,`chatml`),Xx={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},Zx={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},Qx={...Zx,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},$x={n_epochs:50,learning_rate:`2e-5`,split:.5,max_split_val_dataset_sample:5,eval_epochs:20,save_total_limit:10,lora_rank:32,lora_alpha:32};function eS(e){return e===`image`||e===`image-i2i`}function tS(e){return e===`video`||e===`video-kf2v`}function nS(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function rS(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const iS=[Yx,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return Mb(e,{...n,schema:`tts`});if(eS(t))return Mb(e,{...n,schema:`image`,maxBytes:cy});if(tS(t)){let r=await Mb(e,{...n,schema:`video`,maxBytes:cy});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(Z(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(Z(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return Mb(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...Xx};if(eS(e)){let n={...e===`image-i2i`?Qx:Zx};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(tS(e)){let e=t.model??t.baseModel,n={...$x,batch_size:rS(e)?1:4,max_pixels:rS(e)?102400:nS(e)?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.batchSize!==void 0&&(n.batch_size=t.batchSize),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return qx(t)},shouldSkipGate(e,t){return!(t!==`audio`&&!eS(t)&&!tS(t)||e!==`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||eS(e)||tS(e)}},Jx(`dpo`,`dpo_full`,`dpo`),Jx(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return Mb(e,{...n,schema:`cpt`,maxBytes:oy})},resolveHyperParameters(e,t){return qx(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function aS(e){let t=iS.find(t=>t.clientTrainingType===e);if(!t){let t=iS.map(e=>e.clientTrainingType).join(`, `);throw new O(`Unknown training type "${e}".`,D.USAGE,`Supported training types: ${t}.`)}return t}function oS(){return iS.map(e=>e.clientTrainingType)}const sS=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,cS=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,lS=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function uS(e,t){return Rv(await e.console(sS,{query:{type:0,modelId:t}}))}async function dS(e,t,n){return Rv(await e.console(cS,{input:{trainDatasetIds:t,hyperParams:n}}))}async function fS(e,t,n,r){let i=JSON.stringify({useDefault:!1,userDefinedObj:{batch_size:16,eval_steps:50,learning_rate:`7e-6`,lr_scheduler_type:`linear`,max_length:8192,n_epochs:r,split:.9,save_total_limit:`3`,resume_from_checkpoint:!1,save_strategy:`epoch`},useQwenMixedStrategy:!1});return Rv(await e.console(lS,{input:{trainingType:`cpt`,instanceName:`${t}_cli_estimate`,algorithmType:100,bizType:100,trainDatasetIds:n,hyperParams:i,bailianTrainModel:t,validationDatasetIds:``,jobName:`${t}_cli_estimate`,priority:`L0`}}))}function pS(e){return e?{"x-acs-req-uuid":e,"X-DashScope-RequestId":e}:void 0}async function mS(e,t,n){return e.requestJson({path:e_(),method:`POST`,body:t,signal:n})}async function hS(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.plan!==void 0&&n.set(`plan`,t.plan);let r=e_(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function gS(e,t,n){return e.requestJson({path:t_(t),method:`GET`,signal:n})}async function _S(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize)),n.includeDeleted!==void 0&&r.set(`include_deleted`,String(n.includeDeleted)),n.statuses!==void 0&&r.set(`statuses`,n.statuses.join(`,`)),n.chargeTypes!==void 0&&r.set(`charge_types`,n.chargeTypes.join(`,`));let i=n_(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function vS(e,t,n,r){return e.requestJson({path:r_(t,n),method:`GET`,signal:r})}async function yS(e,t,n,r){return e.requestJson({path:s_(t,n),method:`GET`,signal:r})}async function bS(e,t,n,r={}){return e.requestJson({path:n_(t),method:`POST`,body:n,headers:pS(r.requestId),signal:r.signal})}async function xS(e,t,n,r,i={}){return e.requestJson({path:i_(t,n),method:`PUT`,body:r,headers:pS(i.requestId),signal:i.signal})}async function SS(e,t,n,r,i={}){return e.requestJson({path:a_(t,n),method:`PUT`,body:r,headers:pS(i.requestId),signal:i.signal})}async function CS(e,t,n,r={}){let i=r_(t,n),a=new URLSearchParams;return r.reason!==void 0&&a.set(`reason`,r.reason),e.requestJson({path:a.toString()?`${i}?${a.toString()}`:i,method:`DELETE`,headers:pS(r.requestId),signal:r.signal})}async function wS(e,t,n,r){return e.requestJson({path:o_(t),method:`PUT`,body:{overflow_strategy:n},signal:r})}async function TS(e,t,n){return e.requestJson({path:t_(t),method:`DELETE`,signal:n})}async function ES(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.version&&n.set(`version`,t.version),t.modelSource&&n.set(`model_source`,t.modelSource);let r=u_(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function DS(e,t,n,r,i){return e.requestJson({path:c_(t),method:`PUT`,body:n,headers:pS(i),signal:r})}async function OS(e,t,n,r){return e.requestJson({path:l_(t),method:`PUT`,body:n,signal:r})}const kS={LORA:`lora`,PTU:`ptu`,MU:`mu`},AS=kS.LORA;function jS(e){return e===`audio`?kS.MU:AS}const MS={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},NS=MS.POST_PAY,PS={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`};function FS(e,t){if(t||e.inputTpm!==void 0||e.outputTpm!==void 0){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm must be provided together.
|
|
81
80
|
必须同时提供 --input-tpm 和 --output-tpm。`;if(!Number.isSafeInteger(e.inputTpm)||e.inputTpm<0)return`--input-tpm must be a non-negative safe integer in kTPM.
|
|
82
81
|
--input-tpm 必须是非负安全整数,单位为 kTPM。`;if(!Number.isSafeInteger(e.outputTpm)||e.outputTpm<0)return`--output-tpm must be a non-negative safe integer in kTPM.
|
|
83
|
-
--output-tpm 必须是非负安全整数,单位为 kTPM。`}}function
|
|
82
|
+
--output-tpm 必须是非负安全整数,单位为 kTPM。`}}function IS(e){let t={};return e.inputTpm!==void 0&&(t.input_tpm=e.inputTpm),e.outputTpm!==void 0&&(t.output_tpm=e.outputTpm),t}function LS(e){return e.duration!==void 0||e.autoRenewal!==void 0||e.autoRenewalDuration!==void 0||e.autoRenewalCycle!==void 0}function RS(e,t){if(t||LS(e)){if(e.duration===void 0||!Number.isSafeInteger(e.duration)||e.duration<=0)return`--duration must be a positive safe integer in days.
|
|
84
83
|
--duration 必须是正安全整数,单位为天。`;if(typeof e.autoRenewal!=`boolean`)return`--auto-renewal must explicitly be true or false.
|
|
85
84
|
必须显式指定 --auto-renewal 为 true 或 false。`;if((e.autoRenewal||e.autoRenewalDuration!==void 0)&&(e.autoRenewalDuration===void 0||!Number.isSafeInteger(e.autoRenewalDuration)||e.autoRenewalDuration<=0))return`--auto-renewal-duration must be a positive safe integer in days; required when --auto-renewal=true.
|
|
86
85
|
--auto-renewal-duration 必须是正安全整数(天);开启自动续费时必填。`;if(e.autoRenewalCycle!==void 0&&(typeof e.autoRenewalCycle!=`string`||e.autoRenewalCycle.trim()===``))return`--auto-renewal-cycle must be a non-empty string.
|
|
87
|
-
--auto-renewal-cycle 必须是非空字符串。`}}function
|
|
88
|
-
plan=ptu 不支持 --capacity、--deploy-spec 和 --billing-method;请使用预留容量参数和 --charge-type。`:e.thinkingOutputTpm===void 0?e.chargeType!==
|
|
86
|
+
--auto-renewal-cycle 必须是非空字符串。`}}function zS(e){if(!LS(e))return;let t={};return e.duration!==void 0&&(t.duration=e.duration),e.autoRenewal!==void 0&&(t.auto_renewal=e.autoRenewal),e.autoRenewalDuration!==void 0&&(t.auto_renewal_duration=e.autoRenewalDuration),e.autoRenewalCycle!==void 0&&(t.auto_renewal_cycle=e.autoRenewalCycle),t}const BS={name:kS.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},VS={name:kS.PTU,validateFlags(e){return e.capacity!==void 0||e.deploySpec!==void 0||e.billingMethod!==void 0?`--capacity, --deploy-spec and --billing-method are not supported for plan=ptu; use reservation capacity and --charge-type.
|
|
87
|
+
plan=ptu 不支持 --capacity、--deploy-spec 和 --billing-method;请使用预留容量参数和 --charge-type。`:e.thinkingOutputTpm===void 0?e.chargeType!==PS.PRE_PAID&&e.chargeType!==PS.POST_PAID?`--charge-type is required for plan=ptu and must be pre_paid or post_paid.
|
|
89
88
|
plan=ptu 必须提供 --charge-type,且只能为 pre_paid 或 post_paid。`:e.serviceTier!==void 0&&e.serviceTier!==`ptu_fast`&&e.serviceTier!==`ptu_default`?`--service-tier must be ptu_fast or ptu_default.
|
|
90
|
-
--service-tier 只能为 ptu_fast 或 ptu_default。`:e.serviceTier===`ptu_default`&&e.chargeType===
|
|
91
|
-
ptu_default 仅支持 pre_paid。`:e.chargeType===
|
|
92
|
-
--charge-type post_paid 不允许提供预付费参数。`:
|
|
93
|
-
当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:bS(e.flags)};e.flags.serviceTier!==void 0&&(t.service_tier=e.flags.serviceTier),e.flags.suffix!==void 0&&(t.suffix=e.flags.suffix);let n=CS(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},ES={name:pS.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||_S,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new D(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,E.USAGE);try{let a=await uS(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===pS.MU)?.templates??[];if(o.length===0)throw i();let s=t===gS.POST_PAY?vS.POST_PAID:vS.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof D?e:new D(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,E.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},DS={[pS.LORA]:wS,[pS.PTU]:TS,[pS.MU]:ES};function OS(e){let t=DS[e];if(!t)throw new D(`Unsupported plan "${e}". Supported plans: ${Object.keys(DS).join(`, `)}.`,E.USAGE);return t}const kS=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,AS=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,jS=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function MS(e,t){return Dv(await e.console(kS,{input:{modelServiceId:t}}))}async function NS(e,t){return Dv(await e.console(AS,{input:{modelServiceId:t}}))}async function PS(e){let t=[],n=1;for(;;){let r=Dv(await e.console(jS,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function FS(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const IS=`speech-biasing`;function LS(e,t){return{model:IS,input:{action:e,...t}}}async function RS(e,t,n,r){return e.requestJson({path:gg(),method:`POST`,body:LS(t,n),signal:r})}function zS(e,t,n){return RS(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function BS(e,t={},n){let r={};return t.prefix!==void 0&&(r.prefix=t.prefix),t.pageIndex!==void 0&&(r.page_index=t.pageIndex),t.pageSize!==void 0&&(r.page_size=t.pageSize),RS(e,`list_vocabulary`,r,n)}function VS(e,t,n){return RS(e,`query_vocabulary`,{vocabulary_id:t},n)}function HS(e,t,n,r){return RS(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function US(e,t,n){return RS(e,`delete_vocabulary`,{vocabulary_id:t},n)}function WS(e,t){try{return JSON.parse(e)}catch(e){throw new nt(`${t} is not valid JSON — ${e.message}`)}}function GS(e){let t=WS(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new nt(`--vocabulary must decode to a JSON object of word→weight.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new nt(`--vocabulary weight for "${e}" must be a number.`);return t}function KS(e,t){let n=`--words`,r=WS(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new nt(`${n} entry #${t} must be an object with string "text" and number "weight".`);let r=e;if(typeof r.text!=`string`||typeof r.weight!=`number`)throw new nt(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new nt(`${n} entry #${t} weight must be a finite number.`);return{text:r.text,weight:r.weight,...typeof r.lang==`string`?{lang:r.lang}:{}}});else if(!r||typeof r!=`object`)throw new nt(`${n} must decode to a JSON object or array.`);else{i=[];for(let[e,a]of Object.entries(r)){if(typeof a!=`number`||!Number.isFinite(a))throw new nt(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new nt(`${n} must contain at least one hot word.`);return i}const qS={introspect:{type:`switch`,description:{"en-US":`Print the machine-readable command schema (JSON) and exit`,"zh-CN":`输出机器可读的命令说明(JSON)并退出`}},output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},JS={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},YS={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},XS={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},ZS={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},QS={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function $S(e){return e.auth===`apiKey`?XS:e.auth===`console`?ZS:e.auth===`openapi`?QS:{}}function eC(e){return e}const tC=1;function nC(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function rC(e,t){return`${nC(e||`image`,`image`)}_${nC((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function iC(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return aC(t);if(process.platform===`win32`){let t=process.env.LOCALAPPDATA?.trim();return t?g(t,`hermes`):g(e,`AppData`,`Local`,`hermes`)}return g(e,`.hermes`)}function aC(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const oC=()=>g(f(),`bailian-output`);function sC(e,t){let n=t?.flagDir||e.outputDir||oC(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function cC(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function lC(e){return o(e===`-`?0:e,`utf-8`)}async function uC(e,t){let n=[],r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}let a=Array.from({length:Math.min(t,e.length)},()=>i());return await Promise.all(a),n}function dC(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new D(`Invalid ${t} value "${String(e)}". Use true or false.`,E.USAGE)}function fC(e,t=`boolean`){if(e!=null)return dC(e,t)}function pC(e,t,n=`boolean`){let r=fC(e,n);return r===void 0?t:r}function mC(e,t){return fC(e,`watermark`)??t??!0}const hC=/^[a-z0-9][a-z0-9.-]{0,63}$/,gC=/^bailian-[a-z0-9-]{1,64}$/,_C=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function vC(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function yC(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return hC.test(t)?t:`unknown`}function bC(e){let t=vC(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t!==`agent`&&t!==`ai_agent`)return{callerType:`unknown`};let n=vC(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),r=n!==void 0&&gC.test(n)?n:void 0,i=vC(e,`BAILIAN_SKILL_VERSION`),a=r!==void 0&&i!==void 0&&_C.test(i)?i:void 0;return{callerType:`agent`,callerName:yC(vC(e,`BAILIAN_CALLER_NAME`)),...r===void 0?{}:{skillName:r},...a===void 0?{}:{skillVersion:a}}}function xC(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform,callerType:e.caller.callerType};return e.caller.callerType===`agent`&&(t.callerName=e.caller.callerName,e.caller.skillName!==void 0&&(t.skillName=e.caller.skillName),e.caller.skillVersion!==void 0&&(t.skillVersion=e.caller.skillVersion)),e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.exitCode!==void 0&&(t.exitCode=e.error.exitCode),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function SC(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function CC(e){let{command:t,params:n,...r}=e,i={et:`EXP`,ext:r,c1:n,c2:e.success?`success`:`failure`};return e.httpStatus!==void 0&&(i.c3=String(e.httpStatus)),e.errorMessage&&(i.c4=SC(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let wC;function TC(){return wC||(process.env.NODE_ENV===`development`?(wC=`dev`,wC):process.env.BAILIAN_COMPILED===`1`?(wC=`prod`,wC):(wC=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,wC))}var EC=/* @__PURE__ */ T(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=tt(`os`)},function(e,t){e.exports=(...e)=>(process.versions.bun?globalThis.fetch:tt(`undici`).fetch)(...e)},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=tt(`dns`)},function(e,t){e.exports=tt(`util`)},function(e,t){e.exports=tt(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},b=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},ce=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},pe=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},me=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},he=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ge=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},_e=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ve=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ye=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map;S.set(`Baiduspider-render`,i),S.set(`Baiduspider+`,i),S.set(`Baiduspider-image+`,i),S.set(`360Spider`,a),S.set(`360Spider-Image`,a),S.set(`bingbot`,o),S.set(`Googlebot`,s),S.set(`YandexRenderResourcesBot`,c),S.set(`spider`,l),S.set(`Dataprovider.com`,u),S.set(`AhrefsBot`,d),S.set(`BitSightBot`,f),S.set(`oBot`,p),S.set(`Cincraw`,m),S.set(`DingTalkBot-LinkService`,h),S.set(`YisouSpider`,g),S.set(`Bytespider`,_),S.set(`ev-crawler`,v),S.set(`bitdiscovery`,y),S.set(`Spider`,ee),S.set(`Ai2Bot-Dolma`,b),S.set(`dianjing_ad_spider`,te),C.set(`Baiduspider-render`,ne),C.set(`Baiduspider+`,ne),C.set(`Baiduspider-image+`,ne),C.set(`360Spider`,re),C.set(`360Spider-Image`,re),C.set(`bingbot`,ie),C.set(`Googlebot`,ae),C.set(`YandexRenderResourcesBot`,oe),C.set(`spider`,se),C.set(`Dataprovider.com`,ce),C.set(`AhrefsBot`,le),C.set(`BitSightBot`,ue),C.set(`oBot`,de),C.set(`Cincraw`,fe),C.set(`DingTalkBot-LinkService`,pe),C.set(`YisouSpider`,x),C.set(`Bytespider`,me),C.set(`ev-crawler`,he),C.set(`bitdiscovery`,ge),C.set(`Spider`,_e),C.set(`Ai2Bot-Dolma`,ve),C.set(`dianjing_ad_spider`,ye);let be={productHandlerMap:S,commentHandlerMap:C,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,be),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=/* @__PURE__ */ new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,"DEFAULT_MODEL_HANDLER_KEY",{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,"createUAInfo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,"runTask",{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:(/* @__PURE__ */ new Date()).getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||(/* @__PURE__ */ new Date()).getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var ee=y,b=n(3),te=n.n(b),ne=n(4),re=n(5),ie=n.n(re);function ae(e){return(ae=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function oe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function se(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?oe(Object(n),!0).forEach(function(t){ce(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oe(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ce(e,t,n){return(t=(function(e){var t=(function(e,t){if(ae(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ae(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return ae(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function le(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=de(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
94
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function
|
|
95
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function
|
|
96
|
-
`,{mode:384})}catch{}}async function
|
|
89
|
+
--service-tier 只能为 ptu_fast 或 ptu_default。`:e.serviceTier===`ptu_default`&&e.chargeType===PS.POST_PAID?`ptu_default only supports pre_paid.
|
|
90
|
+
ptu_default 仅支持 pre_paid。`:e.chargeType===PS.POST_PAID&&LS(e)?`Prepaid flags are not allowed with --charge-type post_paid.
|
|
91
|
+
--charge-type post_paid 不允许提供预付费参数。`:FS(e,!0)??RS(e,e.chargeType===PS.PRE_PAID):`--thinking-output-tpm is not supported by current reservation models.
|
|
92
|
+
当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:IS(e.flags)};e.flags.serviceTier!==void 0&&(t.service_tier=e.flags.serviceTier),e.flags.suffix!==void 0&&(t.suffix=e.flags.suffix);let n=zS(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},HS={name:kS.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||NS,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new O(`No mu-plan template found for model "${e.model}". `+(e.modelUnavailableHint??`Pass --deploy-spec explicitly.`),D.USAGE);try{let a=await ES(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===kS.MU)?.templates??[];if(o.length===0)throw i();let s=t===MS.POST_PAY?PS.POST_PAID:PS.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof O?e:new O(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,D.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},US={[kS.LORA]:BS,[kS.PTU]:VS,[kS.MU]:HS};function WS(e){let t=US[e];if(!t)throw new O(`Unsupported plan "${e}". Supported plans: ${Object.keys(US).join(`, `)}.`,D.USAGE);return t}const GS=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,KS=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,qS=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function JS(e,t){return Rv(await e.console(GS,{input:{modelServiceId:t}}))}async function YS(e,t){return Rv(await e.console(KS,{input:{modelServiceId:t}}))}async function XS(e){let t=[],n=1;for(;;){let r=Rv(await e.console(qS,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function ZS(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}async function QS(e,t,n){return e.requestJson({path:Kg(),method:`POST`,body:t,signal:n})}async function $S(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status),t.modelName&&n.set(`model_name`,t.modelName);let r=Kg(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function eC(e,t,n){return e.requestJson({path:qg(t),method:`GET`,signal:n})}async function tC(e,t,n){return e.requestJson({path:qg(t),method:`DELETE`,signal:n})}const nC=`zeldaEasy.broadscope-platform.customModel.listSupportImportModels`;async function rC(e){let t=Rv(await e.console(nC,{}));return{total:t.total,pageNo:t.pageNo,pageSize:t.pageSize,list:t.list??[]}}function iC(e,t){let n=t.trim().toLowerCase();return e.find(e=>String(e.model??``).toLowerCase()===n)}function aC(e){return e===`lora`?`efficient_sft`:`sft`}const oC=`speech-biasing`;function sC(e,t){return{model:oC,input:{action:e,...t}}}async function cC(e,t,n,r){return e.requestJson({path:wg(),method:`POST`,body:sC(t,n),signal:r})}function lC(e,t,n){return cC(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function uC(e,t={},n){let r={};return t.prefix!==void 0&&(r.prefix=t.prefix),t.pageIndex!==void 0&&(r.page_index=t.pageIndex),t.pageSize!==void 0&&(r.page_size=t.pageSize),cC(e,`list_vocabulary`,r,n)}function dC(e,t,n){return cC(e,`query_vocabulary`,{vocabulary_id:t},n)}function fC(e,t,n,r){return cC(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function pC(e,t,n){return cC(e,`delete_vocabulary`,{vocabulary_id:t},n)}function mC(e,t){try{return JSON.parse(e)}catch(e){throw new rt(`${t} is not valid JSON — ${e.message}`)}}function hC(e){let t=mC(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new rt(`--vocabulary must decode to a JSON object of word→weight.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new rt(`--vocabulary weight for "${e}" must be a number.`);return t}function gC(e,t){let n=`--words`,r=mC(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new rt(`${n} entry #${t} must be an object with string "text" and number "weight".`);let r=e;if(typeof r.text!=`string`||typeof r.weight!=`number`)throw new rt(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new rt(`${n} entry #${t} weight must be a finite number.`);return{text:r.text,weight:r.weight,...typeof r.lang==`string`?{lang:r.lang}:{}}});else if(!r||typeof r!=`object`)throw new rt(`${n} must decode to a JSON object or array.`);else{i=[];for(let[e,a]of Object.entries(r)){if(typeof a!=`number`||!Number.isFinite(a))throw new rt(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new rt(`${n} must contain at least one hot word.`);return i}const _C={introspect:{type:`switch`,description:{"en-US":`Print the machine-readable command schema (JSON) and exit`,"zh-CN":`输出机器可读的命令说明(JSON)并退出`}},output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},vC={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},yC={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},bC={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},xC={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},SC={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function CC(e){return e.auth===`apiKey`?e.optionalConsole?{...bC,...xC}:bC:e.auth===`console`?xC:e.auth===`openapi`?SC:{}}function wC(e){return e}const TC=1;function EC(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function DC(e,t){return`${EC(e||`image`,`image`)}_${EC((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function OC(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return kC(t);if(process.platform===`win32`){let t=process.env.LOCALAPPDATA?.trim();return t?g(t,`hermes`):g(e,`AppData`,`Local`,`hermes`)}return g(e,`.hermes`)}function kC(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const AC=()=>g(f(),`bailian-output`);function jC(e,t){let n=t?.flagDir||e.outputDir||AC(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function MC(e){return e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:`***`}function NC(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function PC(e){return o(e===`-`?0:e,`utf-8`)}async function FC(e,t){let n=[],r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}let a=Array.from({length:Math.min(t,e.length)},()=>i());return await Promise.all(a),n}function IC(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new O(`Invalid ${t} value "${String(e)}". Use true or false.`,D.USAGE)}function LC(e,t=`boolean`){if(e!=null)return IC(e,t)}function RC(e,t,n=`boolean`){let r=LC(e,n);return r===void 0?t:r}function zC(e,t){return LC(e,`watermark`)??t??!0}const BC=/^[a-z0-9][a-z0-9.-]{0,63}$/,VC=/^bailian-[a-z0-9-]{1,64}$/,HC=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function UC(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function WC(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return BC.test(t)?t:`unknown`}function GC(e){let t=UC(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t!==`agent`&&t!==`ai_agent`)return{callerType:`unknown`};let n=UC(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),r=n!==void 0&&VC.test(n)?n:void 0,i=UC(e,`BAILIAN_SKILL_VERSION`),a=r!==void 0&&i!==void 0&&HC.test(i)?i:void 0;return{callerType:`agent`,callerName:WC(UC(e,`BAILIAN_CALLER_NAME`)),...r===void 0?{}:{skillName:r},...a===void 0?{}:{skillVersion:a}}}function KC(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform,callerType:e.caller.callerType};return e.caller.callerType===`agent`&&(t.callerName=e.caller.callerName,e.caller.skillName!==void 0&&(t.skillName=e.caller.skillName),e.caller.skillVersion!==void 0&&(t.skillVersion=e.caller.skillVersion)),e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.exitCode!==void 0&&(t.exitCode=e.error.exitCode),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function qC(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function JC(e){let{command:t,params:n,...r}=e,i={et:`EXP`,ext:r,c1:n,c2:e.success?`success`:`failure`};return e.httpStatus!==void 0&&(i.c3=String(e.httpStatus)),e.errorMessage&&(i.c4=qC(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let YC;function XC(){return YC||(process.env.NODE_ENV===`development`?(YC=`dev`,YC):process.env.BAILIAN_COMPILED===`1`?(YC=`prod`,YC):(YC=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,YC))}var ZC=/* @__PURE__ */ E(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=et(`os`)},function(e,t){e.exports=(...e)=>(process.versions.bun?globalThis.fetch:et(`undici`).fetch)(...e)},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=et(`dns`)},function(e,t){e.exports=et(`util`)},function(e,t){e.exports=et(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},x=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},se=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},pe=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},me=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},he=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},ge=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},_e=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},ve=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map;C.set(`Baiduspider-render`,i),C.set(`Baiduspider+`,i),C.set(`Baiduspider-image+`,i),C.set(`360Spider`,a),C.set(`360Spider-Image`,a),C.set(`bingbot`,o),C.set(`Googlebot`,s),C.set(`YandexRenderResourcesBot`,c),C.set(`spider`,l),C.set(`Dataprovider.com`,u),C.set(`AhrefsBot`,d),C.set(`BitSightBot`,f),C.set(`oBot`,p),C.set(`Cincraw`,m),C.set(`DingTalkBot-LinkService`,h),C.set(`YisouSpider`,g),C.set(`Bytespider`,_),C.set(`ev-crawler`,v),C.set(`bitdiscovery`,y),C.set(`Spider`,b),C.set(`Ai2Bot-Dolma`,x),C.set(`dianjing_ad_spider`,ee),w.set(`Baiduspider-render`,te),w.set(`Baiduspider+`,te),w.set(`Baiduspider-image+`,te),w.set(`360Spider`,ne),w.set(`360Spider-Image`,ne),w.set(`bingbot`,re),w.set(`Googlebot`,ie),w.set(`YandexRenderResourcesBot`,ae),w.set(`spider`,oe),w.set(`Dataprovider.com`,se),w.set(`AhrefsBot`,ce),w.set(`BitSightBot`,le),w.set(`oBot`,ue),w.set(`Cincraw`,de),w.set(`DingTalkBot-LinkService`,fe),w.set(`YisouSpider`,S),w.set(`Bytespider`,pe),w.set(`ev-crawler`,me),w.set(`bitdiscovery`,he),w.set(`Spider`,ge),w.set(`Ai2Bot-Dolma`,_e),w.set(`dianjing_ad_spider`,ve);let ye={productHandlerMap:C,commentHandlerMap:w,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,ye),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=/* @__PURE__ */ new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,"DEFAULT_MODEL_HANDLER_KEY",{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,"createUAInfo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,"runTask",{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:(/* @__PURE__ */ new Date()).getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||(/* @__PURE__ */ new Date()).getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,x=n(5),ee=n.n(x);function te(e){return(te=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function ne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function re(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ne(Object(n),!0).forEach(function(t){ie(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ne(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ie(e,t,n){return(t=(function(e){var t=(function(e,t){if(te(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(te(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return te(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ae(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=se(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
93
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function oe(e,t){return(function(e){if(Array.isArray(e))return e})(e)||(function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}})(e,t)||se(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
94
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function se(e,t){if(e){if(typeof e==`string`)return ce(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ce(e,t):void 0}}function ce(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function le(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=oe(r[n],2),o=(a[0],a[1]);if(o){var s,c=ae(o);try{for(c.s();!(s=c.n()).done;){var l=s.value;if(!1===e.test(l.mac))return l.mac}}catch(e){c.e(e)}finally{c.f()}}}return`00:00:00:00:00:00`}var ue,de,fe=(ue=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:ue,device_id:ee.a.createHash(`md5`).update(le()).digest(`hex`),platform:`node`});function S(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,re(re({},fe),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}S.prototype=((de=function(){}).prototype=b.prototype,new de),S.prototype.constructor=S,S.prototype.send=async function(e,t={}){let n=t.signal;if(n?.aborted)return;let r;if(!process.versions.bun){let{Agent:e,EnvHttpProxyAgent:t}=et(`undici`),i={signal:n,timeout:1e3},a=process.env.HTTP_PROXY?.trim()||void 0,o=process.env.HTTPS_PROXY?.trim()||void 0;r=a||o?new t({httpProxy:a,httpsProxy:o,noProxy:process.env.NO_PROXY?.trim()||void 0,connect:i,requestTls:i,proxyTls:i}):new e({connect:i})}let i=[...this._offlineQueue.splice(0),e];try{await Promise.all(i.map(async e=>{if(!n?.aborted)try{this._print(`send`,e),await(await o()(this._config.endpoint_url,{method:`POST`,keepalive:!0,signal:n,...r?{dispatcher:r}:{},body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})})).body?.cancel().catch(()=>{})}catch{n?.aborted||(this._offlineQueue.length>500&&this._offlineQueue.shift(),this._offlineQueue.push(e))}}))}finally{await r?.destroy().catch(()=>{})}},t.default=S}]).default})),QC=/* @__PURE__ */ E(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=0)})([function(e,t,n){n.r(t);var r=[`ec`,`ea`,`el`,`et`],i=function(e,t){var n=function(e){var n=e.ec,r=e.ea,i=e.el,a=e.et,o=a===void 0?`CLK`:a,s=e.xpath;delete e.ec,delete e.ea,delete e.el,delete e.et,delete e.xpath,e.p1=n,e.p2=r,e.p3=i,e.p4=o,e.p5=s;try{t.log(`event`,e)}catch{}};return function(){var t=arguments,i={};if(t.length!==0){for(var a=0;a<t.length;a++){var o,s,c=t[a];if(a!==0&&typeof c==`object`&&a!==t.length-1)return void(e==null||(o=e.console)==null||(s=o.warn)==null||s.call(o,`Only the last argument can be object type`));if(typeof c==`string`||typeof c==`number`)i[r[a]]=c;else if(typeof c==`object`&&a===t.length-1)for(var l in c)c.hasOwnProperty(l)&&(i[l]=c[l])}n(i)}else{var u,d;(u=e.console)==null||(d=u.warn)==null||d.call(u,`At lease one augument`)}}};t.default=function(e,t){return i(global,e)}}]).default})),$C=/* @__PURE__ */ $e(ZC(),1),ew=/* @__PURE__ */ $e(QC(),1);const tw=()=>g(Ft(),`telemetry.jsonl`);let nw;const rw=/* @__PURE__ */ new Set;let iw;try{let e=new $C.default({pid:`bailian-cli-node`,env:XC()}),t=e.send.bind(e);e.send=function(e){let n=new AbortController,r=setTimeout(()=>n.abort(),1e3);r.unref?.();let i={controller:n,promise:Promise.resolve().then(()=>t(e,{signal:n.signal})).catch(()=>{}).finally(()=>{n.abort(),clearTimeout(r),rw.delete(i)})};return rw.add(i),i.promise},iw=e,nw=e.use(ew.default)}catch{}async function aw(e=1e3){let t;try{if(iw)try{typeof iw._sendAll==`function`&&iw._sendAll()}catch{}if(rw.size===0)return;await Promise.race([Promise.allSettled([...rw].map(e=>e.promise)),new Promise(n=>{t=setTimeout(()=>{for(let e of rw)e.controller.abort();n()},e),t.unref?.()})])}catch{}finally{clearTimeout(t)}}async function ow(e){try{await Rt();let n=tw();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
|
|
95
|
+
`,{mode:384})}catch{}}async function sw(e){try{if(!nw)return;nw(e.command,JC(e))}catch{}}const cw=/* @__PURE__ */ new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),lw=/* @__PURE__ */ new Set(/* @__PURE__ */ `page.pageSize.n.count.model.voice.language.provider.capability.temperature.topP.topK.maxTokens.seed.stream.size.resolution.ratio.duration.format.audioFormat.sampleRate.pitch.rate.volume.api.mode.download.textOnly.promptExtend.enableSsml.watermark.hasThoughts.listTools.rerank.rerankTopN.diarization`.split(`.`));function uw(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||cw.has(n)||lw.has(n)&&r!==void 0&&r!==!1&&(n!==`page`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r);return t}async function dw(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c,l;try{await r()}catch(e){throw a=!1,e instanceof O?(o=e.message,s=e.exitCode,c=e.api?.httpStatus,l=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),u=KC({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},cliVersion:e.identity.version,authMethod:e.authMethod,params:uw(n),caller:e.caller});ow(u).catch(()=>{}),sw(u).catch(()=>{})}}const fw=/* @__PURE__ */ `代码生成.创意写作.客服对话.知识问答.文档理解.数据分析.数学推理.翻译.图像生成.图像编辑.视频生成.视频编辑.语音合成.语音识别.实时对话.Agent编排.深度研究.教育辅导.电商营销.角色扮演.3D生成.向量检索.数字人.音乐生成.人脸人像.虚拟试穿.OCR文字识别.情感分析.意图识别.图像修复.语义重排.播客.有声书`.split(`.`),pw=`You are an intent analyzer for an AI model recommendation system. Given the user's requirement, understand the scenario first, then extract structured information.
|
|
97
96
|
|
|
98
97
|
CRITICAL: Respond with ONLY a valid JSON object. taskSummary must be in English; segments[].step is a short Simplified Chinese label (e.g. "剧本创作", "图生视频").
|
|
99
98
|
|
|
@@ -155,8 +154,8 @@ Pick ONLY the capabilities actually needed (at most 2 for a single task — choo
|
|
|
155
154
|
- 3D-generation: 3D model generation
|
|
156
155
|
|
|
157
156
|
## Scene mapping
|
|
158
|
-
Map the user's need to ONE OR MORE of these ${
|
|
159
|
-
${
|
|
157
|
+
Map the user's need to ONE OR MORE of these ${fw.length} scenes (use exact Chinese labels):
|
|
158
|
+
${fw.join(`, `)}
|
|
160
159
|
|
|
161
160
|
- matchedScenes: array of matched scene labels (max 3, ordered by relevance); [] if none match
|
|
162
161
|
- sceneConfidence: 0.0-1.0 (1.0 = exact match, 0.5 = inferred, 0.0 = no match)
|
|
@@ -200,24 +199,24 @@ Set optimizeDimension ONLY when the user explicitly writes a single-dimension su
|
|
|
200
199
|
"optimizeDimension": null | "price" | "speed" | "context" | "quality" // null unless an explicit superlative appears
|
|
201
200
|
}
|
|
202
201
|
|
|
203
|
-
Output only JSON, no other text.`;var UC=class extends Error{kind;status;code;requestId;stage;constructor(e,t,n={}){super(t,n.cause===void 0?void 0:{cause:n.cause}),this.name=`LLMError`,this.kind=e,this.status=n.status,this.code=n.code,this.requestId=n.requestId,this.stage=n.stage}get fatal(){return this.kind===`rate_limit`||this.kind===`auth`||this.kind===`cancelled`}get tag(){return this.status?`${this.status} ${this.kind}`:this.kind}};function $(e){if(!e?.aborted)return;let t=e.reason;throw new UC(`cancelled`,t instanceof Error?t.message:`执行已取消`,{cause:t})}function WC(e){return e===429?`rate_limit`:e===401||e===403?`auth`:`http`}function GC(e,t,n){return{stage:e,fallback:t,kind:n.kind,status:n.status,message:n.message}}function KC(e){let t=e.status?`${e.status} ${e.kind}`:e.kind;return`${e.fallback} (${t})`}function qC(e,t){return e instanceof UC?(e.stage??=t,e):new UC(`parse`,e instanceof Error?e.message:String(e),{stage:t,cause:e})}const JC=[`unconstrained`,`scoped`,`comparison`,`alternative`],YC=/* @__PURE__ */ new Set([`Text`,`Image`,`Video`,`Audio`]),XC=new Set(VC),ZC=/* @__PURE__ */ new Set([`price`,`speed`,`context`,`quality`]),QC=/* @__PURE__ */ new Set([`one`,`few`,`many`]);function $C(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function ew(e){return $C(e).filter(e=>YC.has(e))}function tw(e){if(!e||typeof e!=`object`)return;let t=e,n=typeof t.mode==`string`&&JC.includes(t.mode)?t.mode:`unconstrained`,r=$C(t.targets),i=$C(t.excludes);return{mode:n,targets:r.length>0?r:void 0,excludes:i.length>0?i:void 0}}async function nw(e,t,n){let r;try{r=await e.chatJson([{role:`system`,content:HC},{role:`user`,content:t}],{stage:`intent`,signal:n})}catch(e){throw qC(e,`intent`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new UC(`parse`,`Intent response is not a JSON object`,{stage:`intent`});let i=$C(r.matchedScenes).filter(e=>XC.has(e)),a=typeof r.sceneConfidence==`number`&&r.sceneConfidence>=0&&r.sceneConfidence<=1?r.sceneConfidence:i.length>0?.5:0;return{complexity:r.complexity===`pipeline`?`pipeline`:`single`,segments:Array.isArray(r.segments)?r.segments.map(e=>({step:typeof e.step==`string`?e.step:``,scene:typeof e.scene==`string`&&XC.has(e.scene)?e.scene:void 0,inputModality:ew(e.inputModality),outputModality:ew(e.outputModality),requiredCapabilities:$C(e.requiredCapabilities)})):void 0,taskSummary:typeof r.taskSummary==`string`?r.taskSummary:``,scenarioHints:$C(r.scenarioHints),inputModality:ew(r.inputModality),outputModality:ew(r.outputModality),requiredCapabilities:$C(r.requiredCapabilities),requiredFeatures:$C(r.requiredFeatures),budget:r.budget===`low`||r.budget===`high`?r.budget:`medium`,contextNeed:r.contextNeed===`large`||r.contextNeed===`extra-large`?r.contextNeed:`standard`,qualityPreference:r.qualityPreference===`cost-optimized`||r.qualityPreference===`balanced`?r.qualityPreference:`flagship`,confidence:1,modelPreference:tw(r.modelPreference),matchedScenes:i,sceneConfidence:a,cardinalityHint:typeof r.cardinalityHint==`string`&&QC.has(r.cardinalityHint)?r.cardinalityHint:void 0,optimizeDimension:typeof r.optimizeDimension==`string`&&ZC.has(r.optimizeDimension)?r.optimizeDimension:void 0}}function rw(e){return!e.offlineInfo}function iw(e,t,n,r){let i=e.inferenceMetadata?.request_modality??[],a=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&i.length>0&&!t.some(e=>i.includes(e))||n.length>0&&a.length>0&&!n.some(e=>a.includes(e))||r.length>0&&!r.some(t=>e.capabilities.includes(t)))}function aw(e,t){return iw(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function ow(e,t){let n=[...t.matchedScenes,...t.scenarioHints].filter(Boolean);return n.length===0?e:e.filter(e=>{let t=e.profile?.notSuitableFor;return!t?.length||!t.some(e=>n.some(t=>e.includes(t)))})}function sw(e,t,n=5){let r=e.filter(e=>aw(e,t));if(r.length>=n)return r;if(t.requiredCapabilities.length>0){let n=e.filter(e=>t.requiredCapabilities.some(t=>e.capabilities.includes(t)));if(n.length>0)return n}return e}const cw=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`VU`,`IG`,`VG`,`TTS`,`ASR`,`Realtime-ASR`,`Realtime-Text-to-Speech`,`Realtime-Audio-Translate`,`Realtime-Chatting`,`Realtime-Omni`,`Multimodal-Omni`,`ME`,`TR`,`3D-generation`]),lw=/* @__PURE__ */ new Set([`Reasoning`]),uw={TG:[`代码生成`,`创意写作`,`客服对话`,`知识问答`,`文档理解`,`数据分析`,`数学推理`,`翻译`,`Agent编排`,`深度研究`,`教育辅导`,`电商营销`,`角色扮演`,`情感分析`,`意图识别`],VU:[`文档理解`,`OCR文字识别`,`数据分析`],IG:[`图像生成`,`图像编辑`,`图像修复`,`人脸人像`,`虚拟试穿`,`电商营销`],VG:[`视频生成`,`视频编辑`,`数字人`],TTS:[`语音合成`,`有声书`,`播客`,`数字人`],ASR:[`语音识别`],"Realtime-ASR":[`语音识别`,`实时对话`],TR:[`向量检索`,`语义重排`,`知识问答`],ME:[`向量检索`],"3D-generation":[`3D生成`]},dw={IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`},fw=[[/重排|rerank/i,`语义重排`],[/向量|嵌入|embedding|索引/i,`向量检索`],[/翻译|translat/i,`翻译`],[/代码|编程|code/i,`代码生成`],[/剧本|脚本|文案|歌词|故事|小说|创作|写作|script|lyric/i,`创意写作`],[/纪要|摘要|总结|整理|summar/i,`文档理解`],[/问答|回答|答案|answer/i,`知识问答`],[/转写|识别|听写|transcri/i,`语音识别`],[/配音|旁白|朗读|语音合成|voice/i,`语音合成`],[/数字人|口型|lip/i,`数字人`]],pw=/剪辑|合成剪辑|合轨|混音|拼接|加字幕|字幕合成|后期|导出|assembl|edit(ing)? together|mux/i;function mw(e,t){let n=t[0];if(n===`Image`)return`IG`;if(n===`Video`)return`VG`;if(n===`Audio`)return e.includes(`Audio`)&&!e.includes(`Text`)?void 0:`TTS`;if(n===`Text`)return e.includes(`Audio`)?`ASR`:e.includes(`Image`)||e.includes(`Video`)?`VU`:`TG`}function hw(e){return{TG:`文本生成`,VU:`视觉理解`,IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`,TR:`文本检索`,ME:`多模态检索`,"3D-generation":`3D 生成`}[e]??e}function gw(e){let t=[];for(let n of e??[]){let e=n.requiredCapabilities.filter(e=>cw.has(e)),r=e.filter(e=>!lw.has(e)),i=n.step?.trim()??``;if(r.length===0&&pw.test(i))continue;let a=r[0]??mw(n.inputModality,n.outputModality);if(!a)continue;let o=[a,...e.filter(e=>e!==a)],s=i||hw(a);if(t.push({index:t.length+1,label:s,inputModality:n.inputModality,outputModality:n.outputModality,primaryCapability:a,capabilities:o,scene:_w(n.scene,s,a)}),t.length>=5)break}return t.length>=2?t:[]}function _w(e,t,n){let r=e=>(uw[n]??[]).includes(e);if(e&&r(e))return e;for(let[e,n]of fw)if(e.test(t)&&r(n))return n;return dw[n]}function vw(e,t){if(e.scene)return[e.scene];let n=new Set(uw[e.primaryCapability]??[]);return t.matchedScenes.filter(e=>n.has(e))}function yw(e,t){return{...t,complexity:`single`,segments:void 0,inputModality:e.inputModality,outputModality:e.outputModality,requiredCapabilities:[e.primaryCapability],requiredFeatures:e.primaryCapability===`TG`?t.requiredFeatures:[],matchedScenes:vw(e,t)}}const bw=/* @__PURE__ */ new Set([`IG`,`VG`,`TTS`,`Realtime-Text-to-Speech`,`3D-generation`]),xw=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`ASR`,`Realtime-ASR`,`TR`,`ME`]);function Sw(e){let t=!1,n=!1;for(let r of e)bw.has(r)&&(t=!0),xw.has(r)&&(n=!0);return t&&n}function Cw(e){let t=e.modelPreference?.mode;if(t!==`comparison`&&t!==`alternative`){if(e.outputModality.length>0&&e.inputModality.length===0){let t=e.outputModality[0];if(t===`Video`&&e.matchedScenes.length===0)return{question:`你打算从什么素材出发生成视频?`,options:[`纯文字描述(文生视频)`,`已有图片(图生视频)`,`已有视频(视频编辑)`],defaultIfSkip:`纯文字描述(文生视频)`,impact:`text-to-video and image-to-video use completely different models`};if(t===`Audio`&&e.matchedScenes.length===0)return{question:`你需要的是哪类语音能力?`,options:[`文字转语音(TTS)`,`语音转文字(ASR)`,`实时语音对话`],defaultIfSkip:`文字转语音(TTS)`,impact:`TTS and ASR are completely different models`}}if(e.complexity!==`pipeline`&&e.requiredCapabilities.length>=3&&Sw(e.requiredCapabilities))return{question:`你的核心需求是哪一类?`,options:e.requiredCapabilities.slice(0,4),defaultIfSkip:e.requiredCapabilities[0],impact:`different capabilities map to completely different model pools`}}}function ww(e,t){let n=e.modelPreference?.mode;if(n===`comparison`||n===`alternative`||n===`scoped`||e.matchedScenes.length>0&&e.sceneConfidence>=.5||e.complexity===`pipeline`)return;let r=t.filter(t=>aw(t,e));if(e.matchedScenes.length===0&&e.sceneConfidence<.5){let e=/* @__PURE__ */ new Map;for(let t of r)for(let n of t.profile?.scenes??[])e.set(n,(e.get(n)??0)+1);let t=[...e.entries()].sort((e,t)=>t[1]-e[1]).slice(0,3).map(([e])=>e);return t.length===0?void 0:{question:`你想用在什么场景?`,options:t,defaultIfSkip:t[0],impact:`不同场景对应完全不同的模型池`}}if(r.length<=20)return;let i=/* @__PURE__ */ new Map;for(let e of r)for(let t of e.profile?.scenes??[])i.set(t,(i.get(t)??0)+1);let a=[...i.entries()].sort((e,t)=>t[1]-e[1]);if(a.length===0||a[0][1]/r.length>=.5)return;let o=a.slice(0,3).map(([e])=>e);return{question:`你的需求更接近哪个场景?`,options:o,defaultIfSkip:o[0],impact:`different scenes produce completely different recommendations`}}function Tw(e){let t=e.modelPreference;return!t||t.mode===`unconstrained`?`none`:t.mode===`comparison`?`existing`:t.mode===`alternative`?`reference`:`scope`}function Ew(e){return e.modelPreference?.mode===`comparison`?(e.modelPreference?.targets?.length??0)<=1?`evaluate`:`differentiate`:e.optimizeDimension?`optimize`:`match`}function Dw(e){return e.cardinalityHint??`few`}function Ow(e,t,n){return t===`differentiate`?`compare`:t===`evaluate`?`validate`:n===`many`?`catalog`:`recommend`}function kw(e){return e.matchedScenes.length===0&&e.sceneConfidence<.5&&e.confidence>0}const Aw=[{name:`forced-compare`,match:e=>e.anchor===`existing`,plan:{recall:`forced`,score:`none`,rank:`forced-order`,explain:`llm-compare`,fairness:!1,topN:3}},{name:`forced-alternative`,match:e=>e.anchor===`reference`,plan:{recall:`forced`,score:`formula`,rank:`score-sort`,explain:`llm-compare`,fairness:!1,topN:3}},{name:`pipeline-steps`,match:e=>e.pipeline&&e.steps>=2,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:2,stepwise:!0}},{name:`template-fast`,match:e=>e.sceneHit&&e.userIntent===`match`&&!e.pipeline,plan:{recall:`template`,score:`none`,rank:`template-order`,explain:`template-text`,fairness:!0,topN:3}},{name:`holistic-complex`,match:e=>e.pipeline||e.fuzzy,plan:{recall:`holistic-pool`,score:`holistic`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}},{name:`catalog-browse`,match:e=>e.cardinality===`many`,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`catalog`,fairness:!0,topN:10}},{name:`optimize-single`,match:e=>e.userIntent===`optimize`&&e.cardinality===`one`,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3}}],jw={name:`structured-normal`,match:()=>!0,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}};function Mw(e){return{recall:`structured`,score:`none`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3,routingReason:`ambiguity-detected`,clarify:e}}function Nw(e,t,n){let r=Cw(e);if(r)return Mw(r);let i=ww(e,t);if(i)return Mw(i);let a=Tw(e),o=Ew(e),s=Dw(e),c=Ow(a,o,s),l={anchor:a,userIntent:o,cardinality:s,output:c,sceneHit:e.matchedScenes.length>0&&e.sceneConfidence>=.8,pipeline:e.complexity===`pipeline`,steps:e.complexity===`pipeline`?gw(e.segments).length:0,fuzzy:kw(e)},u=Aw.find(e=>e.match(l))??jw;return{...u.plan,...n!==void 0&&n>0?{topN:n}:{},routingReason:`${u.name}|${a}/${o}/${s}/${c}`}}const Pw=/-\d{4}-\d{2}-\d{2}$/;function Fw(e){return(e??``).toLowerCase().replace(Pw,``).replace(/[\s_-]+/g,``).trim()}function Iw(e,t){if(Fw(e.model)===t||Fw(e.name)===t)return!0;let n=e.model.lastIndexOf(`/`);return n>=0&&Fw(e.model.slice(n+1))===t}function Lw(e,t){return[e.family,e.familyName].some(e=>{if(!e)return!1;let n=Fw(e);return n.length>0&&(t.includes(n)||n.includes(t))})}function Rw(e,t){if(t.length===0)return[];let n=[],r=/* @__PURE__ */ new Set;for(let i of t){let t=Fw(i);if(!t)continue;let a=e.filter(e=>Iw(e,t));a.length===0&&(a=e.filter(e=>Lw(e,t)));for(let e of a)r.has(e.model)||(r.add(e.model),n.push(e))}return n}function zw(e,t){return t.length===0?e:e.filter(e=>!t.some(t=>{let n=Fw(t);return n.length>0&&(Iw(e,n)||Lw(e,n))}))}function Bw(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}const Vw={flagship:0,balanced:1,lightweight:2},Hw=/* @__PURE__ */ new Set([`qwen`,`qwen-domain-model`,`wan`]);function Uw(e){return Hw.has(e.provider)}function Ww(e){let t=e.model.match(/(\d+(?:\.\d+)?)/);return t?Number.parseFloat(t[1]):-1/0}function Gw(e){let t=e.budget===`low`||e.qualityPreference===`cost-optimized`;return(e,n)=>{let r=Vw[e.profile?.familyTier??``]??1.5,i=Vw[n.profile?.familyTier??``]??1.5,a=t?i-r:r-i;if(a!==0)return a;let o=+!Uw(e),s=+!Uw(n);if(o!==s)return o-s;let c=Bw(e),l=Bw(n),u=!Number.isFinite(c);if(u!==!Number.isFinite(l))return u?1:-1;if(!u){let e=t?c-l:l-c;if(e!==0)return e}return Ww(n)-Ww(e)}}function Kw(e,t){return{model:e,hardScore:t,finalScore:t}}function qw(e,t){let n=e.matchedScenes[0];if(!n)return null;let r=t.filter(e=>e.profile?.scenes?.includes(n));return r.length<3?null:r.sort(Gw(e)).map(e=>Kw(e,1))}function Jw(e,t){let n=sw(t,e),r=e.matchedScenes[0],i=Gw(e),a=[...n].sort((e,t)=>{if(r){let n=+!e.profile?.scenes?.includes(r),i=+!t.profile?.scenes?.includes(r);if(n!==i)return n-i}return i(e,t)}),o=/* @__PURE__ */ new Map;for(let e of a){let t=e.profile?.familyTier??`unknown`,n=o.get(t)??[];n.push(e),o.set(t,n)}let s=[],c=Math.ceil(20/Math.max(o.size,1));for(let[,e]of o)s.push(...e.slice(0,c));if(s.length<20){let e=new Set(s.map(e=>e.model));for(let t of a){if(s.length>=20)break;e.has(t.model)||s.push(t)}}return s.slice(0,20).map(e=>Kw(e,0))}function Yw(e,t,n){let r=Rw(t,e.modelPreference?.targets??[]),i=new Set(r.map(e=>e.model)),a=r.map(e=>Kw(e,1));if(e.modelPreference?.mode===`comparison`)return a;let o=Math.max(0,Math.max(n,5)-a.length);if(o>0){let n=sw(t.filter(e=>!i.has(e.model)),e);for(let t of n.sort(Gw(e)).slice(0,o))a.push(Kw(t,0))}return a}function Xw(e,t){let n=t.filter(t=>aw(t,e));return n.length<5&&(n=t),n.sort(Gw(e)).slice(0,30).map(e=>Kw(e,0))}function Zw(e,t,n,r){let i=n.filter(rw);i=zw(i,t.modelPreference?.excludes??[]);let a;switch(e){case`template`:a=qw(t,i)??Jw(t,i);break;case`forced`:a=Yw(t,i,r);break;case`holistic-pool`:a=Xw(t,i);break;default:a=Jw(t,i)}if(e!==`forced`){let e=new Set(ow(a.map(e=>e.model),t).map(e=>e.model));a=a.filter(t=>e.has(t.model.model))}return a}function Qw(e){let t=(e??``).replace(/```(?:json)?\s*([\s\S]*?)```/gi,`$1`).trim();try{return JSON.parse(t)}catch{}let n=t.indexOf(`{`),r=t.lastIndexOf(`}`);if(n!==-1&&r!==-1&&r>n){let e=t.slice(n,r+1);try{return JSON.parse(e)}catch{}let i=e.replace(/,\s*([}\]])/g,`$1`);try{return JSON.parse(i)}catch{}}throw Error(`Failed to extract valid JSON from LLM response`)}function $w(e,t){return`${e.length?e.join(`/`):`?`} → ${t.length?t.join(`/`):`?`}`}function eT(e){let t=[];e.taskSummary&&t.push(`Task: ${e.taskSummary}`),t.push(`Complexity: ${e.complexity}`);let n=e.complexity===`pipeline`?e.segments??[]:[];n.length>0&&(t.push(`Steps:`),n.forEach((e,n)=>{let r=e.requiredCapabilities.length?` [${e.requiredCapabilities.join(`, `)}]`:``;t.push(` ${n+1}. ${e.step||`step`}: ${$w(e.inputModality,e.outputModality)}${r}`)})),t.push(`Modality: ${$w(e.inputModality,e.outputModality)}`),e.requiredCapabilities.length&&t.push(`Capabilities: ${e.requiredCapabilities.join(`, `)}`),e.requiredFeatures.length&&t.push(`Features: ${e.requiredFeatures.join(`, `)}`),e.matchedScenes.length&&t.push(`Scenes: ${e.matchedScenes.join(`, `)}`),e.scenarioHints.length&&t.push(`Hints: ${e.scenarioHints.join(`, `)}`),t.push(`Budget: ${e.budget}`),t.push(`Quality: ${e.qualityPreference}`),e.contextNeed!==`standard`&&t.push(`Context need: ${e.contextNeed}`);let r=e.modelPreference?.excludes??[];return r.length&&t.push(`Excluded by user: ${r.join(`, `)}`),t.join(`
|
|
204
|
-
`)}const
|
|
205
|
-
`);t.trace.performance.llmCalls++;let i=
|
|
202
|
+
Output only JSON, no other text.`;var mw=class extends Error{kind;status;code;requestId;stage;constructor(e,t,n={}){super(t,n.cause===void 0?void 0:{cause:n.cause}),this.name=`LLMError`,this.kind=e,this.status=n.status,this.code=n.code,this.requestId=n.requestId,this.stage=n.stage}get fatal(){return this.kind===`rate_limit`||this.kind===`auth`||this.kind===`cancelled`}get tag(){return this.status?`${this.status} ${this.kind}`:this.kind}};function $(e){if(!e?.aborted)return;let t=e.reason;throw new mw(`cancelled`,t instanceof Error?t.message:`执行已取消`,{cause:t})}function hw(e){return e===429?`rate_limit`:e===401||e===403?`auth`:`http`}function gw(e,t,n){return{stage:e,fallback:t,kind:n.kind,status:n.status,message:n.message}}function _w(e){let t=e.status?`${e.status} ${e.kind}`:e.kind;return`${e.fallback} (${t})`}function vw(e,t){return e instanceof mw?(e.stage??=t,e):new mw(`parse`,e instanceof Error?e.message:String(e),{stage:t,cause:e})}const yw=[`unconstrained`,`scoped`,`comparison`,`alternative`],bw=/* @__PURE__ */ new Set([`Text`,`Image`,`Video`,`Audio`]),xw=new Set(fw),Sw=/* @__PURE__ */ new Set([`price`,`speed`,`context`,`quality`]),Cw=/* @__PURE__ */ new Set([`one`,`few`,`many`]);function ww(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Tw(e){return ww(e).filter(e=>bw.has(e))}function Ew(e){if(!e||typeof e!=`object`)return;let t=e,n=typeof t.mode==`string`&&yw.includes(t.mode)?t.mode:`unconstrained`,r=ww(t.targets),i=ww(t.excludes);return{mode:n,targets:r.length>0?r:void 0,excludes:i.length>0?i:void 0}}async function Dw(e,t,n){let r;try{r=await e.chatJson([{role:`system`,content:pw},{role:`user`,content:t}],{stage:`intent`,signal:n})}catch(e){throw vw(e,`intent`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new mw(`parse`,`Intent response is not a JSON object`,{stage:`intent`});let i=ww(r.matchedScenes).filter(e=>xw.has(e)),a=typeof r.sceneConfidence==`number`&&r.sceneConfidence>=0&&r.sceneConfidence<=1?r.sceneConfidence:i.length>0?.5:0;return{complexity:r.complexity===`pipeline`?`pipeline`:`single`,segments:Array.isArray(r.segments)?r.segments.map(e=>({step:typeof e.step==`string`?e.step:``,scene:typeof e.scene==`string`&&xw.has(e.scene)?e.scene:void 0,inputModality:Tw(e.inputModality),outputModality:Tw(e.outputModality),requiredCapabilities:ww(e.requiredCapabilities)})):void 0,taskSummary:typeof r.taskSummary==`string`?r.taskSummary:``,scenarioHints:ww(r.scenarioHints),inputModality:Tw(r.inputModality),outputModality:Tw(r.outputModality),requiredCapabilities:ww(r.requiredCapabilities),requiredFeatures:ww(r.requiredFeatures),budget:r.budget===`low`||r.budget===`high`?r.budget:`medium`,contextNeed:r.contextNeed===`large`||r.contextNeed===`extra-large`?r.contextNeed:`standard`,qualityPreference:r.qualityPreference===`cost-optimized`||r.qualityPreference===`balanced`?r.qualityPreference:`flagship`,confidence:1,modelPreference:Ew(r.modelPreference),matchedScenes:i,sceneConfidence:a,cardinalityHint:typeof r.cardinalityHint==`string`&&Cw.has(r.cardinalityHint)?r.cardinalityHint:void 0,optimizeDimension:typeof r.optimizeDimension==`string`&&Sw.has(r.optimizeDimension)?r.optimizeDimension:void 0}}function Ow(e){return!e.offlineInfo}function kw(e,t,n,r){let i=e.inferenceMetadata?.request_modality??[],a=e.inferenceMetadata?.response_modality??[];return!(t.length>0&&i.length>0&&!t.some(e=>i.includes(e))||n.length>0&&a.length>0&&!n.some(e=>a.includes(e))||r.length>0&&!r.some(t=>e.capabilities.includes(t)))}function Aw(e,t){return kw(e,t.inputModality,t.outputModality,t.requiredCapabilities)}function jw(e,t){let n=[...t.matchedScenes,...t.scenarioHints].filter(Boolean);return n.length===0?e:e.filter(e=>{let t=e.profile?.notSuitableFor;return!t?.length||!t.some(e=>n.some(t=>e.includes(t)))})}function Mw(e,t,n=5){let r=e.filter(e=>Aw(e,t));if(r.length>=n)return r;if(t.requiredCapabilities.length>0){let n=e.filter(e=>t.requiredCapabilities.some(t=>e.capabilities.includes(t)));if(n.length>0)return n}return e}const Nw=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`VU`,`IG`,`VG`,`TTS`,`ASR`,`Realtime-ASR`,`Realtime-Text-to-Speech`,`Realtime-Audio-Translate`,`Realtime-Chatting`,`Realtime-Omni`,`Multimodal-Omni`,`ME`,`TR`,`3D-generation`]),Pw=/* @__PURE__ */ new Set([`Reasoning`]),Fw={TG:[`代码生成`,`创意写作`,`客服对话`,`知识问答`,`文档理解`,`数据分析`,`数学推理`,`翻译`,`Agent编排`,`深度研究`,`教育辅导`,`电商营销`,`角色扮演`,`情感分析`,`意图识别`],VU:[`文档理解`,`OCR文字识别`,`数据分析`],IG:[`图像生成`,`图像编辑`,`图像修复`,`人脸人像`,`虚拟试穿`,`电商营销`],VG:[`视频生成`,`视频编辑`,`数字人`],TTS:[`语音合成`,`有声书`,`播客`,`数字人`],ASR:[`语音识别`],"Realtime-ASR":[`语音识别`,`实时对话`],TR:[`向量检索`,`语义重排`,`知识问答`],ME:[`向量检索`],"3D-generation":[`3D生成`]},Iw={IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`},Lw=[[/重排|rerank/i,`语义重排`],[/向量|嵌入|embedding|索引/i,`向量检索`],[/翻译|translat/i,`翻译`],[/代码|编程|code/i,`代码生成`],[/剧本|脚本|文案|歌词|故事|小说|创作|写作|script|lyric/i,`创意写作`],[/纪要|摘要|总结|整理|summar/i,`文档理解`],[/问答|回答|答案|answer/i,`知识问答`],[/转写|识别|听写|transcri/i,`语音识别`],[/配音|旁白|朗读|语音合成|voice/i,`语音合成`],[/数字人|口型|lip/i,`数字人`]],Rw=/剪辑|合成剪辑|合轨|混音|拼接|加字幕|字幕合成|后期|导出|assembl|edit(ing)? together|mux/i;function zw(e,t){let n=t[0];if(n===`Image`)return`IG`;if(n===`Video`)return`VG`;if(n===`Audio`)return e.includes(`Audio`)&&!e.includes(`Text`)?void 0:`TTS`;if(n===`Text`)return e.includes(`Audio`)?`ASR`:e.includes(`Image`)||e.includes(`Video`)?`VU`:`TG`}function Bw(e){return{TG:`文本生成`,VU:`视觉理解`,IG:`图像生成`,VG:`视频生成`,TTS:`语音合成`,ASR:`语音识别`,TR:`文本检索`,ME:`多模态检索`,"3D-generation":`3D 生成`}[e]??e}function Vw(e){let t=[];for(let n of e??[]){let e=n.requiredCapabilities.filter(e=>Nw.has(e)),r=e.filter(e=>!Pw.has(e)),i=n.step?.trim()??``;if(r.length===0&&Rw.test(i))continue;let a=r[0]??zw(n.inputModality,n.outputModality);if(!a)continue;let o=[a,...e.filter(e=>e!==a)],s=i||Bw(a);if(t.push({index:t.length+1,label:s,inputModality:n.inputModality,outputModality:n.outputModality,primaryCapability:a,capabilities:o,scene:Hw(n.scene,s,a)}),t.length>=5)break}return t.length>=2?t:[]}function Hw(e,t,n){let r=e=>(Fw[n]??[]).includes(e);if(e&&r(e))return e;for(let[e,n]of Lw)if(e.test(t)&&r(n))return n;return Iw[n]}function Uw(e,t){if(e.scene)return[e.scene];let n=new Set(Fw[e.primaryCapability]??[]);return t.matchedScenes.filter(e=>n.has(e))}function Ww(e,t){return{...t,complexity:`single`,segments:void 0,inputModality:e.inputModality,outputModality:e.outputModality,requiredCapabilities:[e.primaryCapability],requiredFeatures:e.primaryCapability===`TG`?t.requiredFeatures:[],matchedScenes:Uw(e,t)}}const Gw=/* @__PURE__ */ new Set([`IG`,`VG`,`TTS`,`Realtime-Text-to-Speech`,`3D-generation`]),Kw=/* @__PURE__ */ new Set([`TG`,`Reasoning`,`ASR`,`Realtime-ASR`,`TR`,`ME`]);function qw(e){let t=!1,n=!1;for(let r of e)Gw.has(r)&&(t=!0),Kw.has(r)&&(n=!0);return t&&n}function Jw(e){let t=e.modelPreference?.mode;if(t!==`comparison`&&t!==`alternative`){if(e.outputModality.length>0&&e.inputModality.length===0){let t=e.outputModality[0];if(t===`Video`&&e.matchedScenes.length===0)return{question:`你打算从什么素材出发生成视频?`,options:[`纯文字描述(文生视频)`,`已有图片(图生视频)`,`已有视频(视频编辑)`],defaultIfSkip:`纯文字描述(文生视频)`,impact:`text-to-video and image-to-video use completely different models`};if(t===`Audio`&&e.matchedScenes.length===0)return{question:`你需要的是哪类语音能力?`,options:[`文字转语音(TTS)`,`语音转文字(ASR)`,`实时语音对话`],defaultIfSkip:`文字转语音(TTS)`,impact:`TTS and ASR are completely different models`}}if(e.complexity!==`pipeline`&&e.requiredCapabilities.length>=3&&qw(e.requiredCapabilities))return{question:`你的核心需求是哪一类?`,options:e.requiredCapabilities.slice(0,4),defaultIfSkip:e.requiredCapabilities[0],impact:`different capabilities map to completely different model pools`}}}function Yw(e,t){let n=e.modelPreference?.mode;if(n===`comparison`||n===`alternative`||n===`scoped`||e.matchedScenes.length>0&&e.sceneConfidence>=.5||e.complexity===`pipeline`)return;let r=t.filter(t=>Aw(t,e));if(e.matchedScenes.length===0&&e.sceneConfidence<.5){let e=/* @__PURE__ */ new Map;for(let t of r)for(let n of t.profile?.scenes??[])e.set(n,(e.get(n)??0)+1);let t=[...e.entries()].sort((e,t)=>t[1]-e[1]).slice(0,3).map(([e])=>e);return t.length===0?void 0:{question:`你想用在什么场景?`,options:t,defaultIfSkip:t[0],impact:`不同场景对应完全不同的模型池`}}if(r.length<=20)return;let i=/* @__PURE__ */ new Map;for(let e of r)for(let t of e.profile?.scenes??[])i.set(t,(i.get(t)??0)+1);let a=[...i.entries()].sort((e,t)=>t[1]-e[1]);if(a.length===0||a[0][1]/r.length>=.5)return;let o=a.slice(0,3).map(([e])=>e);return{question:`你的需求更接近哪个场景?`,options:o,defaultIfSkip:o[0],impact:`different scenes produce completely different recommendations`}}function Xw(e){let t=e.modelPreference;return!t||t.mode===`unconstrained`?`none`:t.mode===`comparison`?`existing`:t.mode===`alternative`?`reference`:`scope`}function Zw(e){return e.modelPreference?.mode===`comparison`?(e.modelPreference?.targets?.length??0)<=1?`evaluate`:`differentiate`:e.optimizeDimension?`optimize`:`match`}function Qw(e){return e.cardinalityHint??`few`}function $w(e,t,n){return t===`differentiate`?`compare`:t===`evaluate`?`validate`:n===`many`?`catalog`:`recommend`}function eT(e){return e.matchedScenes.length===0&&e.sceneConfidence<.5&&e.confidence>0}const tT=[{name:`forced-compare`,match:e=>e.anchor===`existing`,plan:{recall:`forced`,score:`none`,rank:`forced-order`,explain:`llm-compare`,fairness:!1,topN:3}},{name:`forced-alternative`,match:e=>e.anchor===`reference`,plan:{recall:`forced`,score:`formula`,rank:`score-sort`,explain:`llm-compare`,fairness:!1,topN:3}},{name:`pipeline-steps`,match:e=>e.pipeline&&e.steps>=2,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:2,stepwise:!0}},{name:`template-fast`,match:e=>e.sceneHit&&e.userIntent===`match`&&!e.pipeline,plan:{recall:`template`,score:`none`,rank:`template-order`,explain:`template-text`,fairness:!0,topN:3}},{name:`holistic-complex`,match:e=>e.pipeline||e.fuzzy,plan:{recall:`holistic-pool`,score:`holistic`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}},{name:`catalog-browse`,match:e=>e.cardinality===`many`,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`catalog`,fairness:!0,topN:10}},{name:`optimize-single`,match:e=>e.userIntent===`optimize`&&e.cardinality===`one`,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3}}],nT={name:`structured-normal`,match:()=>!0,plan:{recall:`structured`,score:`formula`,rank:`score-sort`,explain:`llm-generate`,fairness:!0,topN:3}};function rT(e){return{recall:`structured`,score:`none`,rank:`score-sort`,explain:`llm-generate`,fairness:!1,topN:3,routingReason:`ambiguity-detected`,clarify:e}}function iT(e,t,n){let r=Jw(e);if(r)return rT(r);let i=Yw(e,t);if(i)return rT(i);let a=Xw(e),o=Zw(e),s=Qw(e),c=$w(a,o,s),l={anchor:a,userIntent:o,cardinality:s,output:c,sceneHit:e.matchedScenes.length>0&&e.sceneConfidence>=.8,pipeline:e.complexity===`pipeline`,steps:e.complexity===`pipeline`?Vw(e.segments).length:0,fuzzy:eT(e)},u=tT.find(e=>e.match(l))??nT;return{...u.plan,...n!==void 0&&n>0?{topN:n}:{},routingReason:`${u.name}|${a}/${o}/${s}/${c}`}}const aT=/-\d{4}-\d{2}-\d{2}$/;function oT(e){return(e??``).toLowerCase().replace(aT,``).replace(/[\s_-]+/g,``).trim()}function sT(e,t){if(oT(e.model)===t||oT(e.name)===t)return!0;let n=e.model.lastIndexOf(`/`);return n>=0&&oT(e.model.slice(n+1))===t}function cT(e,t){return[e.family,e.familyName].some(e=>{if(!e)return!1;let n=oT(e);return n.length>0&&(t.includes(n)||n.includes(t))})}function lT(e,t){if(t.length===0)return[];let n=[],r=/* @__PURE__ */ new Set;for(let i of t){let t=oT(i);if(!t)continue;let a=e.filter(e=>sT(e,t));a.length===0&&(a=e.filter(e=>cT(e,t)));for(let e of a)r.has(e.model)||(r.add(e.model),n.push(e))}return n}function uT(e,t){return t.length===0?e:e.filter(e=>!t.some(t=>{let n=oT(t);return n.length>0&&(sT(e,n)||cT(e,n))}))}function dT(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}const fT={flagship:0,balanced:1,lightweight:2},pT=/* @__PURE__ */ new Set([`qwen`,`qwen-domain-model`,`wan`]);function mT(e){return pT.has(e.provider)}function hT(e){let t=e.model.match(/(\d+(?:\.\d+)?)/);return t?Number.parseFloat(t[1]):-1/0}function gT(e){let t=e.budget===`low`||e.qualityPreference===`cost-optimized`;return(e,n)=>{let r=fT[e.profile?.familyTier??``]??1.5,i=fT[n.profile?.familyTier??``]??1.5,a=t?i-r:r-i;if(a!==0)return a;let o=+!mT(e),s=+!mT(n);if(o!==s)return o-s;let c=dT(e),l=dT(n),u=!Number.isFinite(c);if(u!==!Number.isFinite(l))return u?1:-1;if(!u){let e=t?c-l:l-c;if(e!==0)return e}return hT(n)-hT(e)}}function _T(e,t){return{model:e,hardScore:t,finalScore:t}}function vT(e,t){let n=e.matchedScenes[0];if(!n)return null;let r=t.filter(e=>e.profile?.scenes?.includes(n));return r.length<3?null:r.sort(gT(e)).map(e=>_T(e,1))}function yT(e,t){let n=Mw(t,e),r=e.matchedScenes[0],i=gT(e),a=[...n].sort((e,t)=>{if(r){let n=+!e.profile?.scenes?.includes(r),i=+!t.profile?.scenes?.includes(r);if(n!==i)return n-i}return i(e,t)}),o=/* @__PURE__ */ new Map;for(let e of a){let t=e.profile?.familyTier??`unknown`,n=o.get(t)??[];n.push(e),o.set(t,n)}let s=[],c=Math.ceil(20/Math.max(o.size,1));for(let[,e]of o)s.push(...e.slice(0,c));if(s.length<20){let e=new Set(s.map(e=>e.model));for(let t of a){if(s.length>=20)break;e.has(t.model)||s.push(t)}}return s.slice(0,20).map(e=>_T(e,0))}function bT(e,t,n){let r=lT(t,e.modelPreference?.targets??[]),i=new Set(r.map(e=>e.model)),a=r.map(e=>_T(e,1));if(e.modelPreference?.mode===`comparison`)return a;let o=Math.max(0,Math.max(n,5)-a.length);if(o>0){let n=Mw(t.filter(e=>!i.has(e.model)),e);for(let t of n.sort(gT(e)).slice(0,o))a.push(_T(t,0))}return a}function xT(e,t){let n=t.filter(t=>Aw(t,e));return n.length<5&&(n=t),n.sort(gT(e)).slice(0,30).map(e=>_T(e,0))}function ST(e,t,n,r){let i=n.filter(Ow);i=uT(i,t.modelPreference?.excludes??[]);let a;switch(e){case`template`:a=vT(t,i)??yT(t,i);break;case`forced`:a=bT(t,i,r);break;case`holistic-pool`:a=xT(t,i);break;default:a=yT(t,i)}if(e!==`forced`){let e=new Set(jw(a.map(e=>e.model),t).map(e=>e.model));a=a.filter(t=>e.has(t.model.model))}return a}function CT(e){let t=(e??``).replace(/```(?:json)?\s*([\s\S]*?)```/gi,`$1`).trim();try{return JSON.parse(t)}catch{}let n=t.indexOf(`{`),r=t.lastIndexOf(`}`);if(n!==-1&&r!==-1&&r>n){let e=t.slice(n,r+1);try{return JSON.parse(e)}catch{}let i=e.replace(/,\s*([}\]])/g,`$1`);try{return JSON.parse(i)}catch{}}throw Error(`Failed to extract valid JSON from LLM response`)}function wT(e,t){return`${e.length?e.join(`/`):`?`} → ${t.length?t.join(`/`):`?`}`}function TT(e){let t=[];e.taskSummary&&t.push(`Task: ${e.taskSummary}`),t.push(`Complexity: ${e.complexity}`);let n=e.complexity===`pipeline`?e.segments??[]:[];n.length>0&&(t.push(`Steps:`),n.forEach((e,n)=>{let r=e.requiredCapabilities.length?` [${e.requiredCapabilities.join(`, `)}]`:``;t.push(` ${n+1}. ${e.step||`step`}: ${wT(e.inputModality,e.outputModality)}${r}`)})),t.push(`Modality: ${wT(e.inputModality,e.outputModality)}`),e.requiredCapabilities.length&&t.push(`Capabilities: ${e.requiredCapabilities.join(`, `)}`),e.requiredFeatures.length&&t.push(`Features: ${e.requiredFeatures.join(`, `)}`),e.matchedScenes.length&&t.push(`Scenes: ${e.matchedScenes.join(`, `)}`),e.scenarioHints.length&&t.push(`Hints: ${e.scenarioHints.join(`, `)}`),t.push(`Budget: ${e.budget}`),t.push(`Quality: ${e.qualityPreference}`),e.contextNeed!==`standard`&&t.push(`Context need: ${e.contextNeed}`);let r=e.modelPreference?.excludes??[];return r.length&&t.push(`Excluded by user: ${r.join(`, `)}`),t.join(`
|
|
203
|
+
`)}const ET={match:{scene:.4,tier:.2,price:.2,context:.2},optimize:{scene:.1,tier:.1,price:.6,context:.2},evaluate:{scene:.5,tier:.2,price:.1,context:.2},differentiate:{scene:.3,tier:.3,price:.2,context:.2}},DT={price:{scene:0,tier:0,price:1,context:0},context:{scene:0,tier:0,price:0,context:1},quality:{scene:.2,tier:.8,price:0,context:0},speed:{scene:.2,tier:0,price:.4,context:.4}};function OT(e,t){return e===`optimize`&&t.optimizeDimension?DT[t.optimizeDimension]??ET.optimize:ET[e]}const kT={standard:0,large:32e3,"extra-large":128e3};function AT(e){let t=e.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:void 0}function jT(e,t){if(t.matchedScenes.length===0)return 1;let n=e.profile?.scenes??[];return+!!t.matchedScenes.some(e=>n.includes(e))}function MT(e,t){let n=e.profile?.familyTier;return n?t.qualityPreference===`flagship`?n===`flagship`?1:.5:t.qualityPreference===`cost-optimized`?n===`lightweight`?1:.5:1:1}function NT(e,t,n){let r=n.map(e=>AT(e.model)).filter(e=>e!==void 0);if(r.length<2)return 1;let i=Math.min(...r),a=Math.max(...r);if(a===i)return 1;let o=AT(e),s=o===void 0?.5:1-(o-i)/(a-i);return t.budget===`low`?s:t.budget===`high`?1-s*.5:.5+s*.5}function PT(e,t){let n=kT[t.contextNeed]??0;if(n===0)return 1;let r=e.contextWindow??0;return r===0||r>=n?1:r/n}function FT(e,t,n){let r=OT(n,t);return e.map(n=>{let i=r.scene*jT(n.model,t)+r.tier*MT(n.model,t)+r.price*NT(n.model,t,e)+r.context*PT(n.model,t);return{...n,hardScore:i,finalScore:i}})}function IT(e){let t=e.model.profile;return[`ID: ${e.model.model}`,t?.oneLinePositioning?`Positioning: ${t.oneLinePositioning}`:``,t?.scenes?.length?`Scenes: ${t.scenes.join(`, `)}`:``,t?.styleKeywords?.length?`Style: ${t.styleKeywords.join(`, `)}`:``,t?.notSuitableFor?.length?`NotSuitableFor: ${t.notSuitableFor.join(`, `)}`:``].filter(Boolean).join(` | `)}async function LT(e,t){let n=t.llm,r=e.map(IT).join(`
|
|
204
|
+
`);t.trace.performance.llmCalls++;let i=CT(await n.chat([{role:`system`,content:`You are a model-fit judge. For each candidate model, rate how well it fits the user's need on a 1-10 scale, considering the FULL user request and the parsed intent against the model's complete profile (positioning, scenes, style, limitations).
|
|
206
205
|
|
|
207
206
|
Rules:
|
|
208
207
|
- Judge holistically; do not decompose into dimensions
|
|
209
208
|
- The parsed intent is the structured reading of the request; use it, but the original request wins if they conflict
|
|
210
209
|
- For a pipeline task (Complexity: pipeline), score each model by how well it serves the step that matches its capability; a model that fits no step must score ≤3
|
|
211
210
|
- A model whose notSuitableFor conflicts with the need must score ≤3
|
|
212
|
-
- Respond with ONLY JSON: {"scores": [{"model": "<id>", "score": <1-10>}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${
|
|
213
|
-
`)}`}],{maxTokens:2048,stage:`explain`,signal:n.signal})),i=new Map((r.items??[]).map(e=>[e.model,e]));return t.map(e=>{let t=i.get(e.model.model);return{model:e.model.model,name:e.model.name,reason:t?.reason??e.model.profile?.oneLinePositioning??``,highlights:t?.highlights??[],confidence:
|
|
211
|
+
- Respond with ONLY JSON: {"scores": [{"model": "<id>", "score": <1-10>}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${TT(t.intent)}\n\nCandidates:\n${r}`}],{maxTokens:2048,stage:`holistic-score`,signal:t.signal})),a=new Map((i.scores??[]).map(e=>[e.model,e.score]));return e.map(e=>{let t=a.get(e.model.model),n=typeof t==`number`&&t>=1&&t<=10?t:5;return{...e,holisticScore:n,finalScore:n/10}})}async function RT(e,t,n,r){switch(e){case`none`:return t;case`holistic`:try{return await LT(t,n)}catch(e){if($(n.signal),vw(e,`holistic-score`).kind===`cancelled`)throw e;return n.trace.degradations.push(gw(`holistic-score`,`holistic-score→formula`,vw(e,`holistic-score`))),FT(t,n.intent,r)}default:return FT(t,n.intent,r)}}function zT(e,t){if(e.length<=1)return e;let n=/* @__PURE__ */ new Map,r=[],i=[];for(let t of e){let e=t.model.family;if(!e){r.push(t);continue}let a=n.get(e)??0;a<2?(r.push(t),n.set(e,a+1)):i.push(t)}let a=[...r,...i],o=a.slice(0,t),s=new Set(o.map(e=>e.model.family).filter(Boolean));if(t>=3&&s.size===1&&a.length>t){let e=o[0].model.family,n=a.findIndex((n,r)=>r>=t&&n.model.family!==e);if(n>=0){let[e]=a.splice(n,1);a.splice(t-1,0,e)}}return a}function BT(e){let t=e.model.prices?.[0]?.price,n=t?Number.parseFloat(t):NaN;return Number.isFinite(n)?n:1/0}function VT(e){return e.model.profile?.familyTier??`unknown`}function HT(e,t){let n=[`primary`,`runner-up`,`exploration`];return e.slice(0,t).map((e,t)=>({...e,rank:t+1,slot:n[Math.min(t,n.length-1)]}))}function UT(e,t,n){if(t<3||e.length<3)return HT(e,t);let r=[],i=/* @__PURE__ */ new Set,a=()=>{for(let t of e){if(r.length>=3)break;i.has(t.model.model)||(r.push(t),i.add(t.model.model))}};if(n.budget===`low`||n.qualityPreference===`cost-optimized`){let n=/* @__PURE__ */ new Map;for(let t of e){let e=VT(t),r=n.get(e)??[];r.push(t),n.set(e,r)}for(let e of[`lightweight`,`balanced`,`flagship`]){let t=n.get(e)?.[0];if(t&&!i.has(t.model.model)&&(r.push(t),i.add(t.model.model)),r.length>=3)break}return a(),HT(r,t)}let o=/* @__PURE__ */ new Set;for(let t of e){if(r.length>=3)break;VT(t)===`flagship`&&(o.has(t.model.provider)||(o.add(t.model.provider),r.push(t),i.add(t.model.model)))}return a(),HT(r,t)}function WT(e,t,n,r,i){let a;switch(e){case`template-order`:case`forced-order`:a=t;break;default:a=[...t].sort((e,t)=>{let n=t.finalScore-e.finalScore;return Math.abs(n)>1e-9?n:BT(e)-BT(t)})}return r&&(a=zT(a,n)),e===`forced-order`?HT(a,n):UT(a,n,i)}const GT={input_token:`输入`,output_token:`输出`,input_token_cache:`缓存输入`,input_token_cache_creation_5m:`缓存写入`,input_token_cache_read:`缓存读取`,input_token_batch:`批量输入`,output_token_batch:`批量输出`,input_token_batch_chat:`批量对话输入`,output_token_batch_chat:`批量对话输出`};function KT(e){let t=[];for(let n of e.prices??[]){if(t.length>=3)break;let e=GT[n.type]??n.type;t.push(`${e} ${n.price} / ${n.unit}`)}return{pricing:t,contextWindow:e.contextWindow,maxInputTokens:e.maxInputTokens,maxOutputTokens:e.maxOutputTokens,features:e.features??[]}}function qT(e){let t=e.model,n=t.profile;return[`ID: ${t.model}`,`Name: ${t.name}`,`Slot: ${e.slot}`,n?.oneLinePositioning?`Positioning: ${n.oneLinePositioning}`:`Description: ${t.description.slice(0,120)}`,n?.scenes?.length?`Scenes: ${n.scenes.join(`, `)}`:``,n?.familyTier?`Tier: ${n.familyTier}`:``,t.contextWindow?`Context: ${t.contextWindow}`:``,t.prices?.length?`Price: ${t.prices[0].price}/${t.prices[0].unit}`:``,n?.notSuitableFor?.length?`NotSuitableFor: ${n.notSuitableFor.join(`, `)}`:``].filter(Boolean).join(` | `)}function JT(e){return e.model.profile?.profileCompleteness===`structured-only`?`low`:e.slot===`exploration`||e.slot===`alternative`?`medium`:`high`}function YT(e){return e.map(e=>{let t=e.model.profile,n=[];return t?.familyTier&&n.push(t.familyTier),e.model.prices?.length&&n.push(`${e.model.prices[0].price}/${e.model.prices[0].unit}`),t?.styleKeywords?.length&&n.push(...t.styleKeywords.slice(0,2)),{model:e.model.model,name:e.model.name,reason:t?.oneLinePositioning??e.model.description.slice(0,80),highlights:n,confidence:JT(e),slot:e.slot,docUrl:e.model.docUrl,specs:KT(e.model)}})}function XT(e){return e.map(e=>({model:e.model.model,name:e.model.name,reason:e.model.profile?.oneLinePositioning??``,highlights:e.model.profile?.familyTier?[e.model.profile.familyTier]:[],confidence:JT(e),slot:e.slot,docUrl:e.model.docUrl,specs:KT(e.model)}))}async function ZT(e,t,n){n.trace.performance.llmCalls++;let r=CT(await n.llm.chat([{role:`system`,content:e},{role:`user`,content:`User request: ${n.input}\n\nIntent:\n${TT(n.intent)}\n\nRanked candidates:\n${t.map(qT).join(`
|
|
212
|
+
`)}`}],{maxTokens:2048,stage:`explain`,signal:n.signal})),i=new Map((r.items??[]).map(e=>[e.model,e]));return t.map(e=>{let t=i.get(e.model.model);return{model:e.model.model,name:e.model.name,reason:t?.reason??e.model.profile?.oneLinePositioning??``,highlights:t?.highlights??[],confidence:JT(e),slot:e.slot,docUrl:e.model.docUrl,specs:KT(e.model)}})}async function QT(e,t,n){switch(e){case`template-text`:return YT(t);case`catalog`:return XT(t);case`llm-compare`:try{return await ZT(`You are a model comparison advisor for Alibaba Cloud Model Studio. Analyze the given models against the user's use case comparatively.
|
|
214
213
|
|
|
215
214
|
Rules:
|
|
216
215
|
- reason and highlights MUST be in Simplified Chinese (简体中文)
|
|
217
216
|
- Each reason must be comparative: strengths/weaknesses relative to the other models, and "choose this if ..."
|
|
218
217
|
- highlights emphasize differentiators
|
|
219
218
|
- Respond with ONLY JSON:
|
|
220
|
-
{"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),
|
|
219
|
+
{"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),vw(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(gw(`explain`,`llm-compare→template-text`,vw(e,`explain`))),YT(t)}default:try{return await ZT(`You are a model recommendation advisor for Alibaba Cloud Model Studio. The candidates below are ALREADY ranked — do not reorder them. Write a recommendation reason for each.
|
|
221
220
|
|
|
222
221
|
The candidates occupy distinct quality-tier slots. Write each reason from its slot's perspective:
|
|
223
222
|
- primary (Best Pick): why this model is the best fit for the user's budget and quality preference
|
|
@@ -230,8 +229,8 @@ Rules:
|
|
|
230
229
|
- The three reasons must take distinct angles
|
|
231
230
|
- If the intent is a pipeline (Complexity: pipeline), name the step each model serves (e.g. "用于第3步图生视频")
|
|
232
231
|
- Respond with ONLY JSON:
|
|
233
|
-
{"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),
|
|
234
|
-
`)}function
|
|
232
|
+
{"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}`,t,n)}catch(e){if($(n.signal),vw(e,`explain`).kind===`cancelled`)throw e;return n.trace.degradations.push(gw(`explain`,`llm-generate→template-text`,vw(e,`explain`))),YT(t)}}}function $T(e){let t=e.model,n=t.profile,r=(n?.pipelineRole??[]).map(e=>`${e.from}→${e.to}: ${e.role}`).slice(0,3);return[` - ID: ${t.model}`,`Slot: ${e.slot}`,n?.oneLinePositioning?`Positioning: ${n.oneLinePositioning}`:`Description: ${t.description.slice(0,120)}`,n?.familyTier?`Tier: ${n.familyTier}`:``,t.prices?.length?`Price: ${t.prices[0].price}/${t.prices[0].unit}`:``,r.length?`Roles: ${r.join(`; `)}`:``,n?.notSuitableFor?.length?`NotSuitableFor: ${n.notSuitableFor.slice(0,3).join(`, `)}`:``].filter(Boolean).join(` | `)}function eE({step:e,candidates:t}){let n=`${e.inputModality.join(`/`)||`?`} → ${e.outputModality.join(`/`)||`?`}`;return[`Step ${e.index}: ${e.label} (${n}, ${e.capabilities.join(`+`)})`,...t.map($T)].join(`
|
|
233
|
+
`)}function tE(e){return YT(e.candidates).map(t=>({...t,step:e.step.index}))}async function nE(e,t){if(e.every(e=>e.candidates.length===0))return e.map(()=>[]);let n;try{t.trace.performance.llmCalls++,n=CT(await t.llm.chat([{role:`system`,content:`You are a model recommendation advisor for Alibaba Cloud Model Studio. The user's task is a multi-step pipeline. For EACH step, the candidates are ALREADY selected — do not reorder, add or drop models. Write a recommendation reason for each candidate.
|
|
235
234
|
|
|
236
235
|
Rules:
|
|
237
236
|
- reason and highlights MUST be in Simplified Chinese (简体中文)
|
|
@@ -240,12 +239,12 @@ Rules:
|
|
|
240
239
|
- Each reason at most 80 Chinese characters; be specific to the user's task; no generic praise ("性能强大", "效果好")
|
|
241
240
|
- highlights: 2-3 short phrases
|
|
242
241
|
- Respond with ONLY JSON:
|
|
243
|
-
{"steps":[{"index":1,"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${
|
|
242
|
+
{"steps":[{"index":1,"items":[{"model":"<id>","reason":"...","highlights":["...","..."]}]}]}`},{role:`user`,content:`User request: ${t.input}\n\nParsed intent:\n${TT(t.intent)}\n\nSelected candidates per step:\n${e.map(eE).join(`
|
|
244
243
|
|
|
245
|
-
`)}`}],{maxTokens:2048,stage:`step-explain`,signal:t.signal}))}catch(n){if($(t.signal),qC(n,`explain`).kind===`cancelled`)throw n;return t.trace.degradations.push(GC(`explain`,`step-explain→template-text`,qC(n,`explain`))),e.map(AT)}let r=/* @__PURE__ */ new Map;for(let e of n.steps??[])typeof e.index==`number`&&r.set(e.index,new Map((e.items??[]).map(e=>[e.model,e])));return e.map(e=>{let t=AT(e),n=r.get(e.step.index);return t.map(e=>{let t=n?.get(e.model);return t?.reason?{...e,reason:t.reason,highlights:t.highlights?.length?t.highlights:e.highlights}:e})})}function MT(e){return e.inferenceMetadata?.request_modality??[]}function NT(e){return e.inferenceMetadata?.response_modality??[]}function PT(e,t){return t.length===0||e.length===0||t.some(t=>e.includes(t))}function FT(e,t,n){return e.capabilities.includes(t.primaryCapability)?n===`capability-only`?!0:PT(NT(e),t.outputModality)?n===`relaxed-input`||PT(MT(e),t.inputModality):!1:!1}const IT={向量检索:`语义重排`};function LT(e,t){let n=e.filter(t);return n.length>=2?n:e}function RT(e,t,n){let r=yw(e,t);for(let t of[`strict`,`relaxed-input`,`capability-only`]){let i=n.filter(n=>FT(n,e,t));if(i.length<2)continue;let a=e.scene;if(a){i=LT(i,e=>e.profile?.scenes?.includes(a)??!1);let e=IT[a];e&&(i=LT(i,t=>!(t.profile?.scenes?.includes(e)??!1)))}return i=LT(i,e=>ow([e],r).length>0),{models:i,gate:t}}return{models:n.filter(t=>FT(t,e,`capability-only`)),gate:`capability-only`}}const zT={role:.35,scene:.2,tier:.2,price:.15,extras:.1},BT=/纯文[字本]|无图|仅[用靠]?文字|只有文字|无参考/;function VT(e,t){if(t.inputModality.length>0&&t.inputModality.every(e=>e===`Text`)&&t.outputModality.some(e=>e===`Image`||e===`Video`)&&(e.profile?.notSuitableFor??[]).some(e=>BT.test(e)))return .25;let n=e.profile?.pipelineRole??[];if(n.length===0)return .5;let r=e=>t.outputModality.length===0||t.outputModality.includes(e),i=e=>t.inputModality.length===0||t.inputModality.includes(e);return n.some(e=>i(e.from)&&r(e.to))?1:n.some(e=>r(e.to))?.5:0}function HT(e,t){let n=e.profile?.familyTier;return n?{flagship:{flagship:1,balanced:.6,lightweight:.3},"cost-optimized":{lightweight:1,balanced:.7,flagship:.4},balanced:{balanced:1,flagship:.85,lightweight:.7}}[t.qualityPreference]?.[n]??.7:.7}function UT(e){let t=e.prices?.[0],n=t?.price?Number.parseFloat(t.price):NaN;return Number.isFinite(n)?{value:n,unit:t.unit}:void 0}function WT(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=UT(t);e&&n.set(e.unit,(n.get(e.unit)??0)+1)}let r=[...n.entries()].sort((e,t)=>t[1]-e[1])[0]?.[0],i=e.map(UT).filter(e=>e!==void 0&&e.unit===r).map(e=>e.value),a=Math.min(...i),o=Math.max(...i);return e=>{let n=UT(e);if(!n||n.unit!==r||i.length<2||o===a)return .5;let s=1-(n.value-a)/(o-a);return t.budget===`low`?s:t.budget===`high`?1-s*.5:.5+s*.5}}function GT(e,t,n){let r=t.capabilities.filter(e=>e!==t.primaryCapability),i=r.length+n.length;return i===0?1:(r.filter(t=>e.capabilities.includes(t)).length+n.filter(t=>e.features.includes(t)).length)/i}function KT(e,t,n){let r=yw(t,n),i=vw(t,n),a=WT(e,n);return e.map(e=>{let o=VT(e,t),s=i.length===0||(e.profile?.scenes??[]).some(e=>i.includes(e))?1:.3,c=zT.role*o+zT.scene*s+zT.tier*HT(e,n)+zT.price*a(e)+zT.extras*GT(e,t,r.requiredFeatures);return e.profile?.profileCompleteness===`structured-only`&&(c*=.9),{model:e,score:c,role:o}}).sort((e,t)=>t.score-e.score||(UT(e.model)?.value??1/0)-(UT(t.model)?.value??1/0))}function qT(e){let[t,...n]=e;if(!t)return[];let r=n.filter(e=>e.role>=t.role),i=r.length>0?r:n,a=e=>e.model.profile?.familyTier??`unknown`,o=e=>e.model.family??e.model.provider,s=i.find(e=>a(e)!==a(t))??i.find(e=>o(e)!==o(t))??i[0];return s?[t,s]:[t]}const JT={Text:`文本`,Image:`图片`,Video:`视频`,Audio:`音频`};function YT(e,t){let n=[];for(let r=1;r<e.length;r++){let i=t[r-1],a=t[r];if(!i||!a)continue;let o=NT(i).length?NT(i):e[r-1].outputModality,s=e[r].inputModality.filter(e=>o.includes(e));if(s.length===0)continue;let c=MT(a);if(c.length>0&&!s.some(e=>c.includes(e))){let e=s.map(e=>JT[e]??e).join(`/`);n.push(`第${r}步 ${i.name} 输出${e},但第${r+1}步首选 ${a.name} 不接受${e}输入,衔接时需要转换或换用备选`)}}return n}function XT(e,t){return!t||e.models.length<2||e.gate===`capability-only`?`low`:e.gate===`strict`&&e.models.length>=3&&t.role===1?`high`:`medium`}const ZT=[`low`,`medium`,`high`];function QT(e){return e.reduce((e,t)=>ZT.indexOf(t)<ZT.indexOf(e)?t:e,`high`)}async function $T(e){let t=gw(e.intent.segments),n=zw(e.models.filter(rw),e.intent.modelPreference?.excludes??[]),r=Date.now(),i=t.map(t=>RT(t,e.intent,n));e.trace.performance.recallMs=Date.now()-r;for(let n=0;n<t.length;n++)e.decisionLog?.push(`[step ${n+1} recall] ${t[n].label}: pool=${i[n].models.length} gate=${i[n].gate} scene=${t[n].scene??`-`}`);let a=Date.now(),o=t.map((t,n)=>KT(i[n].models,t,e.intent));e.trace.performance.scoreMs=Date.now()-a;for(let n=0;n<t.length;n++){let r=o[n].slice(0,3).map(e=>`${e.model.model}(${e.score.toFixed(2)},role=${e.role})`).join(`, `);e.decisionLog?.push(`[step ${n+1} score] ${t[n].label}: ${r}`)}let s=Date.now(),c=o.map(t=>qT(t).slice(0,e.topN));e.trace.performance.rankMs=Date.now()-s;for(let n=0;n<t.length;n++)e.decisionLog?.push(`[step ${n+1} pick] ${t[n].label}: ${c[n].map(e=>e.model.model).join(` + `)}`);let l=t.map((e,t)=>({step:e,candidates:c[t].map((e,t)=>({model:e.model,hardScore:e.score,finalScore:e.score,rank:t+1,slot:t===0?`primary`:`alternative`}))})),u=Date.now(),d=await jT(l,e);e.trace.performance.explainMs=Date.now()-u;let f=t.map((e,t)=>({index:e.index,step:e.label,inputModality:e.inputModality,outputModality:e.outputModality,capabilities:e.capabilities,recommendations:d[t],candidatePool:i[t].models.length,confidence:XT(i[t],o[t][0]),gate:i[t].gate}));return{steps:f,warnings:YT(t,c.map(e=>e[0]?.model)),candidatePool:i.reduce((e,t)=>e+t.models.length,0),confidence:QT(f.map(e=>e.confidence))}}function eE(e,t){let{plan:n,intent:r}=e;if(n.recall===`template`&&r.sceneConfidence>=.8)return`high`;if(t.length<5&&n.recall!==`forced`)return`low`;let i=[...t].sort((e,t)=>t.finalScore-e.finalScore);return(i[0]?i[0].finalScore-(i[1]?.finalScore??0):0)>.2&&(i[0]?.finalScore??0)>.6||n.recall===`forced`?`high`:`medium`}function tE(e,t){if(t){process.stderr.write(`[recommend:trace] ${JSON.stringify(e)}\n`);return}let n=[e.failure?`failed at ${e.failure.stage}`:e.routingReason??`?`,`${e.performance.totalMs}ms`,`llm=${e.performance.llmCalls}`];if(e.failure){let{status:t,kind:r}=e.failure;n.push(`error=${t?`${t} ${r}`:r}`)}e.degradations.length&&n.push(`degraded=${e.degradations.map(KC).join(`,`)}`),process.stderr.write(`[recommend] ${n.join(`, `)}\n`)}async function nE(e,t,n){$(t.signal);let r=Date.now(),i={timestamp:(/* @__PURE__ */ new Date()).toISOString(),input:e,performance:{llmCalls:0},degradations:[]},a=await t.catalog();$(t.signal);let o=t.decisionLog??[],s=Date.now(),c;if(n)c=n;else{i.performance.llmCalls++;try{c=await nw(t.llm,e,t.signal),$(t.signal)}catch(e){let n=qC(e,`intent`);throw i.performance.intentMs=Date.now()-s,i.performance.totalMs=Date.now()-r,i.failure={stage:`intent`,kind:n.kind,status:n.status,code:n.code,requestId:n.requestId,message:n.message},tE(i,t.verbose??!1),n}}i.performance.intentMs=Date.now()-s,i.matchedScenes=c.matchedScenes,i.sceneConfidence=c.sceneConfidence,o.push(`[intent] complexity=${c.complexity} scenes=[${c.matchedScenes.join(`,`)}] conf=${c.sceneConfidence} caps=[${c.requiredCapabilities.join(`,`)}] budget=${c.budget} quality=${c.qualityPreference}`);let l=Nw(c,a,t.topN);if(i.routingReason=l.routingReason,o.push(`[route] ${l.routingReason}${l.clarify?` → clarify`:``}`),l.clarify)return i.performance.totalMs=Date.now()-r,tE(i,t.verbose??!1),{type:`need_clarify`,...l.clarify,intent:c};let u={input:e,intent:c,models:a,plan:l,topN:l.topN,llm:t.llm,signal:t.signal,trace:i,decisionLog:o};if(l.stepwise){let e=await $T(u);return $(t.signal),i.performance.totalMs=Date.now()-r,tE(i,t.verbose??!1),{type:`result`,recommendations:e.steps.flatMap(e=>e.recommendations),confidence:e.confidence,routingReason:l.routingReason,candidatePool:e.candidatePool,intent:c,degradations:[...i.degradations],steps:e.steps,warnings:e.warnings}}let d=Ew(c),f=Date.now(),p=Zw(l.recall,c,a,l.topN);i.performance.recallMs=Date.now()-f,o.push(`[recall] strategy=${l.recall} pool=${p.length}`);let m=Date.now(),h=await pT(l.score,p,u,d);$(t.signal),i.performance.scoreMs=Date.now()-m,o.push(`[score] strategy=${l.score} top=${h.slice(0,3).map(e=>`${e.model.model}(${e.finalScore.toFixed(2)})`).join(`, `)}`);let g=Date.now(),_=yT(l.rank,h,l.topN,l.fairness,c);i.performance.rankMs=Date.now()-g,o.push(`[rank] ${_.map(e=>`${e.model.model}/${e.slot}`).join(`, `)}`);let v=Date.now(),y=await DT(l.explain,_,u);return $(t.signal),i.performance.explainMs=Date.now()-v,i.performance.totalMs=Date.now()-r,tE(i,t.verbose??!1),{type:`result`,recommendations:y,confidence:eE(u,h),routingReason:l.routingReason,candidatePool:p.length,intent:c,degradations:[...i.degradations]}}const rE=/* @__PURE__ */ new Set([`bailian-model-recommend`]);function iE(){let e=(process.env.BAILIAN_SKILL_EXCLUDE??``).split(`,`).map(e=>e.trim()).filter(Boolean);return/* @__PURE__ */ new Set([...rE,...e])}function aE(){return process.env.BAILIAN_SKILLS_DIR||w(Nt(),`skills`)}function oE(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=t[1].split(/\r?\n/),r={},i=``,a=!1;for(let e of n){if(a&&/^\s+/.test(e)){r[i]+=(r[i]?` `:``)+e.trim();continue}a=!1;let t=e.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)/);if(!t)continue;let[,n,o]=t;o===`>-`||o===`|`||o===`>`||o===`|-`?(i=n,r[n]=``,a=!0):r[n]=o.trim()}return r}function sE(){let e=aE();if(!x(e))return[];let t=[],n;try{n=_e(e)}catch{return[]}let r=iE();for(let i of n){let n=w(e,i),a=w(n,`SKILL.md`);if(!x(a))continue;let o;try{o=ge(a,`utf-8`)}catch{continue}let s=oE(o),c=s.name||i;if(r.has(i)||r.has(c))continue;let l=s.description||``;l&&t.push({name:c,description:l,basePath:n})}return t}function cE(e){if(e.length===0)return``;let t=[`## Available Skills`,"When the user's request matches a skill's description, call the `use_skill` tool with that skill's name to load its full instructions.",``],n=0;for(let r of e){let e=r.description,i=8e3-n;i<=0?e=`(description truncated)`:e.length>i&&(e=e.slice(0,i)+`…`),n+=e.length,t.push(`- **${r.name}**: ${e}`)}return t.join(`
|
|
246
|
-
`)}const
|
|
247
|
-
`),n=[],i=0;for(let e=0;e<t.length;e++)t[e].toLowerCase().includes(a)&&(i++,n.length<40&&n.push(`${e+1}: ${t[e]}`));return{ok:!0,matches:n,totalMatches:i}}catch(e){return{ok:!1,error:e.message}}}function
|
|
248
|
-
`)}`}const
|
|
244
|
+
`)}`}],{maxTokens:2048,stage:`step-explain`,signal:t.signal}))}catch(n){if($(t.signal),vw(n,`explain`).kind===`cancelled`)throw n;return t.trace.degradations.push(gw(`explain`,`step-explain→template-text`,vw(n,`explain`))),e.map(tE)}let r=/* @__PURE__ */ new Map;for(let e of n.steps??[])typeof e.index==`number`&&r.set(e.index,new Map((e.items??[]).map(e=>[e.model,e])));return e.map(e=>{let t=tE(e),n=r.get(e.step.index);return t.map(e=>{let t=n?.get(e.model);return t?.reason?{...e,reason:t.reason,highlights:t.highlights?.length?t.highlights:e.highlights}:e})})}function rE(e){return e.inferenceMetadata?.request_modality??[]}function iE(e){return e.inferenceMetadata?.response_modality??[]}function aE(e,t){return t.length===0||e.length===0||t.some(t=>e.includes(t))}function oE(e,t,n){return e.capabilities.includes(t.primaryCapability)?n===`capability-only`?!0:aE(iE(e),t.outputModality)?n===`relaxed-input`||aE(rE(e),t.inputModality):!1:!1}const sE={向量检索:`语义重排`};function cE(e,t){let n=e.filter(t);return n.length>=2?n:e}function lE(e,t,n){let r=Ww(e,t);for(let t of[`strict`,`relaxed-input`,`capability-only`]){let i=n.filter(n=>oE(n,e,t));if(i.length<2)continue;let a=e.scene;if(a){i=cE(i,e=>e.profile?.scenes?.includes(a)??!1);let e=sE[a];e&&(i=cE(i,t=>!(t.profile?.scenes?.includes(e)??!1)))}return i=cE(i,e=>jw([e],r).length>0),{models:i,gate:t}}return{models:n.filter(t=>oE(t,e,`capability-only`)),gate:`capability-only`}}const uE={role:.35,scene:.2,tier:.2,price:.15,extras:.1},dE=/纯文[字本]|无图|仅[用靠]?文字|只有文字|无参考/;function fE(e,t){if(t.inputModality.length>0&&t.inputModality.every(e=>e===`Text`)&&t.outputModality.some(e=>e===`Image`||e===`Video`)&&(e.profile?.notSuitableFor??[]).some(e=>dE.test(e)))return .25;let n=e.profile?.pipelineRole??[];if(n.length===0)return .5;let r=e=>t.outputModality.length===0||t.outputModality.includes(e),i=e=>t.inputModality.length===0||t.inputModality.includes(e);return n.some(e=>i(e.from)&&r(e.to))?1:n.some(e=>r(e.to))?.5:0}function pE(e,t){let n=e.profile?.familyTier;return n?{flagship:{flagship:1,balanced:.6,lightweight:.3},"cost-optimized":{lightweight:1,balanced:.7,flagship:.4},balanced:{balanced:1,flagship:.85,lightweight:.7}}[t.qualityPreference]?.[n]??.7:.7}function mE(e){let t=e.prices?.[0],n=t?.price?Number.parseFloat(t.price):NaN;return Number.isFinite(n)?{value:n,unit:t.unit}:void 0}function hE(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=mE(t);e&&n.set(e.unit,(n.get(e.unit)??0)+1)}let r=[...n.entries()].sort((e,t)=>t[1]-e[1])[0]?.[0],i=e.map(mE).filter(e=>e!==void 0&&e.unit===r).map(e=>e.value),a=Math.min(...i),o=Math.max(...i);return e=>{let n=mE(e);if(!n||n.unit!==r||i.length<2||o===a)return .5;let s=1-(n.value-a)/(o-a);return t.budget===`low`?s:t.budget===`high`?1-s*.5:.5+s*.5}}function gE(e,t,n){let r=t.capabilities.filter(e=>e!==t.primaryCapability),i=r.length+n.length;return i===0?1:(r.filter(t=>e.capabilities.includes(t)).length+n.filter(t=>e.features.includes(t)).length)/i}function _E(e,t,n){let r=Ww(t,n),i=Uw(t,n),a=hE(e,n);return e.map(e=>{let o=fE(e,t),s=i.length===0||(e.profile?.scenes??[]).some(e=>i.includes(e))?1:.3,c=uE.role*o+uE.scene*s+uE.tier*pE(e,n)+uE.price*a(e)+uE.extras*gE(e,t,r.requiredFeatures);return e.profile?.profileCompleteness===`structured-only`&&(c*=.9),{model:e,score:c,role:o}}).sort((e,t)=>t.score-e.score||(mE(e.model)?.value??1/0)-(mE(t.model)?.value??1/0))}function vE(e){let[t,...n]=e;if(!t)return[];let r=n.filter(e=>e.role>=t.role),i=r.length>0?r:n,a=e=>e.model.profile?.familyTier??`unknown`,o=e=>e.model.family??e.model.provider,s=i.find(e=>a(e)!==a(t))??i.find(e=>o(e)!==o(t))??i[0];return s?[t,s]:[t]}const yE={Text:`文本`,Image:`图片`,Video:`视频`,Audio:`音频`};function bE(e,t){let n=[];for(let r=1;r<e.length;r++){let i=t[r-1],a=t[r];if(!i||!a)continue;let o=iE(i).length?iE(i):e[r-1].outputModality,s=e[r].inputModality.filter(e=>o.includes(e));if(s.length===0)continue;let c=rE(a);if(c.length>0&&!s.some(e=>c.includes(e))){let e=s.map(e=>yE[e]??e).join(`/`);n.push(`第${r}步 ${i.name} 输出${e},但第${r+1}步首选 ${a.name} 不接受${e}输入,衔接时需要转换或换用备选`)}}return n}function xE(e,t){return!t||e.models.length<2||e.gate===`capability-only`?`low`:e.gate===`strict`&&e.models.length>=3&&t.role===1?`high`:`medium`}const SE=[`low`,`medium`,`high`];function CE(e){return e.reduce((e,t)=>SE.indexOf(t)<SE.indexOf(e)?t:e,`high`)}async function wE(e){let t=Vw(e.intent.segments),n=uT(e.models.filter(Ow),e.intent.modelPreference?.excludes??[]),r=Date.now(),i=t.map(t=>lE(t,e.intent,n));e.trace.performance.recallMs=Date.now()-r;for(let n=0;n<t.length;n++)e.decisionLog?.push(`[step ${n+1} recall] ${t[n].label}: pool=${i[n].models.length} gate=${i[n].gate} scene=${t[n].scene??`-`}`);let a=Date.now(),o=t.map((t,n)=>_E(i[n].models,t,e.intent));e.trace.performance.scoreMs=Date.now()-a;for(let n=0;n<t.length;n++){let r=o[n].slice(0,3).map(e=>`${e.model.model}(${e.score.toFixed(2)},role=${e.role})`).join(`, `);e.decisionLog?.push(`[step ${n+1} score] ${t[n].label}: ${r}`)}let s=Date.now(),c=o.map(t=>vE(t).slice(0,e.topN));e.trace.performance.rankMs=Date.now()-s;for(let n=0;n<t.length;n++)e.decisionLog?.push(`[step ${n+1} pick] ${t[n].label}: ${c[n].map(e=>e.model.model).join(` + `)}`);let l=t.map((e,t)=>({step:e,candidates:c[t].map((e,t)=>({model:e.model,hardScore:e.score,finalScore:e.score,rank:t+1,slot:t===0?`primary`:`alternative`}))})),u=Date.now(),d=await nE(l,e);e.trace.performance.explainMs=Date.now()-u;let f=t.map((e,t)=>({index:e.index,step:e.label,inputModality:e.inputModality,outputModality:e.outputModality,capabilities:e.capabilities,recommendations:d[t],candidatePool:i[t].models.length,confidence:xE(i[t],o[t][0]),gate:i[t].gate}));return{steps:f,warnings:bE(t,c.map(e=>e[0]?.model)),candidatePool:i.reduce((e,t)=>e+t.models.length,0),confidence:CE(f.map(e=>e.confidence))}}function TE(e,t){let{plan:n,intent:r}=e;if(n.recall===`template`&&r.sceneConfidence>=.8)return`high`;if(t.length<5&&n.recall!==`forced`)return`low`;let i=[...t].sort((e,t)=>t.finalScore-e.finalScore);return(i[0]?i[0].finalScore-(i[1]?.finalScore??0):0)>.2&&(i[0]?.finalScore??0)>.6||n.recall===`forced`?`high`:`medium`}async function EE(e,t,n){$(t.signal);let r=Date.now(),i={timestamp:(/* @__PURE__ */ new Date()).toISOString(),input:e,performance:{llmCalls:0},degradations:[]},a=await t.catalog();$(t.signal);let o=t.decisionLog??[],s=Date.now(),c;if(n)c=n;else{i.performance.llmCalls++;try{c=await Dw(t.llm,e,t.signal),$(t.signal)}catch(e){let n=vw(e,`intent`);throw i.performance.intentMs=Date.now()-s,i.performance.totalMs=Date.now()-r,i.failure={stage:`intent`,kind:n.kind,status:n.status,code:n.code,requestId:n.requestId,message:n.message},t.onTrace?.(i),n}}i.performance.intentMs=Date.now()-s,i.matchedScenes=c.matchedScenes,i.sceneConfidence=c.sceneConfidence,o.push(`[intent] complexity=${c.complexity} scenes=[${c.matchedScenes.join(`,`)}] conf=${c.sceneConfidence} caps=[${c.requiredCapabilities.join(`,`)}] budget=${c.budget} quality=${c.qualityPreference}`);let l=iT(c,a,t.topN);if(i.routingReason=l.routingReason,o.push(`[route] ${l.routingReason}${l.clarify?` → clarify`:``}`),l.clarify)return i.performance.totalMs=Date.now()-r,t.onTrace?.(i),{type:`need_clarify`,...l.clarify,intent:c};let u={input:e,intent:c,models:a,plan:l,topN:l.topN,llm:t.llm,signal:t.signal,trace:i,decisionLog:o};if(l.stepwise){let e=await wE(u);return $(t.signal),i.performance.totalMs=Date.now()-r,t.onTrace?.(i),{type:`result`,recommendations:e.steps.flatMap(e=>e.recommendations),confidence:e.confidence,routingReason:l.routingReason,candidatePool:e.candidatePool,intent:c,degradations:[...i.degradations],steps:e.steps,warnings:e.warnings}}let d=Zw(c),f=Date.now(),p=ST(l.recall,c,a,l.topN);i.performance.recallMs=Date.now()-f,o.push(`[recall] strategy=${l.recall} pool=${p.length}`);let m=Date.now(),h=await RT(l.score,p,u,d);$(t.signal),i.performance.scoreMs=Date.now()-m,o.push(`[score] strategy=${l.score} top=${h.slice(0,3).map(e=>`${e.model.model}(${e.finalScore.toFixed(2)})`).join(`, `)}`);let g=Date.now(),_=WT(l.rank,h,l.topN,l.fairness,c);i.performance.rankMs=Date.now()-g,o.push(`[rank] ${_.map(e=>`${e.model.model}/${e.slot}`).join(`, `)}`);let v=Date.now(),y=await QT(l.explain,_,u);return $(t.signal),i.performance.explainMs=Date.now()-v,i.performance.totalMs=Date.now()-r,t.onTrace?.(i),{type:`result`,recommendations:y,confidence:TE(u,h),routingReason:l.routingReason,candidatePool:p.length,intent:c,degradations:[...i.degradations]}}const DE=/* @__PURE__ */ new Set([`bailian-model-recommend`]);function OE(){let e=(process.env.BAILIAN_SKILL_EXCLUDE??``).split(`,`).map(e=>e.trim()).filter(Boolean);return/* @__PURE__ */ new Set([...DE,...e])}function kE(){return process.env.BAILIAN_SKILLS_DIR||T(Ft(),`skills`)}function AE(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=t[1].split(/\r?\n/),r={},i=``,a=!1;for(let e of n){if(a&&/^\s+/.test(e)){r[i]+=(r[i]?` `:``)+e.trim();continue}a=!1;let t=e.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)/);if(!t)continue;let[,n,o]=t;o===`>-`||o===`|`||o===`>`||o===`|-`?(i=n,r[n]=``,a=!0):r[n]=o.trim()}return r}function jE(){let e=kE();if(!S(e))return[];let t=[],n;try{n=ge(e)}catch{return[]}let r=OE();for(let i of n){let n=T(e,i),a=T(n,`SKILL.md`);if(!S(a))continue;let o;try{o=he(a,`utf-8`)}catch{continue}let s=AE(o),c=s.name||i;if(r.has(i)||r.has(c))continue;let l=s.description||``;l&&t.push({name:c,description:l,basePath:n})}return t}function ME(e){if(e.length===0)return``;let t=[`## Available Skills`,"When the user's request matches a skill's description, call the `use_skill` tool with that skill's name to load its full instructions.",``],n=0;for(let r of e){let e=r.description,i=8e3-n;i<=0?e=`(description truncated)`:e.length>i&&(e=e.slice(0,i)+`…`),n+=e.length,t.push(`- **${r.name}**: ${e}`)}return t.join(`
|
|
245
|
+
`)}const NE=65536;function PE(e,t){let n=FE(kE());if(!n)return{error:`skills directory not found`};let r=t?FE(t)??n:n,i=Oe(r,e);if(!IE(i,n))return{error:`path escapes the skills sandbox: ${e}`};let a=FE(i);return a&&!IE(a,n)?{error:`symlink escapes the skills sandbox: ${e}`}:{resolved:i}}function FE(e){try{return ve(e)}catch{return}}function IE(e,t){return e===t||e.startsWith(t+ke)}function LE(e,t,n){let{resolved:r,error:i}=PE(e,n);if(i||!r)return{ok:!1,error:i??`resolve failed`};let a=t.toLowerCase();try{let e=ye(r);if(!e.isFile())return{ok:!1,error:`not a regular file`};if(e.size>4194304)return{ok:!1,error:`file too large to search (${e.size} bytes)`};let t=he(r,`utf-8`).split(`
|
|
246
|
+
`),n=[],i=0;for(let e=0;e<t.length;e++)t[e].toLowerCase().includes(a)&&(i++,n.length<40&&n.push(`${e+1}: ${t[e]}`));return{ok:!0,matches:n,totalMatches:i}}catch(e){return{ok:!1,error:e.message}}}function RE(e,t){let{resolved:n,error:r}=PE(e,t);if(r||!n)return{ok:!1,error:r??`resolve failed`};try{if(!ye(n).isFile())return{ok:!1,error:`not a regular file`};let e=he(n),t=e.length>NE;return{ok:!0,content:e.subarray(0,NE).toString(`utf-8`),truncated:t}}catch(e){return{ok:!1,error:e.message}}}function zE(e){return{originalInput:e,clarifications:[]}}function BE(e){if(e.clarifications.length===0)return e.originalInput;let t=e.clarifications.map(e=>`- ${e.question} → ${e.answer}`);return`${e.originalInput}\n\n补充说明:\n${t.join(`
|
|
247
|
+
`)}`}const VE=[{type:`function`,function:{name:`recommend`,description:`Recommend models for the user's request. Takes no arguments: the system automatically passes the user's original request plus every answer collected via ask_user. Returns top-N recommendations + decision signals (confidence/candidatePool), or need_clarify (user clarification required). Also covers comparison/alternative requests.`,parameters:{type:`object`,properties:{}}}},{type:`function`,function:{name:`use_skill`,description:`Load a skill's full instructions (SKILL.md) by name. Use this when the user's request matches a skill in the Available Skills list — e.g. asking about a specific model's usage, API parameters, calling examples, pricing details, or any documentation lookup. Returns the skill's instructions and its base path; then follow those instructions using read_file.`,parameters:{type:`object`,properties:{skill:{type:`string`,description:`The skill name from the Available Skills list`}},required:[`skill`]}}},{type:`function`,function:{name:`search_files`,description:`Search a file inside the loaded skill for a keyword (case-insensitive substring) and return the matching lines. PREFERRED over read_file for large data files like models.jsonl or families.jsonl — those are truncated when read whole, but search scans the full file. Example: search_files(path='models/models.jsonl', pattern='qwen-image').`,parameters:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the skill's base path`},pattern:{type:`string`,description:`Keyword to search for (case-insensitive substring)`}},required:[`path`,`pattern`]}}},{type:`function`,function:{name:`read_file`,description:`Read a file inside the loaded skill's directory (or the skills root). Use relative paths as instructed by the skill's SKILL.md (e.g. 'models/models.jsonl', 'wiki/index.md'). Only use after loading a skill via use_skill.`,parameters:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the skill's base path`}},required:[`path`]}}},{type:`function`,function:{name:`ask_user`,description:`Ask the user a multiple-choice question to resolve ambiguity. Only use when different choices lead to completely different recommendations; max 2 rounds.`,parameters:{type:`object`,properties:{question:{type:`string`},options:{type:`array`,items:{type:`string`},maxItems:4},default_if_skip:{type:`string`}},required:[`question`,`options`,`default_if_skip`]}}}];async function HE(e,t,n){$(t.signal);let r;try{if(r=e.function.arguments.trim()?JSON.parse(e.function.arguments):{},!r||typeof r!=`object`||Array.isArray(r))throw Error(`参数必须是对象`)}catch{return{result:JSON.stringify({error:`invalid tool arguments`})}}switch(e.function.name){case`recommend`:{t.onProgress?.(`running recommendation engine`);let e=await EE(BE(n),t);if(e.type===`need_clarify`)return{recommendResult:e,result:JSON.stringify({type:`need_clarify`,question:e.question,options:e.options,default_if_skip:e.defaultIfSkip,impact:e.impact})};let r=e=>({model:e.model,name:e.name,reason:e.reason,highlights:e.highlights,slot:e.slot}),i=e.steps?{steps:e.steps.map(e=>({index:e.index,step:e.step,io:`${e.inputModality.join(`/`)} → ${e.outputModality.join(`/`)}`,confidence:e.confidence,recommendations:e.recommendations.map(r)})),warnings:e.warnings?.length?e.warnings:void 0}:{recommendations:e.recommendations.map(r)};return{result:JSON.stringify({type:`result`,confidence:e.confidence,routingReason:e.routingReason,candidatePool:e.candidatePool,...i}),recommendResult:e}}case`use_skill`:{let e=typeof r.skill==`string`?r.skill.trim():``;if(!e)return{result:JSON.stringify({error:`missing skill name`})};let i=jE(),a=i.find(t=>t.name===e);if(!a){let t=i.map(e=>e.name);return{result:JSON.stringify({error:`Skill "${e}" not found. Available skills: ${t.join(`, `)||`(none)`}`})}}t.onProgress?.(`matched skill "${a.name}"`);let o;try{o=he(T(a.basePath,`SKILL.md`),`utf-8`)}catch(e){return{result:JSON.stringify({error:`Failed to read SKILL.md: ${e.message}`})}}return n.activeSkill=a,t.onProgress?.(`loaded skill "${a.name}" (SKILL.md, ${o.length} chars)`),{result:JSON.stringify({type:`skill_loaded`,skill:a.name,basePath:a.basePath,instructions:o})}}case`read_file`:{let e=typeof r.path==`string`?r.path.trim():``;if(!e)return{result:JSON.stringify({error:`missing file path`})};let i=n.activeSkill?.basePath;t.onProgress?.(`reading ${e}`);let a=RE(e,i);return a.ok?(t.onProgress?.(`read ${e} (${a.content?.length??0} chars${a.truncated?`, truncated`:``})`),{result:JSON.stringify({type:`file_content`,path:e,truncated:a.truncated??!1,content:a.content})}):(t.onProgress?.(`read failed: ${a.error}`),{result:JSON.stringify({error:a.error})})}case`search_files`:{let e=typeof r.path==`string`?r.path.trim():``,i=typeof r.pattern==`string`?r.pattern.trim():``;if(!e||!i)return{result:JSON.stringify({error:`missing path or pattern`})};t.onProgress?.(`searching ${e} for "${i}"`);let a=LE(e,i,n.activeSkill?.basePath);return a.ok?(t.onProgress?.(`search ${e}: ${a.totalMatches} match(es)`),{result:JSON.stringify({type:`search_results`,path:e,pattern:i,totalMatches:a.totalMatches,returned:a.matches?.length??0,matches:a.matches})}):(t.onProgress?.(`search failed: ${a.error}`),{result:JSON.stringify({error:a.error})})}case`ask_user`:{let e=typeof r.question==`string`?r.question:``;if(!e.trim()||!Array.isArray(r.options)||!r.options.every(e=>typeof e==`string`)||typeof r.default_if_skip!=`string`)return{result:JSON.stringify({error:`invalid clarification question/options/default`})};let i=await t.interaction.ask({signal:t.signal,question:e,options:Array.isArray(r.options)?r.options:[],defaultIfSkip:typeof r.default_if_skip==`string`?r.default_if_skip:``});return $(t.signal),i.trim()&&n.clarifications.push({question:e,answer:i.trim()}),{result:JSON.stringify({type:`user_answer`,answer:i,note:`Recorded. Call recommend again (no arguments) to apply it.`})}}default:return{result:JSON.stringify({error:`unknown tool: ${e.function.name}`})}}}function UE(){let e=ME(jE());return`You are an AI model selection assistant for Alibaba Cloud Model Studio. You help users find the best model via tools.
|
|
249
248
|
|
|
250
249
|
## Workflow
|
|
251
250
|
1. FIRST, classify the request type:
|
|
@@ -277,10 +276,10 @@ ${e?e+`
|
|
|
277
276
|
- Ask about business scenarios, NOT technical parameters (e.g. never ask "how many tokens of context do you need")
|
|
278
277
|
- Never fabricate model names not returned by tools
|
|
279
278
|
- If the input is NOT a model request (greetings, jokes, casual chat), do NOT call any tool: respond naturally and briefly in Simplified Chinese, then introduce yourself in one sentence as the Bailian model selection assistant — mention that you can recommend models for any scenario (text/image/video/audio, single model or multi-step pipelines), compare models, look up specific models, and find cheaper alternatives — and guide the user with one concrete example question (e.g. "你可以试试问我:推荐一个写代码的模型")
|
|
280
|
-
- Everything else — including vague requests like "推荐一个", "有什么好模型", "帮我选个模型" — MUST go through the recommend tool`}async function
|
|
281
|
-
`);if(f=[],t.trim()===`[DONE]`){u=!0;return}let n=JSON.parse(t);if(n.error||d===`error`)throw
|
|
282
|
-
`);a=o.pop()??``;for(let e of o)if(h(e),u)break;if(e&&(!u&&a&&h(a),u||m(),!u))throw new
|
|
283
|
-
`))if(n.trim())try{t.push(JSON.parse(n))}catch{}return t}function
|
|
284
|
-
`);;){let e=(await i.question(`Select: `,{signal:r})).trim();if($(r),!e)return n;if(/^\d+$/.test(e)){let n=Number.parseInt(e,10)-1;if(n>=0&&n<t.length)return t[n];process.stderr.write(` 请输入 1-${t.length} 之间的序号,或直接输入文字描述\n`);continue}return e}}finally{i.close()}}}}function
|
|
285
|
-
`)}function UE(e,t){let n=VE();n.skills[e]={...n.skills[e],...t},HE(n)}const WE=`BL_SKIP_HOST_AGENTS`,GE=[`CLAUDE_CONFIG_DIR`,`CODEX_HOME`,`VIBE_HOME`,`HERMES_HOME`,`AUTOHAND_HOME`,`GROK_HOME`,`DSH_HOME`,`OPENCLAW_CONFIG_PATH`,`ZCODE_HOME`,`APPDATA`,`LOCALAPPDATA`,`FLATPAK_XDG_CONFIG_HOME`,`PI_CODING_AGENT_DIR`];function KE(){let e=Ue(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||w(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:w(e,r,`skills`),detectDirs:[w(e,r)]}),i=(t,n)=>t?.trim()||w(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:w(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>w(e,t)),s=o.find(e=>x(e))??o[0],c=[w(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(w(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(w(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:w(e,`.agents`,`skills`),detectDirs:[w(e,`.agents`),w(e,`.cline`),w(e,`.dexto`),w(e,`.firebender`),w(e,`.kimi-code`),w(e,`.kimi`),w(e,`.loaf`),w(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:w(n,`agents`,`skills`),detectDirs:[w(n,`agents`),w(n,`amp`),w(t,`.replit`)]},r(`adal`,`AdaL`,`.adal`),r(`aider-desk`,`AiderDesk`,`.aider-desk`),r(`antigravity`,`Antigravity`,`.gemini/antigravity`),r(`antigravity-cli`,`Antigravity CLI`,`.gemini/antigravity-cli`),{id:`astrbot`,displayName:`AstrBot`,skillsDir:w(e,`.astrbot`,`data`,`skills`),detectDirs:[w(t,`data`,`skills`),w(e,`.astrbot`)]},a(`autohand-code`,`Autohand Code CLI`,i(process.env.AUTOHAND_HOME,`.autohand`)),r(`augment`,`Augment`,`.augment`),r(`bob`,`IBM Bob`,`.bob`),a(`claude-code`,`Claude Code`,i(process.env.CLAUDE_CONFIG_DIR,`.claude`)),r(`codearts-agent`,`CodeArts Agent`,`.codeartsdoer`),{id:`codebuddy`,displayName:`CodeBuddy`,skillsDir:w(e,`.codebuddy`,`skills`),detectDirs:[w(t,`.codebuddy`),w(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:w(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:w(e,`.continue`,`skills`),detectDirs:[w(t,`.continue`),w(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:w(e,`.deepagents`,`agent`,`skills`),detectDirs:[w(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:w(n,`devin`,`skills`),detectDirs:[w(n,`devin`)]},r(`droid`,`Droid`,`.factory`),a(`dsh`,`DeepSeek DSH`,i(process.env.DSH_HOME,`.dsh`)),r(`forgecode`,`ForgeCode`,`.forge`),r(`gemini-cli`,`Gemini CLI`,`.gemini`),r(`github-copilot`,`GitHub Copilot`,`.copilot`),{id:`goose`,displayName:`Goose`,skillsDir:w(n,`goose`,`skills`),detectDirs:[w(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,iC(e)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:w(e,`.jazz`,`skills`),detectDirs:[w(e,`.jazz`),w(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:w(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[w(e,`.config`,`kimchi`)]},r(`kiro-cli`,`Kiro CLI`,`.kiro`),r(`kode`,`Kode`,`.kode`),r(`lingma`,`Lingma`,`.lingma`),r(`mcpjam`,`MCPJam`,`.mcpjam`),{id:`minimax-code`,displayName:`MiniMax Code`,skillsDir:w(e,`.minimax`,`skills`),detectDirs:[w(e,`.minimax`),`/Applications/MiniMax Code.app`]},a(`mistral-vibe`,`Mistral Vibe`,i(process.env.VIBE_HOME,`.vibe`)),r(`moxby`,`Moxby`,`.moxby`),r(`mux`,`Mux`,`.mux`),r(`neovate`,`Neovate`,`.neovate`),{id:`opencode`,displayName:`OpenCode`,skillsDir:w(n,`opencode`,`skills`),detectDirs:[w(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:w(s,`skills`),detectDirs:o},r(`openhands`,`OpenHands`,`.openhands`),r(`ona`,`Ona`,`.ona`),r(`pi`,`Pi`,`.pi/agent`),r(`pochi`,`Pochi`,`.pochi`),r(`qoder`,`Qoder`,`.qoder`),r(`qoder-cn`,`Qoder CN`,`.qoder-cn`),r(`qwen-code`,`Qwen Code`,`.qwen`),r(`reasonix`,`Reasonix`,`.reasonix`),r(`rovodev`,`Rovo Dev`,`.rovodev`),r(`roo`,`Roo Code`,`.roo`),{id:`tabnine-cli`,displayName:`Tabnine CLI`,skillsDir:w(e,`.tabnine`,`agent`,`skills`),detectDirs:[w(e,`.tabnine`)]},r(`terramind`,`Terramind`,`.terramind`),r(`tinycloud`,`Tinycloud`,`.tinycloud`),r(`trae`,`Trae`,`.trae`),r(`trae-cli`,`Trae CLI`,`.traecli`),r(`trae-cn`,`Trae CN`,`.trae-cn`),r(`windsurf`,`Windsurf`,`.codeium/windsurf`),r(`workbuddy`,`Tencent WorkBuddy`,`.workbuddy`),{id:`zcode`,displayName:`ZCode`,skillsDir:w(e,`.zcode`,`skills`),detectDirs:[w(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function qE(e){let t=ke(e);try{return ye(t)}catch{let e=[],n=t;for(;n!==Ee(n);){if(x(n))try{return w(ye(n),...e.reverse())}catch{break}e.push(Te(n)),n=Ee(n)}return t}}function JE(e,t){let n=qE(e),r=qE(t);return n===r||n.startsWith(r+Ae)}function YE(e){if(!De(e)||JE(e,Ue()))return!1;let t=process.env.XDG_CONFIG_HOME?.trim();return!(t&&JE(e,t))}function XE(e){return process.env.BL_SKIP_HOST_AGENTS!==`1`||!YE(e)}function ZE(){return KE().filter(e=>e.detectDirs.some(e=>XE(e)&&x(e)))}function QE(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function $E(e){let t=RE();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+Ae)}return e===t||e.startsWith(t+Ae)}function eD(e){try{if(!me(e).isSymbolicLink())return!1;let t=ve(e);return $E(De(t)?t:ke(Ee(e),t))}catch{return!1}}function tD(e,t){if(!t.some(t=>QE(t,e)))return!1;try{return me(e).isDirectory()}catch{return!1}}function nD(e){try{return me(e).isDirectory()?x(w(e,`SKILL.md`)):!1}catch{return!1}}const rD=`existing file/dir not managed by bl skill`;function iD(e,t=ZE(),n=[]){let r=w(RE(),e),i=[];for(let a of t){let t=w(a.skillsDir,e);try{let e=!1;try{me(t),e=!0}catch{}if(e){if(eD(t))C(t);else if(tD(t,n))C(t,{recursive:!0,force:!0});else if(nD(t))C(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:rD});continue}}he(a.skillsDir,{recursive:!0});try{xe(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{de(r,t,{recursive:!0}),i.push({agent:a.id,path:t,mode:`copy`})}}catch(e){i.push({agent:a.id,path:t,mode:`skipped`,reason:e instanceof Error?e.message:String(e)})}}return i}function aD(e,t=ZE(),n=[]){let r=iD(e,t,n),i=r.filter(e=>e.mode!==`skipped`),a=i.map(e=>e.path),o=r.filter(e=>e.mode===`skipped`&&e.reason===rD).map(e=>e.path),s=n.filter(e=>!a.some(t=>QE(t,e))&&!o.some(t=>QE(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function oD(e,t=[]){let n=[],r=new Set(t);for(let t of KE())r.add(w(t.skillsDir,e));for(let e of r)try{let r;try{r=me(e)}catch{continue}r.isSymbolicLink()?eD(e)&&n.push(e):t.some(t=>QE(t,e))&&n.push(e)}catch{}return n}function sD(e,t=[]){let n=[];for(let r of oD(e,t))try{if(eD(r))C(r);else if(!me(r).isSymbolicLink()&&t.some(e=>QE(e,r)))C(r,{recursive:!0,force:!0});else continue;n.push(r)}catch{}return n}function cD(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function lD(e,t){let n=Ke.extract();n.on(`entry`,(e,r,i)=>{if(!cD(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(/* @__PURE__ */ Error(`unsafe tar entry: ${e.name}`));return}let a=w(t,e.name);if(e.type===`directory`){he(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}he(Ee(a),{recursive:!0});let o=pe(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await We(we.from(e),Ge(),n)}function uD(e){let t=[],n=r=>{for(let i of _e(r?w(e,r):e,{withFileTypes:!0})){let e=r?`${r}/${i.name}`:i.name;i.isDirectory()?n(e):i.isFile()&&t.push(e)}};n(``),t.sort((e,t)=>e<t?-1:+(e>t));let r=ze(`sha256`);for(let n of t)r.update(n),r.update(ge(w(e,n)));return`sha256:${r.digest(`hex`)}`}function dD(e,t,n=259){let r,i=a=>{for(let o of _e(a,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let s=w(a,o.name),c=Oe(e,s);for(let e of t){let t=w(e,c).length;t>n&&t>(r?.pathLength??0)&&(r={root:e,relativePath:c,pathLength:t})}o.isDirectory()&&i(s)}};for(let e of t)e.length>n&&e.length>(r?.pathLength??0)&&(r={root:e,relativePath:``,pathLength:e.length});return i(e),r}function fD(e){let t=[],n=r=>{for(let i of _e(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=w(r,i.name),o=Oe(e,a);i.isDirectory()?(t.push({relativePath:o,type:`directory`}),n(a)):i.isFile()&&t.push({relativePath:o,type:`file`})}};return n(e),t}function pD(e,t){let n=fD(e),r=new Set(n.map(e=>e.relativePath));he(t,{recursive:!0});for(let r of n){let n=w(e,r.relativePath),i=w(t,r.relativePath);if(x(i)){let e=me(i);(!(r.type===`directory`?e.isDirectory():e.isFile())||e.isSymbolicLink())&&C(i,{recursive:!0,force:!0})}r.type===`directory`?he(i,{recursive:!0}):(he(Ee(i),{recursive:!0}),ue(n,i))}let i=fD(t).filter(e=>!r.has(e.relativePath)).sort((e,t)=>t.relativePath.length-e.relativePath.length);for(let e of i)C(w(t,e.relativePath),{recursive:!0,force:!0})}function mD(e){let t=e?.code;return t===`EPERM`||t===`EBUSY`}function hD(e){try{x(e)&&C(e,{recursive:!0,force:!0})}catch{}}function gD(e,t,n={}){he(Ee(t),{recursive:!0});let r=`${t}.old-${Date.now()}`;if(x(t))try{S(t,r)}catch(i){if(!(n.allowInPlaceFallback??process.platform===`win32`)||!mD(i))throw i;try{pD(t,r),pD(e,t),hD(r);return}catch(e){try{x(r)&&pD(r,t)}catch{}throw Error(`Skill directory is in use and could not be updated in place. Close running agent hosts and retry. / Skill 目录正被占用,无法原地更新;请关闭正在运行的 Agent 后重试。 ${e instanceof Error?e.message:String(e)}`,{cause:e})}}try{S(e,t)}catch(e){throw x(r)&&!x(t)&&S(r,t),e}hD(r)}function _D(e){if(e instanceof D){let t=e.api?.httpStatus;if(t!==void 0){if(t===408||t===429)return!0;if(t>=400&&t<500)return!1}return!0}return!0}function vD(e){return e instanceof D&&e.api?.httpStatus===429}function yD(e,t){return Math.min(t*2**(e-1),1e4)}function bD(e){return new Promise(t=>setTimeout(t,e))}async function xD(e,t=3){let n=typeof t==`number`?{attempts:t}:t,r=n.attempts??3,i=n.shouldRetry??_D,a=n.backoffBaseMs??500,o;for(let t=1;t<=r;t++)try{return await e(t)}catch(e){if(o=e,t>=r||!i(e,t))break;vD(e)&&await bD(yD(t,a))}throw o}function SD(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function CD(e=3e4,t=3){return xD(async()=>{let t=`${SD()}/index.json`,n;try{n=await gn.fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new D(`Cannot access skill registry: ${t}`,E.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new D(`Skill registry returned HTTP ${n.status}: ${t}`,E.NETWORK,n.status===404?`Skill index not yet published or registry URL is incorrect; confirm the publisher has generated index.json`:`Remote error, retry later`);let r;try{r=await n.json()}catch(e){throw new D(`Skill index index.json is not valid JSON`,E.GENERAL,`Remote may be in the middle of publishing, retry later`,{cause:e})}let i=r;if(typeof i!=`object`||!i||typeof i.skills!=`object`||i.skills===null)throw new D(`Skill index index.json has invalid structure`,E.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const wD=/^sha256-[0-9a-f]{64}\.tar\.br$/;function TD(e){let t=e?.object;return t&&wD.test(t)?t:`skill.tar.br`}async function ED(e,t,n=3){return xD(async()=>{let n=`${SD()}/${e}/${TD(t)}`,r;try{r=await gn.fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new D(`Failed to download skill ${e}: ${n}`,E.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new D(`Failed to download skill ${e}: HTTP ${r.status}`,E.NETWORK,r.status===404?`index.json and skill object are temporarily inconsistent (publishing in progress), retry later`:`Remote error, retry later`);return Buffer.from(await r.arrayBuffer())},{attempts:n})}function DD(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function OD(e){return e.length>0&&DD(e)===e}function kD(e,t){throw new D(`Skill ${e} validation failed: ${t}`,E.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function AD(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function jD(e,t){let n=w(e,`SKILL.md`),r;try{be(n).isFile()||kD(t,`SKILL.md is not a regular file`),r=ge(n,`utf-8`)}catch(e){if(e instanceof D)throw e;kD(t,`missing SKILL.md`)}let i=AD(r);i===null&&kD(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{kD(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&kD(t,`frontmatter is not a key-value structure`);let o=a,s=typeof o.name==`string`?o.name.trim():``,c=typeof o.description==`string`?o.description.trim():``;return(!s||!c)&&kD(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function MD(e){if(!OD(e))throw new D(`Invalid skill name: ${e}`,E.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function ND(e,t,n,r){MD(e);let i=RE(),a=w(i,e),o=w(i,`.tmp-${e}-${process.pid}-${Date.now()}`);try{he(o,{recursive:!0}),await lD(t,o);let i=dD(o,r??(process.platform===`win32`?[a]:[]));if(i)throw new D(`Skill ${e} contains a Windows-incompatible path (${i.pathLength} characters): ${i.relativePath}`,E.GENERAL,`The skill package must shorten this path before it can be installed safely on Windows. / Skill 包必须缩短该路径后才能在 Windows 上安全安装。`);if(n?.startsWith(`sha256:`)){let t=uD(o);if(t!==n)throw new D(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,E.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let s=jD(o,e);return gD(o,a),{name:e,path:a,meta:s}}finally{try{x(o)&&C(o,{recursive:!0,force:!0})}catch{}}}async function PD(e,t,n,r){if(t.compression&&t.compression!==`tar.br`)throw new D(`Skill ${e} uses unsupported compression format: ${t.compression}`,E.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return ND(e,await ED(e,t,n),t.contentHash,r)}function FD(e){MD(e);let t=w(RE(),e);return x(t)?(C(t,{recursive:!0,force:!0}),!0):!1}function ID(e,t){return{...e.contentHash?{contentHash:e.contentHash}:{},...e.publishedAt?{publishedAt:e.publishedAt}:{},installedAt:(/* @__PURE__ */ new Date()).toISOString(),sourceType:`oss`,...e.description?{description:e.description}:{},links:t}}async function LD(e,t,n=ZE(),r=[],i){await PD(e,t,i,process.platform===`win32`?[w(RE(),e),...n.map(t=>w(t.skillsDir,e))]:void 0);let a=aD(e,n,r);return{lockEntry:ID(t,a.links),linkedAgents:a.linkedAgents}}const RD=`bailian-docs-llm-wiki`;function zD(){return w(Nt(),`skills/bailian-docs-llm-wiki`)}function BD(){return x(w(zD(),`models`,`models.jsonl`))}function VD(){return w(Nt(),`wiki-sync-state.json`)}function HD(){try{return JSON.parse(ge(VD(),`utf-8`))}catch{return null}}function UD(e){try{Se(VD(),JSON.stringify(e))}catch{}}function WD(e){try{UE(RD,e)}catch{}}function GD(e){try{let t=VE().skills[RD];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function KD(){try{return(await CD(3e3,1)).skills[RD]??null}catch{return null}}async function qD(){let e=HD(),t=Date.now();if(e&&t-e.lastChecked<432e5&&BD())return!1;let n=await KD();if(!n?.contentHash)return!1;if(BD()&&(!e||e.contentHash===n.contentHash)){if(UD({lastChecked:t,contentHash:n.contentHash}),GD(n.contentHash)){let e=VE().skills[RD]?.links??[];WD(ID(n,aD(RD,ZE(),e).links))}return!1}try{let e=VE().skills[RD]?.links??[];WD((await LD(RD,n,ZE(),e,1)).lockEntry)}catch{return!1}return UD({lastChecked:t,contentHash:n.contentHash}),!0}const JD={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},YD={Single:`single`,Pipeline:`pipeline`},XD={Low:`low`,Medium:`medium`,High:`high`},ZD={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},QD={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},$D={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},eO={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},tO={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},nO=`bailian-cli`,rO=`install-method`,iO=/* @__PURE__ */ new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function aO(e){return e?w(Nt(),`${rO}.${e}`):w(Nt(),rO)}function oO(){if(process.env.BAILIAN_COMPILED===`1`)return!0;let e=process.execPath.replaceAll(`\\`,`/`);return/(^|\/)node(\.exe)?$/i.test(e)||e.includes(`/node/`)||/(^|\/)bun(\.exe)?$/i.test(e)||e.includes(`/.bun/`)?!1:/\/(bl|bailian)(\.exe)?$/i.test(e)}function sO(e){if(!e)return null;let t=e.trim().toLowerCase();return iO.has(t)?t:null}function cO(e){try{return sO(ge(e,`utf-8`).split(`
|
|
286
|
-
`)[0])}catch{return null}}function lO(){let e=sO(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(oO()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function uO(e){let t=sO(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=cO(aO(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=cO(aO());if(e)return e}return lO()}return cO(aO())||lO()}function dO(e){let t=uO(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function fO(e,t={clientName:nO}){try{let n=Nt();x(n)||he(n,{recursive:!0,mode:448}),Se(aO(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&Se(aO(),`${e}\n`,{mode:384})}catch{}}const pO=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,mO=`https://github.com/modelstudioai/cli/releases`,hO=`https://bailian.aliyun.com/cli/install.sh`,gO=`https://bailian.aliyun.com/cli/install.ps1`;function _O(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):pO}function vO(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${_O()}/manifest.json`:`${_O()}/${t}.json`}function yO(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${_O()}/${n}/${t}`}function bO(){let e=process.platform,t=process.arch,n;if(e===`darwin`)n=`darwin`;else if(e===`linux`)n=`linux`;else if(e===`win32`)n=`windows`;else throw Error(`Unsupported platform for binary updates: ${e}`);let r;if(t===`arm64`)r=`arm64`;else if(t===`x64`)r=`x64`;else throw Error(`Unsupported architecture for binary updates: ${t}`);if(n===`linux`&&r===`arm64`)throw Error(`linux arm64 is not supported for binary updates; use: npm install -g bailian-cli`);if(n===`windows`&&r===`arm64`)throw Error(`windows arm64 is not supported for binary updates; use: npm install -g bailian-cli`);return{os:n,arch:r,fileSuffix:e===`win32`?`.exe`:``}}function xO(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function SO(e,t,n){if(t!==`windows`)return`bl-${e}-${t}-${n}.tar.gz`}function CO(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function wO(e){return new Promise((t,n)=>{le.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??/* @__PURE__ */ Error(`Failed to open zip: ${e}`));return}t(i)})})}function TO(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function EO(e,t,n){let r=await wO(e);return new Promise((i,a)=>{let o=!1,s=e=>{if(!o){o=!0;try{r.close()}catch{}a(e instanceof Error?e:Error(String(e)))}},c=e=>{if(!o){o=!0;try{r.close()}catch{}i(e)}};r.on(`error`,s),r.on(`end`,()=>{o||s(/* @__PURE__ */ Error(n?`Zip entry not found: ${n} in ${e}`:`Zip has no file entries: ${e}`))}),r.on(`entry`,e=>{if(o)return;let i=e.fileName.replace(/\\/g,`/`);if(i.endsWith(`/`)){r.readEntry();return}let a=TO(i);if(n&&i!==n&&a!==n){r.readEntry();return}r.openReadStream(e,(n,r)=>{if(n||!r){s(n??/* @__PURE__ */ Error(`Failed to read zip entry: ${e.fileName}`));return}(async()=>{try{await Pe(Ee(t),{recursive:!0}),await We(r,pe(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function DO(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new nt(`--name cannot be empty`,`Use --name all or --name skill-a,skill-b`);let r=[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))];if(r.includes(`all`)){if(r.length>1)throw new nt(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function OO(){let e=RE();return x(e)?_e(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return be(w(e,t)).isDirectory()}catch{return!1}}):[]}function kO(e,t,n){let r=new Set(n),i=/* @__PURE__ */ new Set,a=[];for(let[n,o]of Object.entries(e.skills)){i.add(n);let e=t.skills[n];if(e){let t=r.has(n)?e.contentHash===o.contentHash?`installed`:`outdated`:`missing`;a.push({name:n,status:t,publishedAt:o.publishedAt,description:o.description})}else r.has(n)?a.push({name:n,status:`untracked`,publishedAt:o.publishedAt,description:o.description}):a.push({name:n,status:`not-installed`,publishedAt:o.publishedAt,description:o.description})}for(let[e,n]of Object.entries(t.skills))i.has(e)||(i.add(e),a.push({name:e,status:r.has(e)?`installed`:`missing`,publishedAt:n.publishedAt,description:n.description}));for(let e of n)i.has(e)||a.push({name:e,status:`untracked`});return a.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}export{GE as AGENT_ENV_KEYS,nv as AIGC_MCP_SERVER,rv as AIGC_MCP_TOOL,ht as API_KEY_CAPABILITY_PATTERN,YS as ASYNC_FLAG,lt as BAILIAN_HOST,Hb as BATCH_CSV_COLUMNS,yb as BATCH_ENDPOINTS,bb as BATCH_STATUSES,xb as BATCH_TERMINAL,gS as BILLING_METHOD,nO as BINARY_PRODUCT_CLIENT_NAME,D as BailianError,jb as BatchValidator,XD as Budgets,Kx as CALC_DATASETS_TOKENS_API,wn as CHANNEL,vS as CHARGE_TYPE,tC as COMMAND_PACK_API_VERSION,JS as CONCURRENT_FLAG,ft as CONFIG_FILE_KEYS,ZS as CONSOLE_AUTH_FLAGS,$D as Capabilities,Ph as Client,YD as Complexities,ZD as ContextNeeds,Dn as DASHSCOPE_SERVICE_HEADER,ly as DECISION_QUESTION_TYPES,Zb as DECISION_REGIONS,_S as DEFAULT_BILLING_METHOD,pO as DEFAULT_CLI_CDN_BASE,Xb as DEFAULT_DECISION_MODEL,Qb as DEFAULT_DECISION_REGION,mS as DEFAULT_DEPLOY_PLAN,gO as DEFAULT_INSTALL_PS1_URL,hO as DEFAULT_INSTALL_SCRIPT_URL,dt as DEFAULT_LANGUAGE,xE as DEFAULT_LLM_MODEL,Cx as DEFAULT_TRAINING_TYPE,jS as DEPLOY_LIST_INDEPENDENT_API,pS as DEPLOY_PLAN,kS as DEPLOY_START_API,AS as DEPLOY_STOP_API,ct as DOCS_HOSTS,qx as ESTIMATE_FINETUNE_TOKENS_API,E as ExitCode,eO as Features,mO as GITHUB_RELEASES_BASE,qS as GLOBAL_FLAGS,kx as INSUFFICIENT_SAMPLES_CODE,UC as LLMError,Sb as MAX_BATCH_BYTES,Cb as MAX_BATCH_LINE_BYTES,wb as MAX_BATCH_RECORDS,Wv as MAX_CPT_BYTES,Uv as MAX_DATASET_BYTES,uy as MAX_DECISION_CHOICE_OPTIONS,Gv as MAX_DECISION_DATASET_BYTES,fy as MAX_DECISION_SCORE_LEVELS,Kv as MAX_MEDIA_ZIP_BYTES,Tn as MCP_CALL_SERVICE,fv as MCP_IMAGE_GEN_RATIO_SIZES,mv as MCP_TTS_VOICES,dy as MIN_DECISION_SCORE_LEVELS,XS as MODEL_AUTH_FLAGS,Tv as MODEL_LIST_API,Ch as McpClient,JD as Modalities,tO as ModelCategories,QS as OPENAPI_AUTH_FLAGS,En as OPEN_API_SOURCE,Ev as PREDICT_CONFIG_API,QD as QualityPreferences,u_ as RAG_PATHS,_E as RECOMMEND_TOOLS,st as REGIONS,a_ as SANDBOX_PATHS,WE as SKIP_HOST_AGENTS_ENV,IS as SPEECH_BIASING_MODEL,DS as STRATEGIES,ut as SUPPORTED_LANGUAGES,Gx as TRAINING_MODEL_PRICE_API,Sx as TRAINING_TYPES_CLI,xx as TRAINING_TYPE_MAP,nt as UsageError,rn as activateConfigProfile,bE as agentLoop,t_ as agentStudioFilesPath,wg as agentStudioHost,nw as analyzeEngineIntent,bn as anonymousConsoleCall,og as appCompletionPath,gD as atomicSwap,Qn as audioFileToDataUri,kh as bailianMcpPath,Ah as bailianMcpSsePath,Ob as batchChunks,Yb as batchDataNotes,Jb as batchExamples,Tb as batchIoError,kb as batchLines,Eb as batchObject,Q as batchUsage,xO as binaryAssetFileName,CO as binaryInnerFileName,SO as binaryTarFileName,Ln as buildAcsCanonicalQuery,P_ as buildAsrContextMessages,I_ as buildAsrFlashRequest,F_ as buildAsyncAsrLanguageFields,gE as buildEngineInput,ov as buildImageEditArgs,av as buildImageGenArgs,cv as buildImageToVideoArgs,CS as buildPrepaidInfo,bS as buildReservationCapacity,cn as buildSettings,ID as buildSkillLockEntry,sn as buildSources,dv as buildSpeechToTextArgs,sv as buildTextToVideoArgs,uv as buildTtsArgs,lv as buildVideoFetchArgs,LS as buildVocabularyRequest,Sn as callConsoleGateway,Ib as cancelBatch,yx as cancelCompressJob,cx as cancelFineTune,vO as channelManifestUrl,Uh as chatPath,R_ as collectAsrTranscriptionItems,uD as computeDirContentHash,kO as computeSkillStatuses,Nh as connectBailianMcpWithFallback,$_ as createBailianControlUser,Pb as createBatch,iS as createCapacityInstance,hx as createCompressJob,Qx as createDeployment,ax as createFineTune,Y_ as createInstrumentedFetch,SE as createLLMClient,LE as createNonInteractive,IE as createReadlineInteraction,hE as createSession,xC as createTrackingEvent,zS as createVocabulary,$S as credentialFlagDefs,Xh as decisionPath,hS as defaultDeployPlan,eC as defineCommand,sS as deleteCapacityInstance,bx as deleteCompressJob,an as deleteConfigProfile,Hv as deleteDataset,lS as deleteDeployment,lx as deleteFineTune,US as deleteVocabulary,Kg as deploymentCapacityInstancePath,Jg as deploymentCapacityInstanceRenewPath,qg as deploymentCapacityInstanceScalePath,Gg as deploymentCapacityInstancesPath,Xg as deploymentCapacityOperationPath,Yg as deploymentOverflowPath,Mt as describeAuthState,bO as detectBinaryPlatform,lO as detectInstallMethod,ZE as detectInstalledAgents,sb as detectModality,Bt as detectOutputFormat,vE as dispatchTool,ED as downloadSkillAsset,yn as effectiveConsoleGatewayConfig,BE as emptySkillLock,It as ensureConfigDir,Xx as estimateCptTokens,Yx as estimateSftDpoTokens,qb as exportBatchCsv,fx as exportCheckpoint,L_ as extractAsrFlashText,lD as extractTarBr,EO as extractZipEntryToFile,aD as fanOutSkillToAgents,Ox as fetchModelCapability,Pv as fetchModelDetail,jv as fetchModelGroups,Nv as fetchModelGroupsAll,Ov as fetchModelList,kv as fetchModelListAll,Lv as fetchPredictConfig,CD as fetchSkillsIndex,Jx as fetchTrainingModelPrice,FS as findDeploymentEntry,Av as findModelByName,Mv as flattenModelGroups,PC as flushTelemetry,ix as followParsexResult,KC as formatDegradation,zt as formatErrorJson,vb as formatIssue,Rt as formatJson,Vt as formatOutput,Lt as formatText,Rh as generateCLIAccessToken,rC as generateFilename,KE as getAgentTargets,dn as getApiKeyLoginKind,Fb as getBatch,Rb as getBatchFileContent,nS as getCapacityInstance,rS as getCapacityOperation,_O as getCliCdnBase,_x as getCompressJob,vx as getCompressJobLogs,Nt as getConfigDir,Pt as getConfigPath,Ft as getCredentialsPath,Vv as getDataset,eS as getDeployment,sx as getFineTune,ux as getFineTuneLogs,iC as getHermesHome,uO as getInstallMethod,un as getModelProfilePreset,rx as getParsexResult,Ux as getProfile,zE as getSkillLockPath,SD as getSkillRegistryBaseUrl,RE as getSkillsDir,dO as getUpdateInstallMethod,xS as hasPrepaidFlags,gn as httpTransport,eg as image2ImagePath,ng as image2videoPath,Zn as imageFileToDataUri,Zh as imagePath,Qh as imageSyncPath,$h as imageText2ImagePath,N_ as inferAudioFormatHint,xy as inspectDecisionQuestion,Cy as inspectDecisionQuestionId,Sy as inspectDecisionQuestionTable,wy as inspectDecisionQuestions,_y as inspectDecisionState,PD as installSkill,ND as installSkillFromBuffer,LD as installSkillWithFanout,gt as isApiKeyCapability,oO as isCompiledBinary,V_ as isDashScopeGateway,my as isDecisionObject,YE as isHostSystemDetectDir,y_ as isLegacyImage2ImageModel,v_ as isLegacyText2ImageModel,tr as isLocalFile,hv as isMcpTtsVoice,Ct as isModelConnectionSourceMismatch,cD as isSafeEntryName,OD as isSafeSkillName,jh as isStreamableHttpUnsupported,m_ as isSyncMultimodalImageModel,wx as isTrainingTypeCli,Mh as isUrlOverrideSseFallbackCandidate,b_ as isWanxFunctionImageEditModel,Cg as knowledgeChatEndpoint,Sg as knowledgeSearchEndpoint,iD as linkSkillToAgents,ev as listBailianControlWorkspaces,Lb as listBatches,tS as listCapacityInstances,dx as listCheckpoints,gx as listCompressJobs,mx as listCompressTemplates,Bv as listDatasets,uS as listDeployableModels,$x as listDeployments,ox as listFineTunes,PS as listIndependentDeployedModels,OO as listSkillDirsOnDisk,_b as listSupportedFormats,Dx as listSupportedTrainingTypes,Wx as listTrainingTypes,BS as listVocabularies,NE as loadCatalog,PE as loadFamilies,FC as localSink,mn as makeAuthStore,Rv as makeConfigStore,it as mapApiError,Cn as maskToken,qD as maybeSyncWikiData,Og as mcpWebSearchPath,cg as memoryAddAsyncPath,sg as memoryEndpoint,lg as memoryEventPath,dg as memoryListPath,fg as memoryNodePath,ug as memorySearchPath,pg as memorySkillExportPath,Ex as modelSupportsTrainingType,ig as modelsLimitsPath,ag as modelsPermissionsPath,_t as normalizeApiKeyCapabilities,qt as normalizeConfigName,at as normalizeModelBaseUrl,xv as parseAigcAsrTexts,_v as parseAigcImageResults,iv as parseAigcToolResult,vv as parseAigcTtsResult,yv as parseAigcVideoTaskId,bv as parseAigcVideoTaskResult,Db as parseBatchEndpoint,dC as parseBooleanValue,yt as parseConfigFile,Jv as parseDatasetSchemaFlag,GS as parseInstantVocabulary,fC as parseOptionalBooleanValue,wv as parseSSE,G_ as parseSecurityBody,DO as parseSkillNames,KS as parseVocabularyEntries,Vh as parsexBaseUrl,Hh as parsexEndpoint,OS as pickPlanStrategy,mb as pickValidator,oD as planUnlinkSkillFromAgents,Ax as preflightBatchSizeGate,Vb as prepareBatch,vg as profileSchemaItemPath,_g as profileSchemaPath,Kb as projectBatchCsv,VS as queryVocabulary,e_ as ragEndpoint,Nb as readBatchBlob,bC as readCaller,Zt as readConfigFile,en as readConfigProfiles,VE as readSkillLock,lC as readTextFromPathOrStdin,nE as recommendEngine,$n as redactDataUri,zh as refreshAccessToken,hb as registerValidator,yO as releaseAssetUrl,IC as remoteSink,FD as removeSkillDir,oS as renewCapacityInstance,Mn as request,In as requestJson,tv as resetBailianControlPolicies4Agent,FE as resetCatalogCache,Et as resolveApiKey,bt as resolveApiKeySource,M_ as resolveAsrApi,TD as resolveAssetFileName,zb as resolveBatchChatEndpoint,pC as resolveBooleanFlag,Ih as resolveCLIAccessTokenTarget,Dt as resolveConsole,nr as resolveFileUrl,T_ as resolveImageEditApi,w_ as resolveImageGenerateApi,x_ as resolveImageSizeProfile,pv as resolveMcpImageSize,Tt as resolveModelBaseUrl,xt as resolveModelBaseUrlSource,wt as resolveModelBaseUrlState,St as resolveModelConnectionProvenance,Ot as resolveOpenApi,sC as resolveOutputDir,S_ as resolvePromptExtendDefault,mC as resolveWatermark,Yh as responsesPath,Nw as routeEngine,uC as runWithConcurrency,r_ as sandboxApiPath,n_ as sandboxBaseUrl,i_ as sandboxEndpoint,s_ as sandboxInstanceActionPath,o_ as sandboxInstancePath,l_ as sandboxTemplateBuildStatusPath,c_ as sandboxTemplatePath,DD as sanitizeSkillName,aS as scaleCapacityInstance,dS as scaleDeployment,Dg as securityAgentLogsEndpoint,K_ as securityGet,Eg as securityOverviewEndpoint,on as selectApiKeyResolutionSources,Rn as signAcsRequest,On as sourceConfig,hg as speechRecognizePath,mg as speechSynthesizePath,gg as speechVocabularyPath,MS as startModelService,NS as stopModelService,tx as stripDecisionTrainingFields,cC as stripUndefined,nx as submitParsexTask,rg as taskPath,BC as trackCommandExecution,kn as trackingHeaders,Tx as trainingTypeMethodVariant,sD as unlinkSkillFromAgents,ex as unwrapDecisionQuestions,Dv as unwrapResponse,fS as updateDeployment,cS as updateDeploymentOverflow,HS as updateVocabulary,zv as uploadDataset,er as uploadFile,UE as upsertSkillLockEntry,yg as userProfilePath,bg as userProfileValuesPath,Mb as validateBatch,nn as validateConfigProfileActivation,Lh as validateConsoleAccessToken,gb as validateDataset,SS as validatePrepaidFlags,yS as validateReservationCapacity,jD as validateSkillDir,Ut as validateTimeout,tg as videoGeneratePath,xg as workspaceMaaSBaseUrl,Bb as writeBatchFile,Qt as writeConfigFile,fO as writeInstallMethodSync,HE as writeSkillLock};
|
|
279
|
+
- Everything else — including vague requests like "推荐一个", "有什么好模型", "帮我选个模型" — MUST go through the recommend tool`}async function WE(e,t,n){let r=[{role:`system`,content:UE()},{role:`user`,content:e}],i=zE(e),a=[],o,s=0,c=0,l=e=>{a.push(e),n?.(e)};try{for(let e=0;e<10;e++){c=e,$(t.signal);let n;try{n=await t.llm.chatWithTools(r,VE,{stage:`agent`,signal:t.signal}),$(t.signal)}catch(n){$(t.signal);let r=vw(n,`agent`);if(r.kind===`cancelled`)throw r;if(r.fatal){if(!o)throw r;let n=gw(`agent`,`agent-summary→engine-result`,r);return t.onDiagnostic?.(`[recommend] agent loop failed (${r.tag}), using the recommendation already computed`),l({turn:e,type:`fallback`,reason:`agent_error_existing_result`}),{finalText:``,recommendResult:o,turns:e,degradations:[n],trajectory:a}}t.onDiagnostic?.(`[recommend] agent loop failed (${r.tag}), falling back to engine: ${r.message}`);let s=await EE(BE(i),t);return l({turn:e,type:`fallback`,reason:`agent_error_engine_rerun`}),{finalText:``,recommendResult:s,turns:e,degradations:[gw(`agent`,`agent→engine-rerun`,r)],trajectory:a}}if(!n.toolCalls.length)return l({turn:e,type:`final_answer`,reason:n.content.trim()?`completed`:`empty_answer`}),{finalText:n.content,recommendResult:o,turns:e+1,degradations:[],trajectory:a};r.push({role:`assistant`,content:n.content,tool_calls:n.toolCalls});for(let t of n.toolCalls){let n;try{n=JSON.parse(t.function.arguments||`{}`)}catch{}l({turn:e,type:`tool_call`,callId:t.id,tool:t.function.name,args:n})}for(let a of n.toolCalls)try{if($(t.signal),a.function.name===`ask_user`&&s>=2){let t={error:`clarify budget exhausted; proceed with defaults`};l({turn:e,type:`tool_result`,callId:a.id,tool:a.function.name,status:`rejected`,reason:`clarify_budget`,result:t}),r.push({role:`tool`,tool_call_id:a.id,content:JSON.stringify(t)});continue}let n=await HE(a,t,i);$(t.signal),n.recommendResult&&(o=n.recommendResult);let c=JSON.parse(n.result),u=c.error?`error`:`success`;a.function.name===`ask_user`&&u===`success`&&s++,l({turn:e,type:`tool_result`,callId:a.id,tool:a.function.name,status:u,result:c,resultType:typeof c.type==`string`?c.type:void 0,degradations:n.recommendResult?.type===`result`?n.recommendResult.degradations:void 0}),r.push({role:`tool`,tool_call_id:a.id,content:n.result})}catch(n){let r=t.signal?.aborted||vw(n,`agent`).kind===`cancelled`;throw l({turn:e,type:`tool_result`,callId:a.id,tool:a.function.name,status:r?`cancelled`:`error`,reason:n instanceof Error?n.message:String(n)}),n}}return c=10,$(t.signal),l({turn:10,type:`fallback`,reason:`turn_budget`}),o?{finalText:``,recommendResult:o,turns:10,degradations:[],trajectory:a}:{finalText:``,recommendResult:await EE(BE(i),t),turns:10,degradations:[],trajectory:a}}catch(e){let n=t.signal?.aborted||vw(e,`agent`).kind===`cancelled`,r=new Set(a.filter(e=>e.type===`tool_result`).map(e=>`${e.turn}:${e.callId}`));for(let e of a.filter(e=>e.type===`tool_call`&&!r.has(`${e.turn}:${e.callId}`)))l({turn:e.turn,type:`tool_result`,tool:e.tool,callId:e.callId,status:n?`cancelled`:`rejected`,reason:`run_terminated`});throw l({turn:c,type:n?`cancelled`:`error`,reason:e instanceof Error?e.message:String(e)}),$(t.signal),e}}const GE=`qwen-flash-2025-07-28`;function KE(e){let{baseUrl:t,apiKey:n,defaultModel:r=GE,timeoutMs:i=6e4,enableThinking:a,thinkingStages:o,thinkingLog:s,onThinking:c}=e,l=`${t.replace(/\/$/,``)}/compatible-mode/v1/chat/completions`;async function u(t,r,a){$(r.signal);let o=new AbortController,s=setTimeout(()=>o.abort(),i),c=r.signal?AbortSignal.any([r.signal,o.signal]):o.signal;try{e.onRequest?.(r.stage??`llm`);let i=await(e.fetch??fetch)(l,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:c});if(!i.ok){let e=await i.text(),t={message:e.slice(0,200)};try{t=JSON.parse(e)}catch{}throw qE(t,i.status,i.headers.get(`x-request-id`)??void 0)}let o=await a(i,c);return $(r.signal),o}catch(e){throw $(r.signal),o.signal.aborted?new mw(`timeout`,`LLM request timed out after ${i}ms`,{cause:e}):e instanceof mw?e:e instanceof SyntaxError?new mw(`parse`,`LLM 响应不是有效 JSON`,{cause:e}):new mw(`network`,`LLM request failed: ${e?.cause?.code??e?.message}`,{cause:e})}finally{clearTimeout(s)}}async function d(e,t={}){return u(e,t,async e=>{let n=await e.json();if(n.error)throw qE(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.[0];if(JE(r?.finish_reason),!r?.message)throw new mw(`parse`,`LLM 响应缺少 message`);if(YE(r.message.tool_calls??[]),!r.message.content?.trim()&&!r.message.tool_calls?.length)throw new mw(`parse`,`LLM 返回空响应`);let i=r.message.reasoning_content;return s&&i&&s.push({stage:t.stage??`llm`,content:i}),n})}async function f(e,t,n={}){let i=n.stage??(t?`agent`:`llm`);return u({model:n.model??r,messages:e.map(XE),...t?{tools:t}:{},temperature:n.temperature??0,max_tokens:n.maxTokens??4096,stream:!0,enable_thinking:!0},{...n,stage:i},async(e,t)=>{if(!e.body)throw new mw(`parse`,`SSE 响应缺少正文`);let n=e.body.getReader(),r=new TextDecoder,a=``,o=``,l=``,u=!1,d=``,f=[],p=/* @__PURE__ */ new Map,m=()=>{if(!f.length)return;let t=f.join(`
|
|
280
|
+
`);if(f=[],t.trim()===`[DONE]`){u=!0;return}let n=JSON.parse(t);if(n.error||d===`error`)throw qE(n,void 0,e.headers.get(`x-request-id`)??void 0);let r=n.choices?.find(e=>e.index===0||e.index===void 0);JE(r?.finish_reason);let a=r?.delta;if(a){a.reasoning_content&&(l+=a.reasoning_content,c?.(i,a.reasoning_content)),o+=a.content??``;for(let e of a.tool_calls??[]){let t=e.index;if(t===void 0||!Number.isInteger(t)||t<0)throw new mw(`parse`,`工具片段缺少有效 index`);let n=p.get(t)??{id:``,name:``,arguments:``};if(e.id){if(n.id&&n.id!==e.id)throw new mw(`parse`,`同一工具 index 返回不同 id`);n.id=e.id}n.name+=e.function?.name??``,n.arguments+=e.function?.arguments??``,p.set(t,n)}}},h=e=>{let t=e.replace(/\r$/,``);t?t.startsWith(`data:`)?f.push(t.slice(5).replace(/^ /,``)):t.startsWith(`event:`)&&(d=t.slice(6).trim()):(m(),d=``)},g=()=>{n.cancel().catch(()=>{})};t.addEventListener(`abort`,g,{once:!0});try{for(;!u;){t.throwIfAborted();let{done:e,value:i}=await n.read();t.throwIfAborted(),a+=e?r.decode():r.decode(i,{stream:!0});let o=a.split(`
|
|
281
|
+
`);a=o.pop()??``;for(let e of o)if(h(e),u)break;if(e&&(!u&&a&&h(a),u||m(),!u))throw new mw(`parse`,`SSE 在完成标记前断流`)}let e=[...p.entries()].sort(([e],[t])=>e-t).map(([,e])=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.arguments}}));if(YE(e),!o.trim()&&!e.length)throw new mw(`parse`,`SSE 返回空响应`);return s&&l&&s.push({stage:i,content:l}),{content:o,toolCalls:e}}finally{t.removeEventListener(`abort`,g),await n.cancel().catch(()=>{}),n.releaseLock()}})}let p=e=>e?.stage!==void 0&&o?.includes(e.stage)||a===!0;return{async chat(e,t){return p(t)?(await f(e,void 0,t)).content:(await d({model:t?.model??r,messages:e,temperature:t?.temperature??0,max_tokens:t?.maxTokens??4096},{...t})).choices?.[0]?.message?.content??``},async chatJson(e,t){let n=await this.chat(e,t);try{return CT(n)}catch{let r=await this.chat([...e,{role:`assistant`,content:n},{role:`user`,content:`IMPORTANT: Your previous response was not valid JSON. Respond with ONLY a valid JSON object, no other text.`}],t);try{return CT(r)}catch(e){throw new mw(`parse`,`LLM returned invalid JSON twice: ${r.slice(0,120)}`,{cause:e})}}},async chatWithTools(e,t,n){if(p(n))return f(e,t,n);let i=(await d({model:n?.model??r,messages:e.map(XE),tools:t,temperature:0,max_tokens:4096},{...n,stage:n?.stage??`agent`})).choices?.[0]?.message;return{content:i?.content??``,toolCalls:i?.tool_calls??[]}}}}function qE(e,t,n){let r=e&&typeof e==`object`?e:{},i=r.error&&typeof r.error==`object`?r.error:r,a=typeof i.code==`string`?i.code:void 0;return new mw(t?hw(t):/invalid.?api.?key|unauthorized|accessdenied|forbidden/i.test(a??``)?`auth`:/quota|throttl|rate.?limit/i.test(a??``)?`rate_limit`:`http`,`LLM request failed: ${typeof i.message==`string`?i.message:typeof r.error==`string`?r.error:`服务端错误`}`,{status:t,code:a,requestId:typeof r.request_id==`string`?r.request_id:n})}function JE(e){if(e&&e!==`stop`&&e!==`tool_calls`)throw new mw(`parse`,`LLM 响应未完整结束: ${e}`)}function YE(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(!n.id||t.has(n.id)||!n.function?.name||n.type!==`function`)throw new mw(`parse`,`工具调用缺少标识或标识重复`);t.add(n.id);let e;try{e=JSON.parse(n.function.arguments)}catch(e){throw new mw(`parse`,`工具参数不完整`,{cause:e})}if(!e||typeof e!=`object`||Array.isArray(e))throw new mw(`parse`,`工具参数必须是 JSON 对象`)}}function XE(e){let t={role:e.role,content:e.content};return e.tool_call_id&&(t.tool_call_id=e.tool_call_id),e.tool_calls&&(t.tool_calls=e.tool_calls),t}function ZE(){return T(Ft(),`skills/bailian-docs-llm-wiki`,`models`)}const QE=/-\d{4}-\d{2}-\d{2}$/;let $E=null,eD=null;function tD(e){if(!S(e))return[];let t=[];for(let n of he(e,`utf-8`).split(`
|
|
282
|
+
`))if(n.trim())try{t.push(JSON.parse(n))}catch{}return t}function nD(e){let t=new Set(e.map(({model:e})=>e));return e.filter(({model:e})=>{let n=e.replace(QE,``);return n===e||!t.has(n)})}async function rD(e=ZE()){if($E)return $E;let t=tD(T(e,`models.jsonl`));if(t.length===0)throw Error(`No model catalog found at ${T(e,`models.jsonl`)}. Run any bl advisor/agent command once to sync wiki data.`);return $E=nD(t),$E}async function iD(e=ZE()){if(eD)return eD;let t=tD(T(e,`families.jsonl`));return eD=new Map(t.map(e=>[e.slug,e])),eD}function aD(){$E=null,eD=null}function oD(){return{async ask({question:e,options:t,defaultIfSkip:n,signal:r}){$(r);let i=Ve({input:process.stdin,output:process.stderr});try{for(process.stderr.write(`\n${e}\n`),t.forEach((e,t)=>{let r=e===n;process.stderr.write(` ${t+1}. ${e}${r?` (default)`:``}\n`)}),process.stderr.write(` 输入序号选择,回车使用默认,或直接输入文字描述你的需求
|
|
283
|
+
`);;){let e=(await i.question(`Select: `,{signal:r})).trim();if($(r),!e)return n;if(/^\d+$/.test(e)){let n=Number.parseInt(e,10)-1;if(n>=0&&n<t.length)return t[n];process.stderr.write(` 请输入 1-${t.length} 之间的序号,或直接输入文字描述\n`);continue}return e}}finally{i.close()}}}}function sD(){return{async ask({question:e,defaultIfSkip:t,signal:n}){return $(n),process.stderr.write(`[recommend] non-interactive, "${e}" → default: ${t}\n`),t}}}function cD(){return T(Ft(),`skills`)}function lD(){return T(cD(),`skill-lock.json`)}function uD(){return{version:1,skills:{}}}function dD(){let e=lD();if(!S(e))return uD();try{let t=JSON.parse(he(e,`utf-8`));return t?.version!==1||typeof t.skills!=`object`||t.skills===null?uD():t}catch{return uD()}}function fD(e){me(cD(),{recursive:!0}),xe(lD(),JSON.stringify(e,null,2)+`
|
|
284
|
+
`)}function pD(e,t){let n=dD();n.skills[e]={...n.skills[e],...t},fD(n)}const mD=`BL_SKIP_HOST_AGENTS`,hD=[`CLAUDE_CONFIG_DIR`,`CODEX_HOME`,`VIBE_HOME`,`HERMES_HOME`,`AUTOHAND_HOME`,`GROK_HOME`,`DSH_HOME`,`OPENCLAW_CONFIG_PATH`,`ZCODE_HOME`,`APPDATA`,`LOCALAPPDATA`,`FLATPAK_XDG_CONFIG_HOME`,`PI_CODING_AGENT_DIR`];function gD(){let e=He(),t=process.cwd(),n=process.env.XDG_CONFIG_HOME||T(e,`.config`),r=(t,n,r)=>({id:t,displayName:n,skillsDir:T(e,r,`skills`),detectDirs:[T(e,r)]}),i=(t,n)=>t?.trim()||T(e,n),a=(e,t,n)=>({id:e,displayName:t,skillsDir:T(n,`skills`),detectDirs:[n]}),o=[`.openclaw`,`.clawdbot`,`.moltbot`].map(t=>T(e,t)),s=o.find(e=>S(e))??o[0],c=[T(n,`zed`)],l=process.env.APPDATA?.trim();l&&c.push(T(l,`Zed`));let u=process.env.FLATPAK_XDG_CONFIG_HOME?.trim();u&&c.push(T(u,`zed`));let d=i(process.env.CODEX_HOME,`.codex`);return[{id:`universal`,displayName:`Universal (~/.agents/skills)`,skillsDir:T(e,`.agents`,`skills`),detectDirs:[T(e,`.agents`),T(e,`.cline`),T(e,`.dexto`),T(e,`.firebender`),T(e,`.kimi-code`),T(e,`.kimi`),T(e,`.loaf`),T(e,`.warp`),...c]},{id:`universal-xdg`,displayName:`Universal (XDG agents/skills)`,skillsDir:T(n,`agents`,`skills`),detectDirs:[T(n,`agents`),T(n,`amp`),T(t,`.replit`)]},r(`adal`,`AdaL`,`.adal`),r(`aider-desk`,`AiderDesk`,`.aider-desk`),r(`antigravity`,`Antigravity`,`.gemini/antigravity`),r(`antigravity-cli`,`Antigravity CLI`,`.gemini/antigravity-cli`),{id:`astrbot`,displayName:`AstrBot`,skillsDir:T(e,`.astrbot`,`data`,`skills`),detectDirs:[T(t,`data`,`skills`),T(e,`.astrbot`)]},a(`autohand-code`,`Autohand Code CLI`,i(process.env.AUTOHAND_HOME,`.autohand`)),r(`augment`,`Augment`,`.augment`),r(`bob`,`IBM Bob`,`.bob`),a(`claude-code`,`Claude Code`,i(process.env.CLAUDE_CONFIG_DIR,`.claude`)),r(`codearts-agent`,`CodeArts Agent`,`.codeartsdoer`),{id:`codebuddy`,displayName:`CodeBuddy`,skillsDir:T(e,`.codebuddy`,`skills`),detectDirs:[T(t,`.codebuddy`),T(e,`.codebuddy`)]},r(`codemaker`,`Codemaker`,`.codemaker`),r(`codestudio`,`Code Studio`,`.codestudio`),{id:`codex`,displayName:`Codex`,skillsDir:T(d,`skills`),detectDirs:[d,`/etc/codex`]},r(`command-code`,`Command Code`,`.commandcode`),{id:`continue`,displayName:`Continue`,skillsDir:T(e,`.continue`,`skills`),detectDirs:[T(t,`.continue`),T(e,`.continue`)]},r(`cortex`,`Cortex Code`,`.snowflake/cortex`),r(`crush`,`Crush`,`.config/crush`),r(`cursor`,`Cursor`,`.cursor`),{id:`deepagents`,displayName:`Deep Agents`,skillsDir:T(e,`.deepagents`,`agent`,`skills`),detectDirs:[T(e,`.deepagents`)]},{id:`devin`,displayName:`Devin for Terminal`,skillsDir:T(n,`devin`,`skills`),detectDirs:[T(n,`devin`)]},r(`droid`,`Droid`,`.factory`),a(`dsh`,`DeepSeek DSH`,i(process.env.DSH_HOME,`.dsh`)),r(`forgecode`,`ForgeCode`,`.forge`),r(`gemini-cli`,`Gemini CLI`,`.gemini`),r(`github-copilot`,`GitHub Copilot`,`.copilot`),{id:`goose`,displayName:`Goose`,skillsDir:T(n,`goose`,`skills`),detectDirs:[T(n,`goose`)]},a(`grok`,`Grok Build`,i(process.env.GROK_HOME,`.grok`)),a(`hermes`,`Hermes Agent`,OC(e)),r(`iflow-cli`,`iFlow CLI`,`.iflow`),r(`inference-sh`,`inference.sh`,`.inferencesh`),{id:`jazz`,displayName:`Jazz`,skillsDir:T(e,`.jazz`,`skills`),detectDirs:[T(e,`.jazz`),T(t,`.jazz`)]},r(`junie`,`Junie`,`.junie`),r(`kilo`,`Kilo Code`,`.kilocode`),{id:`kimchi`,displayName:`Kimchi`,skillsDir:T(e,`.config`,`kimchi`,`harness`,`skills`),detectDirs:[T(e,`.config`,`kimchi`)]},r(`kiro-cli`,`Kiro CLI`,`.kiro`),r(`kode`,`Kode`,`.kode`),r(`lingma`,`Lingma`,`.lingma`),r(`mcpjam`,`MCPJam`,`.mcpjam`),{id:`minimax-code`,displayName:`MiniMax Code`,skillsDir:T(e,`.minimax`,`skills`),detectDirs:[T(e,`.minimax`),`/Applications/MiniMax Code.app`]},a(`mistral-vibe`,`Mistral Vibe`,i(process.env.VIBE_HOME,`.vibe`)),r(`moxby`,`Moxby`,`.moxby`),r(`mux`,`Mux`,`.mux`),r(`neovate`,`Neovate`,`.neovate`),{id:`opencode`,displayName:`OpenCode`,skillsDir:T(n,`opencode`,`skills`),detectDirs:[T(n,`opencode`)]},{id:`openclaw`,displayName:`OpenClaw`,skillsDir:T(s,`skills`),detectDirs:o},r(`openhands`,`OpenHands`,`.openhands`),r(`ona`,`Ona`,`.ona`),r(`pi`,`Pi`,`.pi/agent`),r(`pochi`,`Pochi`,`.pochi`),r(`qoder`,`Qoder`,`.qoder`),r(`qoder-cn`,`Qoder CN`,`.qoder-cn`),r(`qwen-code`,`Qwen Code`,`.qwen`),r(`reasonix`,`Reasonix`,`.reasonix`),r(`rovodev`,`Rovo Dev`,`.rovodev`),r(`roo`,`Roo Code`,`.roo`),{id:`tabnine-cli`,displayName:`Tabnine CLI`,skillsDir:T(e,`.tabnine`,`agent`,`skills`),detectDirs:[T(e,`.tabnine`)]},r(`terramind`,`Terramind`,`.terramind`),r(`tinycloud`,`Tinycloud`,`.tinycloud`),r(`trae`,`Trae`,`.trae`),r(`trae-cli`,`Trae CLI`,`.traecli`),r(`trae-cn`,`Trae CN`,`.trae-cn`),r(`windsurf`,`Windsurf`,`.codeium/windsurf`),r(`workbuddy`,`Tencent WorkBuddy`,`.workbuddy`),{id:`zcode`,displayName:`ZCode`,skillsDir:T(e,`.zcode`,`skills`),detectDirs:[T(e,`.zcode`),`/Applications/ZCode.app`]},r(`zencoder`,`Zencoder`,`.zencoder`)]}function _D(e){let t=Oe(e);try{return ve(t)}catch{let e=[],n=t;for(;n!==Te(n);){if(S(n))try{return T(ve(n),...e.reverse())}catch{break}e.push(we(n)),n=Te(n)}return t}}function vD(e,t){let n=_D(e),r=_D(t);return n===r||n.startsWith(r+ke)}function yD(e){if(!Ee(e)||vD(e,He()))return!1;let t=process.env.XDG_CONFIG_HOME?.trim();return!(t&&vD(e,t))}function bD(e){return process.env.BL_SKIP_HOST_AGENTS!==`1`||!yD(e)}function xD(){return gD().filter(e=>e.detectDirs.some(e=>bD(e)&&S(e)))}function SD(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function CD(e){let t=cD();if(process.platform===`win32`){let n=e.toLowerCase(),r=t.toLowerCase();return n===r||n.startsWith(r+ke)}return e===t||e.startsWith(t+ke)}function wD(e){try{if(!pe(e).isSymbolicLink())return!1;let t=_e(e);return CD(Ee(t)?t:Oe(Te(e),t))}catch{return!1}}function TD(e,t){if(!t.some(t=>SD(t,e)))return!1;try{return pe(e).isDirectory()}catch{return!1}}function ED(e){try{return pe(e).isDirectory()?S(T(e,`SKILL.md`)):!1}catch{return!1}}const DD=`existing file/dir not managed by bl skill`;function OD(e,t=xD(),n=[]){let r=T(cD(),e),i=[];for(let a of t){let t=T(a.skillsDir,e);try{let e=!1;try{pe(t),e=!0}catch{}if(e){if(wD(t))w(t);else if(TD(t,n))w(t,{recursive:!0,force:!0});else if(ED(t))w(t,{recursive:!0,force:!0});else{i.push({agent:a.id,path:t,mode:`skipped`,reason:DD});continue}}me(a.skillsDir,{recursive:!0});try{be(r,t,process.platform===`win32`?`junction`:`dir`),i.push({agent:a.id,path:t,mode:`symlink`})}catch{ue(r,t,{recursive:!0}),i.push({agent:a.id,path:t,mode:`copy`})}}catch(e){i.push({agent:a.id,path:t,mode:`skipped`,reason:e instanceof Error?e.message:String(e)})}}return i}function kD(e,t=xD(),n=[]){let r=OD(e,t,n),i=r.filter(e=>e.mode!==`skipped`),a=i.map(e=>e.path),o=r.filter(e=>e.mode===`skipped`&&e.reason===DD).map(e=>e.path),s=n.filter(e=>!a.some(t=>SD(t,e))&&!o.some(t=>SD(t,e)));return{results:r,linkedAgents:i.map(e=>e.agent),links:[...a,...s]}}function AD(e,t=[]){let n=[],r=new Set(t);for(let t of gD())r.add(T(t.skillsDir,e));for(let e of r)try{let r;try{r=pe(e)}catch{continue}r.isSymbolicLink()?wD(e)&&n.push(e):t.some(t=>SD(t,e))&&n.push(e)}catch{}return n}function jD(e,t=[]){let n=[];for(let r of AD(e,t))try{if(wD(r))w(r);else if(!pe(r).isSymbolicLink()&&t.some(e=>SD(e,r)))w(r,{recursive:!0,force:!0});else continue;n.push(r)}catch{}return n}function MD(e){return e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)?!1:!e.split(`/`).includes(`..`)}async function ND(e,t){let n=Ge.extract();n.on(`entry`,(e,r,i)=>{if(!MD(e.name)){r.on(`error`,()=>{}),r.resume(),n.destroy(/* @__PURE__ */ Error(`unsafe tar entry: ${e.name}`));return}let a=T(t,e.name);if(e.type===`directory`){me(a,{recursive:!0}),r.resume(),r.on(`end`,i);return}me(Te(a),{recursive:!0});let o=fe(a);r.pipe(o),o.on(`finish`,i),o.on(`error`,i)}),await Ue(Ce.from(e),We(),n)}function PD(e){let t=[],n=r=>{for(let i of ge(r?T(e,r):e,{withFileTypes:!0})){let e=r?`${r}/${i.name}`:i.name;i.isDirectory()?n(e):i.isFile()&&t.push(e)}};n(``),t.sort((e,t)=>e<t?-1:+(e>t));let r=Re(`sha256`);for(let n of t)r.update(n),r.update(he(T(e,n)));return`sha256:${r.digest(`hex`)}`}function FD(e,t,n=259){let r,i=a=>{for(let o of ge(a,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let s=T(a,o.name),c=De(e,s);for(let e of t){let t=T(e,c).length;t>n&&t>(r?.pathLength??0)&&(r={root:e,relativePath:c,pathLength:t})}o.isDirectory()&&i(s)}};for(let e of t)e.length>n&&e.length>(r?.pathLength??0)&&(r={root:e,relativePath:``,pathLength:e.length});return i(e),r}function ID(e){let t=[],n=r=>{for(let i of ge(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let a=T(r,i.name),o=De(e,a);i.isDirectory()?(t.push({relativePath:o,type:`directory`}),n(a)):i.isFile()&&t.push({relativePath:o,type:`file`})}};return n(e),t}function LD(e,t){let n=ID(e),r=new Set(n.map(e=>e.relativePath));me(t,{recursive:!0});for(let r of n){let n=T(e,r.relativePath),i=T(t,r.relativePath);if(S(i)){let e=pe(i);(!(r.type===`directory`?e.isDirectory():e.isFile())||e.isSymbolicLink())&&w(i,{recursive:!0,force:!0})}r.type===`directory`?me(i,{recursive:!0}):(me(Te(i),{recursive:!0}),le(n,i))}let i=ID(t).filter(e=>!r.has(e.relativePath)).sort((e,t)=>t.relativePath.length-e.relativePath.length);for(let e of i)w(T(t,e.relativePath),{recursive:!0,force:!0})}function RD(e){let t=e?.code;return t===`EPERM`||t===`EBUSY`}function zD(e){try{S(e)&&w(e,{recursive:!0,force:!0})}catch{}}function BD(e,t,n={}){me(Te(t),{recursive:!0});let r=`${t}.old-${Date.now()}`;if(S(t))try{C(t,r)}catch(i){if(!(n.allowInPlaceFallback??process.platform===`win32`)||!RD(i))throw i;try{LD(t,r),LD(e,t),zD(r);return}catch(e){try{S(r)&&LD(r,t)}catch{}throw Error(`Skill directory is in use and could not be updated in place. Close running agent hosts and retry. / Skill 目录正被占用,无法原地更新;请关闭正在运行的 Agent 后重试。 ${e instanceof Error?e.message:String(e)}`,{cause:e})}}try{C(e,t)}catch(e){throw S(r)&&!S(t)&&C(r,t),e}zD(r)}function VD(e){if(e instanceof O){let t=e.api?.httpStatus;if(t!==void 0){if(t===408||t===429)return!0;if(t>=400&&t<500)return!1}return!0}return!0}function HD(e){return e instanceof O&&e.api?.httpStatus===429}function UD(e,t){return Math.min(t*2**(e-1),1e4)}function WD(e){return new Promise(t=>setTimeout(t,e))}async function GD(e,t=3){let n=typeof t==`number`?{attempts:t}:t,r=n.attempts??3,i=n.shouldRetry??VD,a=n.backoffBaseMs??500,o;for(let t=1;t<=r;t++)try{return await e(t)}catch(e){if(o=e,t>=r||!i(e,t))break;HD(e)&&await WD(UD(t,a))}throw o}function KD(){return(process.env.BAILIAN_SKILL_REGISTRY_URL?.trim()||`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/skills`).replace(/\/+$/,``)}async function qD(e=3e4,t=3){return GD(async()=>{let t=`${KD()}/index.json`,n;try{n=await Sn.fetch(t,{signal:AbortSignal.timeout(e)})}catch(e){throw new O(`Cannot access skill registry: ${t}`,D.NETWORK,`Check network connectivity; if using a private mirror, verify BAILIAN_SKILL_REGISTRY_URL configuration`,{cause:e})}if(!n.ok)throw new O(`Skill registry returned HTTP ${n.status}: ${t}`,D.NETWORK,n.status===404?`Skill index not yet published or registry URL is incorrect; confirm the publisher has generated index.json`:`Remote error, retry later`);let r;try{r=await n.json()}catch(e){throw new O(`Skill index index.json is not valid JSON`,D.GENERAL,`Remote may be in the middle of publishing, retry later`,{cause:e})}let i=r;if(typeof i!=`object`||!i||typeof i.skills!=`object`||i.skills===null)throw new O(`Skill index index.json has invalid structure`,D.GENERAL,`Retry later or contact the publisher`);return i},{attempts:t})}const JD=/^sha256-[0-9a-f]{64}\.tar\.br$/;function YD(e){let t=e?.object;return t&&JD.test(t)?t:`skill.tar.br`}async function XD(e,t,n=3){return GD(async()=>{let n=`${KD()}/${e}/${YD(t)}`,r;try{r=await Sn.fetch(n,{signal:AbortSignal.timeout(12e4)})}catch(t){throw new O(`Failed to download skill ${e}: ${n}`,D.NETWORK,`Network error, retryable`,{cause:t})}if(!r.ok)throw new O(`Failed to download skill ${e}: HTTP ${r.status}`,D.NETWORK,r.status===404?`index.json and skill object are temporarily inconsistent (publishing in progress), retry later`:`Remote error, retry later`);return Buffer.from(await r.arrayBuffer())},{attempts:n})}function ZD(e){return e.replace(/[\\/:*?"<>|\s]+/g,`-`).replace(/\.\.+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`unnamed-skill`}function QD(e){return e.length>0&&ZD(e)===e}function $D(e,t){throw new O(`Skill ${e} validation failed: ${t}`,D.GENERAL,`This skill package does not conform to the SKILL.md spec; contact the skill publisher to fix and republish`)}function eO(e){if(!e.startsWith(`---`))return null;let t=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(e);return t?t[1]:null}function tO(e,t){let n=T(e,`SKILL.md`),r;try{ye(n).isFile()||$D(t,`SKILL.md is not a regular file`),r=he(n,`utf-8`)}catch(e){if(e instanceof O)throw e;$D(t,`missing SKILL.md`)}let i=eO(r);i===null&&$D(t,`SKILL.md is missing frontmatter (--- delimited YAML header)`);let a;try{a=_(i)}catch{$D(t,`frontmatter is not valid YAML`)}(typeof a!=`object`||!a)&&$D(t,`frontmatter is not a key-value structure`);let o=a,s=typeof o.name==`string`?o.name.trim():``,c=typeof o.description==`string`?o.description.trim():``;return(!s||!c)&&$D(t,`frontmatter is missing non-empty name / description fields`),{name:s,description:c}}function nO(e){if(!QD(e))throw new O(`Invalid skill name: ${e}`,D.GENERAL,`Skill name contains path separators, traversal sequences, or other illegal characters; refusing to write to disk`)}async function rO(e,t,n,r){nO(e);let i=cD(),a=T(i,e),o=T(i,`.tmp-${e}-${process.pid}-${Date.now()}`);try{me(o,{recursive:!0}),await ND(t,o);let i=FD(o,r??(process.platform===`win32`?[a]:[]));if(i)throw new O(`Skill ${e} contains a Windows-incompatible path (${i.pathLength} characters): ${i.relativePath}`,D.GENERAL,`The skill package must shorten this path before it can be installed safely on Windows. / Skill 包必须缩短该路径后才能在 Windows 上安全安装。`);if(n?.startsWith(`sha256:`)){let t=PD(o);if(t!==n)throw new O(`Skill ${e} failed integrity check: index says ${n}, archive is ${t}`,D.GENERAL,`Downloaded archive does not match the index fingerprint (registry may be mid-publish); retry later`)}let s=tO(o,e);return BD(o,a),{name:e,path:a,meta:s}}finally{try{S(o)&&w(o,{recursive:!0,force:!0})}catch{}}}async function iO(e,t,n,r){if(t.compression&&t.compression!==`tar.br`)throw new O(`Skill ${e} uses unsupported compression format: ${t.compression}`,D.GENERAL,`Upgrade bailian-cli to the latest version and retry`);return rO(e,await XD(e,t,n),t.contentHash,r)}function aO(e){nO(e);let t=T(cD(),e);return S(t)?(w(t,{recursive:!0,force:!0}),!0):!1}function oO(e,t){return{...e.contentHash?{contentHash:e.contentHash}:{},...e.publishedAt?{publishedAt:e.publishedAt}:{},installedAt:(/* @__PURE__ */ new Date()).toISOString(),sourceType:`oss`,...e.description?{description:e.description}:{},links:t}}async function sO(e,t,n=xD(),r=[],i){await iO(e,t,i,process.platform===`win32`?[T(cD(),e),...n.map(t=>T(t.skillsDir,e))]:void 0);let a=kD(e,n,r);return{lockEntry:oO(t,a.links),linkedAgents:a.linkedAgents}}const cO=`bailian-docs-llm-wiki`;function lO(){return T(Ft(),`skills/bailian-docs-llm-wiki`)}function uO(){return S(T(lO(),`models`,`models.jsonl`))}function dO(){return T(Ft(),`wiki-sync-state.json`)}function fO(){try{return JSON.parse(he(dO(),`utf-8`))}catch{return null}}function pO(e){try{xe(dO(),JSON.stringify(e))}catch{}}function mO(e){try{pD(cO,e)}catch{}}function hO(e){try{let t=dD().skills[cO];return t?.contentHash!==e||!Array.isArray(t.links)}catch{return!0}}async function gO(){try{return(await qD(3e3,1)).skills[cO]??null}catch{return null}}async function _O(){let e=fO(),t=Date.now();if(e&&t-e.lastChecked<432e5&&uO())return!1;let n=await gO();if(!n?.contentHash)return!1;if(uO()&&(!e||e.contentHash===n.contentHash)){if(pO({lastChecked:t,contentHash:n.contentHash}),hO(n.contentHash)){let e=dD().skills[cO]?.links??[];mO(oO(n,kD(cO,xD(),e).links))}return!1}try{let e=dD().skills[cO]?.links??[];mO((await sO(cO,n,xD(),e,1)).lockEntry)}catch{return!1}return pO({lastChecked:t,contentHash:n.contentHash}),!0}const vO={Text:`Text`,Image:`Image`,Video:`Video`,Audio:`Audio`},yO={Single:`single`,Pipeline:`pipeline`},bO={Low:`low`,Medium:`medium`,High:`high`},xO={Standard:`standard`,Large:`large`,ExtraLarge:`extra-large`},SO={Flagship:`flagship`,Balanced:`balanced`,CostOptimized:`cost-optimized`},CO={TG:`TG`,Reasoning:`Reasoning`,VU:`VU`,IG:`IG`,VG:`VG`,TTS:`TTS`,ASR:`ASR`,RealtimeASR:`Realtime-ASR`,RealtimeTTS:`Realtime-Text-to-Speech`,RealtimeAudioTranslate:`Realtime-Audio-Translate`,RealtimeOmni:`Realtime-Omni`,MultimodalOmni:`Multimodal-Omni`,ME:`ME`,TR:`TR`,ThreeDGeneration:`3D-generation`},wO={FunctionCalling:`function-calling`,WebSearch:`web-search`,StructuredOutputs:`structured-outputs`,PrefixCompletion:`prefix-completion`},TO={Flagship:`Flagship`,CostOptimized:`Cost-optimized`},EO=`bailian-cli`,DO=`install-method`,OO=/* @__PURE__ */ new Set([`binary`,`npm`,`brew`,`winget`,`unknown`]);function kO(e){return e?T(Ft(),`${DO}.${e}`):T(Ft(),DO)}function AO(){if(process.env.BAILIAN_COMPILED===`1`)return!0;let e=process.execPath.replaceAll(`\\`,`/`);return/(^|\/)node(\.exe)?$/i.test(e)||e.includes(`/node/`)||/(^|\/)bun(\.exe)?$/i.test(e)||e.includes(`/.bun/`)?!1:/\/(bl|bailian)(\.exe)?$/i.test(e)}function jO(e){if(!e)return null;let t=e.trim().toLowerCase();return OO.has(t)?t:null}function MO(e){try{return jO(he(e,`utf-8`).split(`
|
|
285
|
+
`)[0])}catch{return null}}function NO(){let e=jO(process.env.BAILIAN_INSTALL_METHOD);if(e)return e;if(AO()){let e=process.execPath.replaceAll(`\\`,`/`);return e.includes(`/Cellar/`)||e.includes(`/homebrew/`)?`brew`:`binary`}return`npm`}function PO(e){let t=jO(process.env.BAILIAN_INSTALL_METHOD);if(t)return t;if(e?.clientName){let t=MO(kO(e.clientName));if(t)return t;if(e.clientName===`bailian-cli`){let e=MO(kO());if(e)return e}return NO()}return MO(kO())||NO()}function FO(e){let t=PO(e);return t===`binary`&&e.npmPackage!==`bailian-cli`?`npm`:t}function IO(e,t={clientName:EO}){try{let n=Ft();S(n)||me(n,{recursive:!0,mode:448}),xe(kO(t.clientName),`${e}\n`,{mode:384}),t.clientName===`bailian-cli`&&xe(kO(),`${e}\n`,{mode:384})}catch{}}const LO=`https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release`,RO=`https://github.com/modelstudioai/cli/releases`,zO=`https://bailian.aliyun.com/cli/install.sh`,BO=`https://bailian.aliyun.com/cli/install.ps1`;function VO(){let e=process.env.BAILIAN_CLI_CDN?.trim();return e?e.replace(/\/$/,``):LO}function HO(e=`latest`){let t=e.trim();return!t||t===`latest`||t===`stable`?`${VO()}/manifest.json`:`${VO()}/${t}.json`}function UO(e,t){let n=e.startsWith(`v`)?e:`v${e}`;return`${VO()}/${n}/${t}`}function WO(){let e=process.platform,t=process.arch,n;if(e===`darwin`)n=`darwin`;else if(e===`linux`)n=`linux`;else if(e===`win32`)n=`windows`;else throw Error(`Unsupported platform for binary updates: ${e}`);let r;if(t===`arm64`)r=`arm64`;else if(t===`x64`)r=`x64`;else throw Error(`Unsupported architecture for binary updates: ${t}`);if(n===`windows`&&r===`arm64`)throw Error(`windows arm64 is not supported for binary updates; use: npm install -g bailian-cli`);return{os:n,arch:r,fileSuffix:e===`win32`?`.exe`:``}}function GO(e,t,n,r=!1){return`bl-${e}-${t}-${n}.zip`}function KO(e,t,n){if(t!==`windows`)return`bl-${e}-${t}-${n}.tar.gz`}function qO(e,t,n,r=!1){return`bl-${e}-${t}-${n}${r?`.exe`:``}`}function JO(e){return new Promise((t,n)=>{ce.open(e,{lazyEntries:!0},(r,i)=>{if(r||!i){n(r??/* @__PURE__ */ Error(`Failed to open zip: ${e}`));return}t(i)})})}function YO(e){let t=e.replace(/\\/g,`/`);return t.includes(`/`)?t.slice(t.lastIndexOf(`/`)+1):t}async function XO(e,t,n){let r=await JO(e);return new Promise((i,a)=>{let o=!1,s=e=>{if(!o){o=!0;try{r.close()}catch{}a(e instanceof Error?e:Error(String(e)))}},c=e=>{if(!o){o=!0;try{r.close()}catch{}i(e)}};r.on(`error`,s),r.on(`end`,()=>{o||s(/* @__PURE__ */ Error(n?`Zip entry not found: ${n} in ${e}`:`Zip has no file entries: ${e}`))}),r.on(`entry`,e=>{if(o)return;let i=e.fileName.replace(/\\/g,`/`);if(i.endsWith(`/`)){r.readEntry();return}let a=YO(i);if(n&&i!==n&&a!==n){r.readEntry();return}r.openReadStream(e,(n,r)=>{if(n||!r){s(n??/* @__PURE__ */ Error(`Failed to read zip entry: ${e.fileName}`));return}(async()=>{try{await Ne(Te(t),{recursive:!0}),await Ue(r,fe(t)),c(a)}catch(e){s(e)}})()})}),r.readEntry()})}function ZO(e,t){let n=(e??(t?`all`:``)).trim();if(!n)throw new rt(`--name cannot be empty`,`Use --name all or --name skill-a,skill-b`);let r=[...new Set(n.split(`,`).map(e=>e.trim()).filter(Boolean))];if(r.includes(`all`)){if(r.length>1)throw new rt(`--name all cannot be mixed with specific skill names`,`Use either all or a comma-separated list of names`);return`all`}return r}function QO(){let e=cD();return S(e)?ge(e).filter(t=>{if(t.startsWith(`.`)||t.includes(`.tmp-`)||t.includes(`.old-`))return!1;try{return ye(T(e,t)).isDirectory()}catch{return!1}}):[]}function $O(e,t,n){let r=new Set(n),i=/* @__PURE__ */ new Set,a=[];for(let[n,o]of Object.entries(e.skills)){i.add(n);let e=t.skills[n];if(e){let t=r.has(n)?e.contentHash===o.contentHash?`installed`:`outdated`:`missing`;a.push({name:n,status:t,publishedAt:o.publishedAt,description:o.description})}else r.has(n)?a.push({name:n,status:`untracked`,publishedAt:o.publishedAt,description:o.description}):a.push({name:n,status:`not-installed`,publishedAt:o.publishedAt,description:o.description})}for(let[e,n]of Object.entries(t.skills))i.has(e)||(i.add(e),a.push({name:e,status:r.has(e)?`installed`:`missing`,publishedAt:n.publishedAt,description:n.description}));for(let e of n)i.has(e)||a.push({name:e,status:`untracked`});return a.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}export{hD as AGENT_ENV_KEYS,pv as AIGC_MCP_SERVER,mv as AIGC_MCP_TOOL,_t as API_KEY_CAPABILITY_PATTERN,yC as ASYNC_FLAG,dt as BAILIAN_HOST,ix as BATCH_CSV_COLUMNS,Fb as BATCH_ENDPOINTS,Ib as BATCH_STATUSES,Lb as BATCH_TERMINAL,MS as BILLING_METHOD,EO as BINARY_PRODUCT_CLIENT_NAME,O as BailianError,qb as BatchValidator,bO as Budgets,cS as CALC_DATASETS_TOKENS_API,kn as CHANNEL,PS as CHARGE_TYPE,TC as COMMAND_PACK_API_VERSION,vC as CONCURRENT_FLAG,mt as CONFIG_FILE_KEYS,xC as CONSOLE_AUTH_FLAGS,CO as Capabilities,Vh as Client,yO as Complexities,xO as ContextNeeds,at as CredentialError,Mn as DASHSCOPE_SERVICE_HEADER,Ty as DECISION_QUESTION_TYPES,px as DECISION_REGIONS,NS as DEFAULT_BILLING_METHOD,LO as DEFAULT_CLI_CDN_BASE,fx as DEFAULT_DECISION_MODEL,mx as DEFAULT_DECISION_REGION,AS as DEFAULT_DEPLOY_PLAN,BO as DEFAULT_INSTALL_PS1_URL,zO as DEFAULT_INSTALL_SCRIPT_URL,pt as DEFAULT_LANGUAGE,GE as DEFAULT_LLM_MODEL,zx as DEFAULT_TRAINING_TYPE,qS as DEPLOY_LIST_INDEPENDENT_API,kS as DEPLOY_PLAN,GS as DEPLOY_START_API,KS as DEPLOY_STOP_API,ut as DOCS_HOSTS,lS as ESTIMATE_FINETUNE_TOKENS_API,D as ExitCode,wO as Features,RO as GITHUB_RELEASES_BASE,_C as GLOBAL_FLAGS,Gx as INSUFFICIENT_SAMPLES_CODE,nC as LIST_SUPPORT_IMPORT_MODELS_API,mw as LLMError,Rb as MAX_BATCH_BYTES,zb as MAX_BATCH_LINE_BYTES,Bb as MAX_BATCH_RECORDS,oy as MAX_CPT_BYTES,ay as MAX_DATASET_BYTES,Ey as MAX_DECISION_CHOICE_OPTIONS,sy as MAX_DECISION_DATASET_BYTES,Oy as MAX_DECISION_SCORE_LEVELS,cy as MAX_MEDIA_ZIP_BYTES,An as MCP_CALL_SERVICE,Cv as MCP_IMAGE_GEN_RATIO_SIZES,Tv as MCP_TTS_VOICES,Dy as MIN_DECISION_SCORE_LEVELS,bC as MODEL_AUTH_FLAGS,Iv as MODEL_LIST_API,kh as McpClient,vO as Modalities,TO as ModelCategories,SC as OPENAPI_AUTH_FLAGS,jn as OPEN_API_SOURCE,Lv as PREDICT_CONFIG_API,SO as QualityPreferences,x_ as RAG_PATHS,VE as RECOMMEND_TOOLS,lt as REGIONS,g_ as SANDBOX_PATHS,mD as SKIP_HOST_AGENTS_ENV,oC as SPEECH_BIASING_MODEL,US as STRATEGIES,ft as SUPPORTED_LANGUAGES,sS as TRAINING_MODEL_PRICE_API,Rx as TRAINING_TYPES_CLI,Lx as TRAINING_TYPE_MAP,rt as UsageError,on as activateConfigProfile,WE as agentLoop,f_ as agentStudioFilesPath,Mg as agentStudioHost,Dw as analyzeEngineIntent,En as anonymousConsoleCall,mg as appCompletionPath,BD as atomicSwap,rr as audioFileToDataUri,Fh as bailianMcpPath,Ih as bailianMcpSsePath,Wb as batchChunks,dx as batchDataNotes,ux as batchExamples,Vb as batchIoError,Gb as batchLines,Hb as batchObject,Q as batchUsage,GO as binaryAssetFileName,qO as binaryInnerFileName,KO as binaryTarFileName,Hn as buildAcsCanonicalQuery,G_ as buildAsrContextMessages,q_ as buildAsrFlashRequest,K_ as buildAsyncAsrLanguageFields,Zv as buildCommandInvocation,BE as buildEngineInput,_v as buildImageEditArgs,gv as buildImageGenArgs,yv as buildImageToVideoArgs,un as buildOutputSettings,zS as buildPrepaidInfo,IS as buildReservationCapacity,dn as buildSettings,oO as buildSkillLockEntry,ln as buildSources,Sv as buildSpeechToTextArgs,vv as buildTextToVideoArgs,xv as buildTtsArgs,bv as buildVideoFetchArgs,sC as buildVocabularyRequest,On as callConsoleGateway,Qb as cancelBatch,Fx as cancelCompressJob,wx as cancelFineTune,HO as channelManifestUrl,Zh as chatPath,Y_ as collectAsrTranscriptionItems,$v as commandRef,PD as computeDirContentHash,$O as computeSkillStatuses,zh as connectBailianMcpWithFallback,uv as createBailianControlUser,Xb as createBatch,bS as createCapacityInstance,jx as createCompressJob,QS as createCustomModelImport,mS as createDeployment,xx as createFineTune,ov as createInstrumentedFetch,KE as createLLMClient,sD as createNonInteractive,oD as createReadlineInteraction,zE as createSession,KC as createTrackingEvent,lC as createVocabulary,CC as credentialFlagDefs,ig as decisionPath,jS as defaultDeployPlan,wC as defineCommand,CS as deleteCapacityInstance,Ix as deleteCompressJob,sn as deleteConfigProfile,tC as deleteCustomModelImport,iy as deleteDataset,TS as deleteDeployment,Tx as deleteFineTune,pC as deleteVocabulary,r_ as deploymentCapacityInstancePath,a_ as deploymentCapacityInstanceRenewPath,i_ as deploymentCapacityInstanceScalePath,n_ as deploymentCapacityInstancesPath,s_ as deploymentCapacityOperationPath,o_ as deploymentOverflowPath,Pt as describeAuthState,WO as detectBinaryPlatform,NO as detectInstallMethod,xD as detectInstalledAgents,Cb as detectModality,Ht as detectOutputFormat,HE as dispatchTool,XD as downloadSkillAsset,Tn as effectiveConsoleGatewayConfig,uD as emptySkillLock,Rt as ensureConfigDir,fS as estimateCptTokens,dS as estimateSftDpoTokens,lx as exportBatchCsv,Ox as exportCheckpoint,J_ as extractAsrFlashText,ND as extractTarBr,XO as extractZipEntryToFile,kD as fanOutSkillToAgents,Wx as fetchModelCapability,Gv as fetchModelDetail,Hv as fetchModelGroups,Wv as fetchModelGroupsAll,zv as fetchModelList,Bv as fetchModelListAll,Jv as fetchPredictConfig,qD as fetchSkillsIndex,uS as fetchTrainingModelPrice,ZS as findDeploymentEntry,Vv as findModelByName,iC as findSupportImportModel,Uv as flattenModelGroups,aw as flushTelemetry,bx as followParsexResult,Qv as formatCommand,_w as formatDegradation,Vt as formatErrorJson,Pb as formatIssue,Bt as formatJson,Ut as formatOutput,zt as formatText,Gh as generateCLIAccessToken,DC as generateFilename,gD as getAgentTargets,mn as getApiKeyLoginKind,Zb as getBatch,ex as getBatchFileContent,vS as getCapacityInstance,yS as getCapacityOperation,VO as getCliCdnBase,Nx as getCompressJob,Px as getCompressJobLogs,Ft as getConfigDir,It as getConfigPath,Lt as getCredentialsPath,eC as getCustomModelImport,ry as getDataset,gS as getDeployment,Cx as getFineTune,Ex as getFineTuneLogs,OC as getHermesHome,PO as getInstallMethod,pn as getModelProfilePreset,yx as getParsexResult,aS as getProfile,lD as getSkillLockPath,KD as getSkillRegistryBaseUrl,cD as getSkillsDir,FO as getUpdateInstallMethod,LS as hasPrepaidFlags,Sn as httpTransport,cg as image2ImagePath,ug as image2videoPath,nr as imageFileToDataUri,ag as imagePath,og as imageSyncPath,sg as imageText2ImagePath,W_ as inferAudioFormatHint,Ly as inspectDecisionQuestion,zy as inspectDecisionQuestionId,Ry as inspectDecisionQuestionTable,By as inspectDecisionQuestions,Ny as inspectDecisionState,iO as installSkill,rO as installSkillFromBuffer,sO as installSkillWithFanout,vt as isApiKeyCapability,AO as isCompiledBinary,Q_ as isDashScopeGateway,Ay as isDecisionObject,yD as isHostSystemDetectDir,A_ as isLegacyImage2ImageModel,k_ as isLegacyText2ImageModel,or as isLocalFile,Ev as isMcpTtsVoice,Tt as isModelConnectionSourceMismatch,MD as isSafeEntryName,QD as isSafeSkillName,Lh as isStreamableHttpUnsupported,T_ as isSyncMultimodalImageModel,Bx as isTrainingTypeCli,Rh as isUrlOverrideSseFallbackCandidate,j_ as isWanxFunctionImageEditModel,jg as knowledgeChatEndpoint,Ag as knowledgeSearchEndpoint,OD as linkSkillToAgents,dv as listBailianControlWorkspaces,$b as listBatches,_S as listCapacityInstances,Dx as listCheckpoints,Mx as listCompressJobs,Ax as listCompressTemplates,$S as listCustomModelImports,ny as listDatasets,ES as listDeployableModels,hS as listDeployments,Sx as listFineTunes,XS as listIndependentDeployedModels,QO as listSkillDirsOnDisk,rC as listSupportImportModels,Nb as listSupportedFormats,Ux as listSupportedTrainingTypes,oS as listTrainingTypes,uC as listVocabularies,rD as loadCatalog,iD as loadFamilies,ow as localSink,_n as makeAuthStore,Yv as makeConfigStore,ot as mapApiError,MC as maskToken,_O as maybeSyncWikiData,Ig as mcpWebSearchPath,gg as memoryAddAsyncPath,hg as memoryEndpoint,_g as memoryEventPath,yg as memoryListPath,bg as memoryNodePath,vg as memorySearchPath,xg as memorySkillExportPath,Hx as modelSupportsTrainingType,fg as modelsLimitsPath,pg as modelsPermissionsPath,yt as normalizeApiKeyCapabilities,Yt as normalizeConfigName,st as normalizeModelBaseUrl,Mv as parseAigcAsrTexts,Ov as parseAigcImageResults,hv as parseAigcToolResult,kv as parseAigcTtsResult,Av as parseAigcVideoTaskId,jv as parseAigcVideoTaskResult,Ub as parseBatchEndpoint,IC as parseBooleanValue,xt as parseConfigFile,uy as parseDatasetSchemaFlag,hC as parseInstantVocabulary,LC as parseOptionalBooleanValue,Fv as parseSSE,nv as parseSecurityBody,ZO as parseSkillNames,gC as parseVocabularyEntries,Yh as parsexBaseUrl,Xh as parsexEndpoint,WS as pickPlanStrategy,Ab as pickValidator,AD as planUnlinkSkillFromAgents,Kx as preflightBatchSizeGate,rx as prepareBatch,Eg as profileSchemaItemPath,Tg as profileSchemaPath,cx as projectBatchCsv,dC as queryVocabulary,d_ as ragEndpoint,Yb as readBatchBlob,GC as readCaller,$t as readConfigFile,nn as readConfigProfiles,dD as readSkillLock,PC as readTextFromPathOrStdin,EE as recommendEngine,ir as redactDataUri,Kh as refreshAccessToken,jb as registerValidator,UO as releaseAssetUrl,sw as remoteSink,aO as removeSkillDir,ey as renderCommandText,SS as renewCapacityInstance,Ln as request,Vn as requestJson,aC as requiredTrainTypeForWeightType,fv as resetBailianControlPolicies4Agent,aD as resetCatalogCache,Ot as resolveApiKey,St as resolveApiKeySource,U_ as resolveAsrApi,YD as resolveAssetFileName,tx as resolveBatchChatEndpoint,RC as resolveBooleanFlag,Uh as resolveCLIAccessTokenTarget,kt as resolveConsole,sr as resolveFileUrl,I_ as resolveImageEditApi,F_ as resolveImageGenerateApi,M_ as resolveImageSizeProfile,wv as resolveMcpImageSize,Dt as resolveModelBaseUrl,Ct as resolveModelBaseUrlSource,Et as resolveModelBaseUrlState,wt as resolveModelConnectionProvenance,At as resolveOpenApi,jC as resolveOutputDir,N_ as resolvePromptExtendDefault,zC as resolveWatermark,rg as responsesPath,iT as routeEngine,FC as runWithConcurrency,m_ as sandboxApiPath,p_ as sandboxBaseUrl,h_ as sandboxEndpoint,v_ as sandboxInstanceActionPath,__ as sandboxInstancePath,b_ as sandboxTemplateBuildStatusPath,y_ as sandboxTemplatePath,nt as sanitizeDiagnosticDetails,ZD as sanitizeSkillName,xS as scaleCapacityInstance,DS as scaleDeployment,Fg as securityAgentLogsEndpoint,rv as securityGet,Pg as securityOverviewEndpoint,cn as selectApiKeyResolutionSources,Un as signAcsRequest,Nn as sourceConfig,Cg as speechRecognizePath,Sg as speechSynthesizePath,wg as speechVocabularyPath,JS as startModelService,YS as stopModelService,_x as stripDecisionTrainingFields,NC as stripUndefined,vx as submitParsexTask,dg as taskPath,dw as trackCommandExecution,Pn as trackingHeaders,Vx as trainingTypeMethodVariant,jD as unlinkSkillFromAgents,gx as unwrapDecisionQuestions,Rv as unwrapResponse,OS as updateDeployment,wS as updateDeploymentOverflow,fC as updateVocabulary,ty as uploadDataset,ar as uploadFile,pD as upsertSkillLockEntry,Dg as userProfilePath,Og as userProfileValuesPath,Jb as validateBatch,an as validateConfigProfileActivation,Wh as validateConsoleAccessToken,Mb as validateDataset,RS as validatePrepaidFlags,FS as validateReservationCapacity,tO as validateSkillDir,Gt as validateTimeout,lg as videoGeneratePath,kg as workspaceMaaSBaseUrl,nx as writeBatchFile,en as writeConfigFile,IO as writeInstallMethodSync,fD as writeSkillLock};
|