@opentiny/next-remoter 0.3.3 → 0.4.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.
@@ -1,68 +1,73 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("vue"),Ut=require("@opentiny/tiny-robot"),dd=require("@opentiny/genui-sdk-vue"),Jn=require("@opentiny/tiny-robot-kit"),Or=require("@opentiny/tiny-robot-svgs"),Vn=require("@opentiny/next-sdk"),fd=require("@opentiny/vue-tooltip"),hd=require("@opentiny/vue-icon");function pd(t,r){for(var o=0;o<r.length;o++){const c=r[o];if(typeof c!="string"&&!Array.isArray(c)){for(const u in c)if(u!=="default"&&!(u in t)){const f=Object.getOwnPropertyDescriptor(c,u);f&&Object.defineProperty(t,u,f.get?f:{enumerable:!0,get:()=>c[u]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var fl="vercel.ai.error",md=Symbol.for(fl),hl,gd=class pl extends Error{constructor({name:r,message:o,cause:c}){super(o),this[hl]=!0,this.name=r,this.cause=c}static isInstance(r){return pl.hasMarker(r,fl)}static hasMarker(r,o){const c=Symbol.for(o);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}};hl=md;var zt=gd,ml="AI_APICallError",gl=`vercel.ai.error.${ml}`,xd=Symbol.for(gl),xl,Un=class extends zt{constructor({message:r,url:o,requestBodyValues:c,statusCode:u,responseHeaders:f,responseBody:m,cause:g,isRetryable:C=u!=null&&(u===408||u===409||u===429||u>=500),data:x}){super({name:ml,message:r,cause:g}),this[xl]=!0,this.url=o,this.requestBodyValues=c,this.statusCode=u,this.responseHeaders=f,this.responseBody=m,this.isRetryable=C,this.data=x}static isInstance(r){return zt.hasMarker(r,gl)}};xl=xd;var yl="AI_EmptyResponseBodyError",wl=`vercel.ai.error.${yl}`,yd=Symbol.for(wl),_l,wd=class extends zt{constructor({message:r="Empty response body"}={}){super({name:yl,message:r}),this[_l]=!0}static isInstance(r){return zt.hasMarker(r,wl)}};_l=yd;function vl(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Cl="AI_InvalidArgumentError",bl=`vercel.ai.error.${Cl}`,_d=Symbol.for(bl),El,Al=class extends zt{constructor({message:r,cause:o,argument:c}){super({name:Cl,message:r,cause:o}),this[El]=!0,this.argument=c}static isInstance(r){return zt.hasMarker(r,bl)}};El=_d;var Il="AI_InvalidResponseDataError",Sl=`vercel.ai.error.${Il}`,vd=Symbol.for(Sl),Tl,ys=class extends zt{constructor({data:r,message:o=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:Il,message:o}),this[Tl]=!0,this.data=r}static isInstance(r){return zt.hasMarker(r,Sl)}};Tl=vd;var Nl="AI_JSONParseError",Ol=`vercel.ai.error.${Nl}`,Cd=Symbol.for(Ol),kl,Ai=class extends zt{constructor({text:r,cause:o}){super({name:Nl,message:`JSON parsing failed: Text: ${r}.
2
- Error message: ${vl(o)}`,cause:o}),this[kl]=!0,this.text=r}static isInstance(r){return zt.hasMarker(r,Ol)}};kl=Cd;var Rl="AI_LoadAPIKeyError",Ml=`vercel.ai.error.${Rl}`,bd=Symbol.for(Ml),Dl,pi=class extends zt{constructor({message:r}){super({name:Rl,message:r}),this[Dl]=!0}static isInstance(r){return zt.hasMarker(r,Ml)}};Dl=bd;var Pl="AI_NoSuchModelError",Bl=`vercel.ai.error.${Pl}`,Ed=Symbol.for(Bl),Ll,ws=class extends zt{constructor({errorName:t=Pl,modelId:r,modelType:o,message:c=`No such ${o}: ${r}`}){super({name:t,message:c}),this[Ll]=!0,this.modelId=r,this.modelType=o}static isInstance(t){return zt.hasMarker(t,Bl)}};Ll=Ed;var Fl="AI_TypeValidationError",Ul=`vercel.ai.error.${Fl}`,Ad=Symbol.for(Ul),zl,Id=class xo extends zt{constructor({value:r,cause:o}){super({name:Fl,message:`Type validation failed: Value: ${JSON.stringify(r)}.
3
- Error message: ${vl(o)}`,cause:o}),this[zl]=!0,this.value=r}static isInstance(r){return zt.hasMarker(r,Ul)}static wrap({value:r,cause:o}){return xo.isInstance(o)&&o.value===r?o:new xo({value:r,cause:o})}};zl=Ad;var Xr=Id,Vl="AI_UnsupportedFunctionalityError",Zl=`vercel.ai.error.${Vl}`,Sd=Symbol.for(Zl),$l,Hl=class extends zt{constructor({functionality:r,message:o=`'${r}' functionality not supported.`}){super({name:Vl,message:o}),this[$l]=!0,this.functionality=r}static isInstance(r){return zt.hasMarker(r,Zl)}};$l=Sd;class _s extends Error{constructor(r,o){super(r),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line}}function no(t){}function Td(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=no,onError:o=no,onRetry:c=no,onComment:u}=t;let f="",m=!0,g,C="",x="";function A(D){const B=m?D.replace(/^\xEF\xBB\xBF/,""):D,[G,Z]=Nd(`${f}${B}`);for(const z of G)v(z);f=Z,m=!1}function v(D){if(D===""){O();return}if(D.startsWith(":")){u&&u(D.slice(D.startsWith(": ")?2:1));return}const B=D.indexOf(":");if(B!==-1){const G=D.slice(0,B),Z=D[B+1]===" "?2:1,z=D.slice(B+Z);P(G,z,D);return}P(D,"",D)}function P(D,B,G){switch(D){case"event":x=B;break;case"data":C=`${C}${B}
4
- `;break;case"id":g=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.test(B)?c(parseInt(B,10)):o(new _s(`Invalid \`retry\` value: "${B}"`,{type:"invalid-retry",value:B,line:G}));break;default:o(new _s(`Unknown field "${D.length>20?`${D.slice(0,20)}…`:D}"`,{type:"unknown-field",field:D,value:B,line:G}));break}}function O(){C.length>0&&r({id:g,event:x||void 0,data:C.endsWith(`
5
- `)?C.slice(0,-1):C}),g=void 0,C="",x=""}function M(D={}){f&&D.consume&&v(f),m=!0,g=void 0,C="",x="",f=""}return{feed:A,reset:M}}function Nd(t){const r=[];let o="",c=0;for(;c<t.length;){const u=t.indexOf("\r",c),f=t.indexOf(`
6
- `,c);let m=-1;if(u!==-1&&f!==-1?m=Math.min(u,f):u!==-1?u===t.length-1?m=-1:m=u:f!==-1&&(m=f),m===-1){o=t.slice(c);break}else{const g=t.slice(c,m);r.push(g),c=m+1,t[c-1]==="\r"&&t[c]===`
7
- `&&c++}}return[r,o]}class Wl extends TransformStream{constructor({onError:r,onRetry:o,onComment:c}={}){let u;super({start(f){u=Td({onEvent:m=>{f.enqueue(m)},onError(m){r==="terminate"?f.error(m):typeof r=="function"&&r(m)},onRetry:o,onComment:c})},transform(f){u.feed(f)}})}}function te(t,r,o){function c(g,C){var x;Object.defineProperty(g,"_zod",{value:g._zod??{},enumerable:!1}),(x=g._zod).traits??(x.traits=new Set),g._zod.traits.add(t),r(g,C);for(const A in m.prototype)A in g||Object.defineProperty(g,A,{value:m.prototype[A].bind(g)});g._zod.constr=m,g._zod.def=C}const u=o?.Parent??Object;class f extends u{}Object.defineProperty(f,"name",{value:t});function m(g){var C;const x=o?.Parent?new f:this;c(x,g),(C=x._zod).deferred??(C.deferred=[]);for(const A of x._zod.deferred)A();return x}return Object.defineProperty(m,"init",{value:c}),Object.defineProperty(m,Symbol.hasInstance,{value:g=>o?.Parent&&g instanceof o.Parent?!0:g?._zod?.traits?.has(t)}),Object.defineProperty(m,"name",{value:t}),m}class qr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const jl={};function Qn(t){return jl}function Gl(t){const r=Object.values(t).filter(c=>typeof c=="number");return Object.entries(t).filter(([c,u])=>r.indexOf(+c)===-1).map(([c,u])=>u)}function Od(t,r){return typeof r=="bigint"?r.toString():r}function Po(t){return{get value(){{const r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function Bo(t){return t==null}function Lo(t){const r=t.startsWith("^")?1:0,o=t.endsWith("$")?t.length-1:t.length;return t.slice(r,o)}function kd(t,r){const o=(t.toString().split(".")[1]||"").length,c=(r.toString().split(".")[1]||"").length,u=o>c?o:c,f=Number.parseInt(t.toFixed(u).replace(".","")),m=Number.parseInt(r.toFixed(u).replace(".",""));return f%m/10**u}function tt(t,r,o){Object.defineProperty(t,r,{get(){{const c=o();return t[r]=c,c}},set(c){Object.defineProperty(t,r,{value:c})},configurable:!0})}function Fo(t,r,o){Object.defineProperty(t,r,{value:o,writable:!0,enumerable:!0,configurable:!0})}function Ur(t){return JSON.stringify(t)}const Xl=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ii(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Rd=Po(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Si(t){if(Ii(t)===!1)return!1;const r=t.constructor;if(r===void 0)return!0;const o=r.prototype;return!(Ii(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}const Md=new Set(["string","number","symbol"]);function ti(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pr(t,r,o){const c=new t._zod.constr(r??t._zod.def);return(!r||o?.parent)&&(c._zod.parent=t),c}function Ae(t){const r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function Dd(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}const Pd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Bd(t,r){const o={},c=t._zod.def;for(const u in r){if(!(u in c.shape))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(o[u]=c.shape[u])}return pr(t,{...t._zod.def,shape:o,checks:[]})}function Ld(t,r){const o={...t._zod.def.shape},c=t._zod.def;for(const u in r){if(!(u in c.shape))throw new Error(`Unrecognized key: "${u}"`);r[u]&&delete o[u]}return pr(t,{...t._zod.def,shape:o,checks:[]})}function Fd(t,r){if(!Si(r))throw new Error("Invalid input to extend: expected a plain object");const o={...t._zod.def,get shape(){const c={...t._zod.def.shape,...r};return Fo(this,"shape",c),c},checks:[]};return pr(t,o)}function Ud(t,r){return pr(t,{...t._zod.def,get shape(){const o={...t._zod.def.shape,...r._zod.def.shape};return Fo(this,"shape",o),o},catchall:r._zod.def.catchall,checks:[]})}function zd(t,r,o){const c=r._zod.def.shape,u={...c};if(o)for(const f in o){if(!(f in c))throw new Error(`Unrecognized key: "${f}"`);o[f]&&(u[f]=t?new t({type:"optional",innerType:c[f]}):c[f])}else for(const f in c)u[f]=t?new t({type:"optional",innerType:c[f]}):c[f];return pr(r,{...r._zod.def,shape:u,checks:[]})}function Vd(t,r,o){const c=r._zod.def.shape,u={...c};if(o)for(const f in o){if(!(f in u))throw new Error(`Unrecognized key: "${f}"`);o[f]&&(u[f]=new t({type:"nonoptional",innerType:c[f]}))}else for(const f in c)u[f]=new t({type:"nonoptional",innerType:c[f]});return pr(r,{...r._zod.def,shape:u,checks:[]})}function jr(t,r=0){for(let o=r;o<t.issues.length;o++)if(t.issues[o]?.continue!==!0)return!0;return!1}function dr(t,r){return r.map(o=>{var c;return(c=o).path??(c.path=[]),o.path.unshift(t),o})}function mi(t){return typeof t=="string"?t:t?.message}function er(t,r,o){const c={...t,path:t.path??[]};if(!t.message){const u=mi(t.inst?._zod.def?.error?.(t))??mi(r?.error?.(t))??mi(o.customError?.(t))??mi(o.localeError?.(t))??"Invalid input";c.message=u}return delete c.inst,delete c.continue,r?.reportInput||delete c.input,c}function Uo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Yr(...t){const[r,o,c]=t;return typeof r=="string"?{message:r,code:"custom",input:o,inst:c}:{...r}}const ql=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(r,Od,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Yl=te("$ZodError",ql),Kl=te("$ZodError",ql,{Parent:Error});function Zd(t,r=o=>o.message){const o={},c=[];for(const u of t.issues)u.path.length>0?(o[u.path[0]]=o[u.path[0]]||[],o[u.path[0]].push(r(u))):c.push(r(u));return{formErrors:c,fieldErrors:o}}function $d(t,r){const o=r||function(f){return f.message},c={_errors:[]},u=f=>{for(const m of f.issues)if(m.code==="invalid_union"&&m.errors.length)m.errors.map(g=>u({issues:g}));else if(m.code==="invalid_key")u({issues:m.issues});else if(m.code==="invalid_element")u({issues:m.issues});else if(m.path.length===0)c._errors.push(o(m));else{let g=c,C=0;for(;C<m.path.length;){const x=m.path[C];C===m.path.length-1?(g[x]=g[x]||{_errors:[]},g[x]._errors.push(o(m))):g[x]=g[x]||{_errors:[]},g=g[x],C++}}};return u(t),c}const Hd=t=>(r,o,c,u)=>{const f=c?Object.assign(c,{async:!1}):{async:!1},m=r._zod.run({value:o,issues:[]},f);if(m instanceof Promise)throw new qr;if(m.issues.length){const g=new(u?.Err??t)(m.issues.map(C=>er(C,f,Qn())));throw Xl(g,u?.callee),g}return m.value},Wd=t=>async(r,o,c,u)=>{const f=c?Object.assign(c,{async:!0}):{async:!0};let m=r._zod.run({value:o,issues:[]},f);if(m instanceof Promise&&(m=await m),m.issues.length){const g=new(u?.Err??t)(m.issues.map(C=>er(C,f,Qn())));throw Xl(g,u?.callee),g}return m.value},Jl=t=>(r,o,c)=>{const u=c?{...c,async:!1}:{async:!1},f=r._zod.run({value:o,issues:[]},u);if(f instanceof Promise)throw new qr;return f.issues.length?{success:!1,error:new(t??Yl)(f.issues.map(m=>er(m,u,Qn())))}:{success:!0,data:f.value}},jd=Jl(Kl),Ql=t=>async(r,o,c)=>{const u=c?Object.assign(c,{async:!0}):{async:!0};let f=r._zod.run({value:o,issues:[]},u);return f instanceof Promise&&(f=await f),f.issues.length?{success:!1,error:new t(f.issues.map(m=>er(m,u,Qn())))}:{success:!0,data:f.value}},Gd=Ql(Kl),Xd=/^[cC][^\s-]{8,}$/,qd=/^[0-9a-z]+$/,Yd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Kd=/^[0-9a-vA-V]{20}$/,Jd=/^[A-Za-z0-9]{27}$/,Qd=/^[a-zA-Z0-9_-]{21}$/,e1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,t1=/^([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})$/,vs=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,n1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,r1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function i1(){return new RegExp(r1,"u")}const o1=/^(?:(?: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])$/,s1=/^(([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})$/,a1=/^((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])$/,l1=/^(([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])$/,c1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ec=/^[A-Za-z0-9_-]*$/,u1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,d1=/^\+(?:[0-9]){6,14}[0-9]$/,tc="(?:(?:\\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])))",f1=new RegExp(`^${tc}$`);function nc(t){const r="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${r}`:t.precision===0?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function h1(t){return new RegExp(`^${nc(t)}$`)}function p1(t){const r=nc({precision:t.precision}),o=["Z"];t.local&&o.push(""),t.offset&&o.push("([+-]\\d{2}:\\d{2})");const c=`${r}(?:${o.join("|")})`;return new RegExp(`^${tc}T(?:${c})$`)}const m1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},g1=/^\d+$/,x1=/^-?\d+(?:\.\d+)?/i,y1=/true|false/i,w1=/null/i,_1=/^[^A-Z]*$/,v1=/^[^a-z]*$/,on=te("$ZodCheck",(t,r)=>{var o;t._zod??(t._zod={}),t._zod.def=r,(o=t._zod).onattach??(o.onattach=[])}),rc={number:"number",bigint:"bigint",object:"date"},ic=te("$ZodCheckLessThan",(t,r)=>{on.init(t,r);const o=rc[typeof r.value];t._zod.onattach.push(c=>{const u=c._zod.bag,f=(r.inclusive?u.maximum:u.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<f&&(r.inclusive?u.maximum=r.value:u.exclusiveMaximum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value<=r.value:c.value<r.value)||c.issues.push({origin:o,code:"too_big",maximum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),oc=te("$ZodCheckGreaterThan",(t,r)=>{on.init(t,r);const o=rc[typeof r.value];t._zod.onattach.push(c=>{const u=c._zod.bag,f=(r.inclusive?u.minimum:u.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>f&&(r.inclusive?u.minimum=r.value:u.exclusiveMinimum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value>=r.value:c.value>r.value)||c.issues.push({origin:o,code:"too_small",minimum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),C1=te("$ZodCheckMultipleOf",(t,r)=>{on.init(t,r),t._zod.onattach.push(o=>{var c;(c=o._zod.bag).multipleOf??(c.multipleOf=r.value)}),t._zod.check=o=>{if(typeof o.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%r.value===BigInt(0):kd(o.value,r.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:r.value,input:o.value,inst:t,continue:!r.abort})}}),b1=te("$ZodCheckNumberFormat",(t,r)=>{on.init(t,r),r.format=r.format||"float64";const o=r.format?.includes("int"),c=o?"int":"number",[u,f]=Pd[r.format];t._zod.onattach.push(m=>{const g=m._zod.bag;g.format=r.format,g.minimum=u,g.maximum=f,o&&(g.pattern=g1)}),t._zod.check=m=>{const g=m.value;if(o){if(!Number.isInteger(g)){m.issues.push({expected:c,format:r.format,code:"invalid_type",input:g,inst:t});return}if(!Number.isSafeInteger(g)){g>0?m.issues.push({input:g,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort}):m.issues.push({input:g,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort});return}}g<u&&m.issues.push({origin:"number",input:g,code:"too_small",minimum:u,inclusive:!0,inst:t,continue:!r.abort}),g>f&&m.issues.push({origin:"number",input:g,code:"too_big",maximum:f,inst:t})}}),E1=te("$ZodCheckMaxLength",(t,r)=>{var o;on.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Bo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<u&&(c._zod.bag.maximum=r.maximum)}),t._zod.check=c=>{const u=c.value;if(u.length<=r.maximum)return;const m=Uo(u);c.issues.push({origin:m,code:"too_big",maximum:r.maximum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),A1=te("$ZodCheckMinLength",(t,r)=>{var o;on.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Bo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>u&&(c._zod.bag.minimum=r.minimum)}),t._zod.check=c=>{const u=c.value;if(u.length>=r.minimum)return;const m=Uo(u);c.issues.push({origin:m,code:"too_small",minimum:r.minimum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),I1=te("$ZodCheckLengthEquals",(t,r)=>{var o;on.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Bo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag;u.minimum=r.length,u.maximum=r.length,u.length=r.length}),t._zod.check=c=>{const u=c.value,f=u.length;if(f===r.length)return;const m=Uo(u),g=f>r.length;c.issues.push({origin:m,...g?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:c.value,inst:t,continue:!r.abort})}}),Mi=te("$ZodCheckStringFormat",(t,r)=>{var o,c;on.init(t,r),t._zod.onattach.push(u=>{const f=u._zod.bag;f.format=r.format,r.pattern&&(f.patterns??(f.patterns=new Set),f.patterns.add(r.pattern))}),r.pattern?(o=t._zod).check??(o.check=u=>{r.pattern.lastIndex=0,!r.pattern.test(u.value)&&u.issues.push({origin:"string",code:"invalid_format",format:r.format,input:u.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(c=t._zod).check??(c.check=()=>{})}),S1=te("$ZodCheckRegex",(t,r)=>{Mi.init(t,r),t._zod.check=o=>{r.pattern.lastIndex=0,!r.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),T1=te("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=_1),Mi.init(t,r)}),N1=te("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=v1),Mi.init(t,r)}),O1=te("$ZodCheckIncludes",(t,r)=>{on.init(t,r);const o=ti(r.includes),c=new RegExp(typeof r.position=="number"?`^.{${r.position}}${o}`:o);r.pattern=c,t._zod.onattach.push(u=>{const f=u._zod.bag;f.patterns??(f.patterns=new Set),f.patterns.add(c)}),t._zod.check=u=>{u.value.includes(r.includes,r.position)||u.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:u.value,inst:t,continue:!r.abort})}}),k1=te("$ZodCheckStartsWith",(t,r)=>{on.init(t,r);const o=new RegExp(`^${ti(r.prefix)}.*`);r.pattern??(r.pattern=o),t._zod.onattach.push(c=>{const u=c._zod.bag;u.patterns??(u.patterns=new Set),u.patterns.add(o)}),t._zod.check=c=>{c.value.startsWith(r.prefix)||c.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:c.value,inst:t,continue:!r.abort})}}),R1=te("$ZodCheckEndsWith",(t,r)=>{on.init(t,r);const o=new RegExp(`.*${ti(r.suffix)}$`);r.pattern??(r.pattern=o),t._zod.onattach.push(c=>{const u=c._zod.bag;u.patterns??(u.patterns=new Set),u.patterns.add(o)}),t._zod.check=c=>{c.value.endsWith(r.suffix)||c.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:c.value,inst:t,continue:!r.abort})}}),M1=te("$ZodCheckOverwrite",(t,r)=>{on.init(t,r),t._zod.check=o=>{o.value=r.tx(o.value)}});class D1{constructor(r=[]){this.content=[],this.indent=0,this&&(this.args=r)}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r=="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}const c=r.split(`
8
- `).filter(m=>m),u=Math.min(...c.map(m=>m.length-m.trimStart().length)),f=c.map(m=>m.slice(u)).map(m=>" ".repeat(this.indent*2)+m);for(const m of f)this.content.push(m)}compile(){const r=Function,o=this?.args,u=[...(this?.content??[""]).map(f=>` ${f}`)];return new r(...o,u.join(`
9
- `))}}const P1={major:4,minor:0,patch:0},at=te("$ZodType",(t,r)=>{var o;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=P1;const c=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&c.unshift(t);for(const u of c)for(const f of u._zod.onattach)f(t);if(c.length===0)(o=t._zod).deferred??(o.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const u=(f,m,g)=>{let C=jr(f),x;for(const A of m){if(A._zod.def.when){if(!A._zod.def.when(f))continue}else if(C)continue;const v=f.issues.length,P=A._zod.check(f);if(P instanceof Promise&&g?.async===!1)throw new qr;if(x||P instanceof Promise)x=(x??Promise.resolve()).then(async()=>{await P,f.issues.length!==v&&(C||(C=jr(f,v)))});else{if(f.issues.length===v)continue;C||(C=jr(f,v))}}return x?x.then(()=>f):f};t._zod.run=(f,m)=>{const g=t._zod.parse(f,m);if(g instanceof Promise){if(m.async===!1)throw new qr;return g.then(C=>u(C,c,m))}return u(g,c,m)}}t["~standard"]={validate:u=>{try{const f=jd(t,u);return f.success?{value:f.data}:{issues:f.error?.issues}}catch{return Gd(t,u).then(m=>m.success?{value:m.data}:{issues:m.error?.issues})}},vendor:"zod",version:1}}),zo=te("$ZodString",(t,r)=>{at.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??m1(t._zod.bag),t._zod.parse=(o,c)=>{if(r.coerce)try{o.value=String(o.value)}catch{}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:t}),o}}),xt=te("$ZodStringFormat",(t,r)=>{Mi.init(t,r),zo.init(t,r)}),B1=te("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=t1),xt.init(t,r)}),L1=te("$ZodUUID",(t,r)=>{if(r.version){const c={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(c===void 0)throw new Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=vs(c))}else r.pattern??(r.pattern=vs());xt.init(t,r)}),F1=te("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=n1),xt.init(t,r)}),U1=te("$ZodURL",(t,r)=>{xt.init(t,r),t._zod.check=o=>{try{const c=o.value,u=new URL(c),f=u.href;r.hostname&&(r.hostname.lastIndex=0,r.hostname.test(u.hostname)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:u1.source,input:o.value,inst:t,continue:!r.abort})),r.protocol&&(r.protocol.lastIndex=0,r.protocol.test(u.protocol.endsWith(":")?u.protocol.slice(0,-1):u.protocol)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:o.value,inst:t,continue:!r.abort})),!c.endsWith("/")&&f.endsWith("/")?o.value=f.slice(0,-1):o.value=f;return}catch{o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:t,continue:!r.abort})}}}),z1=te("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=i1()),xt.init(t,r)}),V1=te("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=Qd),xt.init(t,r)}),Z1=te("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=Xd),xt.init(t,r)}),$1=te("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=qd),xt.init(t,r)}),H1=te("$ZodULID",(t,r)=>{r.pattern??(r.pattern=Yd),xt.init(t,r)}),W1=te("$ZodXID",(t,r)=>{r.pattern??(r.pattern=Kd),xt.init(t,r)}),j1=te("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=Jd),xt.init(t,r)}),G1=te("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=p1(r)),xt.init(t,r)}),X1=te("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=f1),xt.init(t,r)}),q1=te("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=h1(r)),xt.init(t,r)}),Y1=te("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=e1),xt.init(t,r)}),K1=te("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=o1),xt.init(t,r),t._zod.onattach.push(o=>{const c=o._zod.bag;c.format="ipv4"})}),J1=te("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=s1),xt.init(t,r),t._zod.onattach.push(o=>{const c=o._zod.bag;c.format="ipv6"}),t._zod.check=o=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:t,continue:!r.abort})}}}),Q1=te("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=a1),xt.init(t,r)}),e0=te("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=l1),xt.init(t,r),t._zod.check=o=>{const[c,u]=o.value.split("/");try{if(!u)throw new Error;const f=Number(u);if(`${f}`!==u)throw new Error;if(f<0||f>128)throw new Error;new URL(`http://[${c}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:t,continue:!r.abort})}}});function sc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const t0=te("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=c1),xt.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64"}),t._zod.check=o=>{sc(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:t,continue:!r.abort})}});function n0(t){if(!ec.test(t))return!1;const r=t.replace(/[-_]/g,c=>c==="-"?"+":"/"),o=r.padEnd(Math.ceil(r.length/4)*4,"=");return sc(o)}const r0=te("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=ec),xt.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64url"}),t._zod.check=o=>{n0(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:t,continue:!r.abort})}}),i0=te("$ZodE164",(t,r)=>{r.pattern??(r.pattern=d1),xt.init(t,r)});function o0(t,r=null){try{const o=t.split(".");if(o.length!==3)return!1;const[c]=o;if(!c)return!1;const u=JSON.parse(atob(c));return!("typ"in u&&u?.typ!=="JWT"||!u.alg||r&&(!("alg"in u)||u.alg!==r))}catch{return!1}}const s0=te("$ZodJWT",(t,r)=>{xt.init(t,r),t._zod.check=o=>{o0(o.value,r.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:t,continue:!r.abort})}}),ac=te("$ZodNumber",(t,r)=>{at.init(t,r),t._zod.pattern=t._zod.bag.pattern??x1,t._zod.parse=(o,c)=>{if(r.coerce)try{o.value=Number(o.value)}catch{}const u=o.value;if(typeof u=="number"&&!Number.isNaN(u)&&Number.isFinite(u))return o;const f=typeof u=="number"?Number.isNaN(u)?"NaN":Number.isFinite(u)?void 0:"Infinity":void 0;return o.issues.push({expected:"number",code:"invalid_type",input:u,inst:t,...f?{received:f}:{}}),o}}),a0=te("$ZodNumber",(t,r)=>{b1.init(t,r),ac.init(t,r)}),l0=te("$ZodBoolean",(t,r)=>{at.init(t,r),t._zod.pattern=y1,t._zod.parse=(o,c)=>{if(r.coerce)try{o.value=!!o.value}catch{}const u=o.value;return typeof u=="boolean"||o.issues.push({expected:"boolean",code:"invalid_type",input:u,inst:t}),o}}),c0=te("$ZodNull",(t,r)=>{at.init(t,r),t._zod.pattern=w1,t._zod.values=new Set([null]),t._zod.parse=(o,c)=>{const u=o.value;return u===null||o.issues.push({expected:"null",code:"invalid_type",input:u,inst:t}),o}}),u0=te("$ZodAny",(t,r)=>{at.init(t,r),t._zod.parse=o=>o}),d0=te("$ZodUnknown",(t,r)=>{at.init(t,r),t._zod.parse=o=>o}),f0=te("$ZodNever",(t,r)=>{at.init(t,r),t._zod.parse=(o,c)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:t}),o)});function Cs(t,r,o){t.issues.length&&r.issues.push(...dr(o,t.issues)),r.value[o]=t.value}const h0=te("$ZodArray",(t,r)=>{at.init(t,r),t._zod.parse=(o,c)=>{const u=o.value;if(!Array.isArray(u))return o.issues.push({expected:"array",code:"invalid_type",input:u,inst:t}),o;o.value=Array(u.length);const f=[];for(let m=0;m<u.length;m++){const g=u[m],C=r.element._zod.run({value:g,issues:[]},c);C instanceof Promise?f.push(C.then(x=>Cs(x,o,m))):Cs(C,o,m)}return f.length?Promise.all(f).then(()=>o):o}});function gi(t,r,o){t.issues.length&&r.issues.push(...dr(o,t.issues)),r.value[o]=t.value}function bs(t,r,o,c){t.issues.length?c[o]===void 0?o in c?r.value[o]=void 0:r.value[o]=t.value:r.issues.push(...dr(o,t.issues)):t.value===void 0?o in c&&(r.value[o]=void 0):r.value[o]=t.value}const p0=te("$ZodObject",(t,r)=>{at.init(t,r);const o=Po(()=>{const v=Object.keys(r.shape);for(const O of v)if(!(r.shape[O]instanceof at))throw new Error(`Invalid element at key "${O}": expected a Zod schema`);const P=Dd(r.shape);return{shape:r.shape,keys:v,keySet:new Set(v),numKeys:v.length,optionalKeys:new Set(P)}});tt(t._zod,"propValues",()=>{const v=r.shape,P={};for(const O in v){const M=v[O]._zod;if(M.values){P[O]??(P[O]=new Set);for(const D of M.values)P[O].add(D)}}return P});const c=v=>{const P=new D1(["shape","payload","ctx"]),O=o.value,M=Z=>{const z=Ur(Z);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};P.write("const input = payload.value;");const D=Object.create(null);let B=0;for(const Z of O.keys)D[Z]=`key_${B++}`;P.write("const newResult = {}");for(const Z of O.keys)if(O.optionalKeys.has(Z)){const z=D[Z];P.write(`const ${z} = ${M(Z)};`);const ee=Ur(Z);P.write(`
10
- if (${z}.issues.length) {
11
- if (input[${ee}] === undefined) {
12
- if (${ee} in input) {
13
- newResult[${ee}] = undefined;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("vue"),Vt=require("@opentiny/tiny-robot"),Ed=require("@opentiny/genui-sdk-vue"),Kn=require("@opentiny/tiny-robot-kit"),Mr=require("@opentiny/tiny-robot-svgs"),Jn=require("@opentiny/next-sdk"),Id=require("@opentiny/vue-tooltip"),Sd=require("@opentiny/vue-icon");function Td(t,r){for(var i=0;i<r.length;i++){const c=r[i];if(typeof c!="string"&&!Array.isArray(c)){for(const d in c)if(d!=="default"&&!(d in t)){const f=Object.getOwnPropertyDescriptor(c,d);f&&Object.defineProperty(t,d,f.get?f:{enumerable:!0,get:()=>c[d]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var vl="vercel.ai.error",Nd=Symbol.for(vl),Cl,Od=class bl extends Error{constructor({name:r,message:i,cause:c}){super(i),this[Cl]=!0,this.name=r,this.cause=c}static isInstance(r){return bl.hasMarker(r,vl)}static hasMarker(r,i){const c=Symbol.for(i);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}};Cl=Nd;var Zt=Od,Al="AI_APICallError",El=`vercel.ai.error.${Al}`,kd=Symbol.for(El),Il,Vn=class extends Zt{constructor({message:r,url:i,requestBodyValues:c,statusCode:d,responseHeaders:f,responseBody:m,cause:x,isRetryable:v=d!=null&&(d===408||d===409||d===429||d>=500),data:g}){super({name:Al,message:r,cause:x}),this[Il]=!0,this.url=i,this.requestBodyValues=c,this.statusCode=d,this.responseHeaders=f,this.responseBody=m,this.isRetryable=v,this.data=g}static isInstance(r){return Zt.hasMarker(r,El)}};Il=kd;var Sl="AI_EmptyResponseBodyError",Tl=`vercel.ai.error.${Sl}`,Rd=Symbol.for(Tl),Nl,Md=class extends Zt{constructor({message:r="Empty response body"}={}){super({name:Sl,message:r}),this[Nl]=!0}static isInstance(r){return Zt.hasMarker(r,Tl)}};Nl=Rd;function Ol(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var kl="AI_InvalidArgumentError",Rl=`vercel.ai.error.${kl}`,Dd=Symbol.for(Rl),Ml,Dl=class extends Zt{constructor({message:r,cause:i,argument:c}){super({name:kl,message:r,cause:i}),this[Ml]=!0,this.argument=c}static isInstance(r){return Zt.hasMarker(r,Rl)}};Ml=Dd;var Pl="AI_InvalidResponseDataError",Bl=`vercel.ai.error.${Pl}`,Pd=Symbol.for(Bl),Ll,bs=class extends Zt{constructor({data:r,message:i=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:Pl,message:i}),this[Ll]=!0,this.data=r}static isInstance(r){return Zt.hasMarker(r,Bl)}};Ll=Pd;var Fl="AI_JSONParseError",Ul=`vercel.ai.error.${Fl}`,Bd=Symbol.for(Ul),zl,Oo=class extends Zt{constructor({text:r,cause:i}){super({name:Fl,message:`JSON parsing failed: Text: ${r}.
2
+ Error message: ${Ol(i)}`,cause:i}),this[zl]=!0,this.text=r}static isInstance(r){return Zt.hasMarker(r,Ul)}};zl=Bd;var Vl="AI_LoadAPIKeyError",Zl=`vercel.ai.error.${Vl}`,Ld=Symbol.for(Zl),$l,wo=class extends Zt{constructor({message:r}){super({name:Vl,message:r}),this[$l]=!0}static isInstance(r){return Zt.hasMarker(r,Zl)}};$l=Ld;var jl="AI_NoSuchModelError",Hl=`vercel.ai.error.${jl}`,Fd=Symbol.for(Hl),Wl,As=class extends Zt{constructor({errorName:t=jl,modelId:r,modelType:i,message:c=`No such ${i}: ${r}`}){super({name:t,message:c}),this[Wl]=!0,this.modelId=r,this.modelType=i}static isInstance(t){return Zt.hasMarker(t,Hl)}};Wl=Fd;var Gl="AI_TypeValidationError",ql=`vercel.ai.error.${Gl}`,Ud=Symbol.for(ql),Xl,zd=class Ci extends Zt{constructor({value:r,cause:i}){super({name:Gl,message:`Type validation failed: Value: ${JSON.stringify(r)}.
3
+ Error message: ${Ol(i)}`,cause:i}),this[Xl]=!0,this.value=r}static isInstance(r){return Zt.hasMarker(r,ql)}static wrap({value:r,cause:i}){return Ci.isInstance(i)&&i.value===r?i:new Ci({value:r,cause:i})}};Xl=Ud;var Jr=zd,Yl="AI_UnsupportedFunctionalityError",Kl=`vercel.ai.error.${Yl}`,Vd=Symbol.for(Kl),Jl,Ql=class extends Zt{constructor({functionality:r,message:i=`'${r}' functionality not supported.`}){super({name:Yl,message:i}),this[Jl]=!0,this.functionality=r}static isInstance(r){return Zt.hasMarker(r,Kl)}};Jl=Vd;class ai extends Error{constructor(r,i){super(r),this.name="ParseError",this.type=i.type,this.field=i.field,this.value=i.value,this.line=i.line}}const Es=10,Zd=13,ur=32;function li(t){}function $d(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:r=li,onError:i=li,onRetry:c=li,onComment:d,maxBufferSize:f}=t,m=[];let x=0,v=!0,g,E="",A=0,D,T=!1;function S(Z){if(T)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(v&&(v=!1,Z.charCodeAt(0)===239&&Z.charCodeAt(1)===187&&Z.charCodeAt(2)===191&&(Z=Z.slice(3))),m.length===0){const W=M(Z);W!==""&&(m.push(W),x=W.length),P();return}if(Z.indexOf(`
4
+ `)===-1&&Z.indexOf("\r")===-1){m.push(Z),x+=Z.length,P();return}m.push(Z);const B=m.join("");m.length=0,x=0;const L=M(B);L!==""&&(m.push(L),x=L.length),P()}function P(){f!==void 0&&(x+E.length<=f||(T=!0,m.length=0,x=0,g=void 0,E="",A=0,D=void 0,i(new ai(`Buffered data exceeded max buffer size of ${f} characters`,{type:"max-buffer-size-exceeded"}))))}function M(Z){let B=0;if(Z.indexOf("\r")===-1){let L=Z.indexOf(`
5
+ `,B);for(;L!==-1;){if(B===L){A>0&&r({id:g,event:D,data:E}),g=void 0,E="",A=0,D=void 0,B=L+1,L=Z.indexOf(`
6
+ `,B);continue}const W=Z.charCodeAt(B);if(Is(Z,B,W)){const z=Z.charCodeAt(B+5)===ur?B+6:B+5,we=Z.slice(z,L);if(A===0&&Z.charCodeAt(L+1)===Es){r({id:g,event:D,data:we}),g=void 0,E="",D=void 0,B=L+2,L=Z.indexOf(`
7
+ `,B);continue}E=A===0?we:`${E}
8
+ ${we}`,A++}else Ss(Z,B,W)?D=Z.slice(Z.charCodeAt(B+6)===ur?B+7:B+6,L)||void 0:ee(Z,B,L);B=L+1,L=Z.indexOf(`
9
+ `,B)}return Z.slice(B)}for(;B<Z.length;){const L=Z.indexOf("\r",B),W=Z.indexOf(`
10
+ `,B);let z=-1;if(L!==-1&&W!==-1?z=L<W?L:W:L!==-1?L===Z.length-1?z=-1:z=L:W!==-1&&(z=W),z===-1)break;ee(Z,B,z),B=z+1,Z.charCodeAt(B-1)===Zd&&Z.charCodeAt(B)===Es&&B++}return Z.slice(B)}function ee(Z,B,L){if(B===L){F();return}const W=Z.charCodeAt(B);if(Is(Z,B,W)){const te=Z.charCodeAt(B+5)===ur?B+6:B+5,q=Z.slice(te,L);E=A===0?q:`${E}
11
+ ${q}`,A++;return}if(Ss(Z,B,W)){D=Z.slice(Z.charCodeAt(B+6)===ur?B+7:B+6,L)||void 0;return}if(W===105&&Z.charCodeAt(B+1)===100&&Z.charCodeAt(B+2)===58){const te=Z.slice(Z.charCodeAt(B+3)===ur?B+4:B+3,L);g=te.includes("\0")?void 0:te;return}if(W===58){if(d){const te=Z.slice(B,L);d(te.slice(Z.charCodeAt(B+1)===ur?2:1))}return}const z=Z.slice(B,L),we=z.indexOf(":");if(we===-1){$(z,"",z);return}const G=z.slice(0,we),me=z.charCodeAt(we+1)===ur?2:1,fe=z.slice(we+me);$(G,fe,z)}function $(Z,B,L){switch(Z){case"event":D=B||void 0;break;case"data":E=A===0?B:`${E}
12
+ ${B}`,A++;break;case"id":g=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.test(B)?c(parseInt(B,10)):i(new ai(`Invalid \`retry\` value: "${B}"`,{type:"invalid-retry",value:B,line:L}));break;default:i(new ai(`Unknown field "${Z.length>20?`${Z.slice(0,20)}…`:Z}"`,{type:"unknown-field",field:Z,value:B,line:L}));break}}function F(){A>0&&r({id:g,event:D,data:E}),g=void 0,E="",A=0,D=void 0}function re(Z={}){if(Z.consume&&m.length>0){const B=m.join("");ee(B,0,B.length)}v=!0,g=void 0,E="",A=0,D=void 0,m.length=0,x=0,T=!1}return{feed:S,reset:re}}function Is(t,r,i){return i===100&&t.charCodeAt(r+1)===97&&t.charCodeAt(r+2)===116&&t.charCodeAt(r+3)===97&&t.charCodeAt(r+4)===58}function Ss(t,r,i){return i===101&&t.charCodeAt(r+1)===118&&t.charCodeAt(r+2)===101&&t.charCodeAt(r+3)===110&&t.charCodeAt(r+4)===116&&t.charCodeAt(r+5)===58}class ec extends TransformStream{constructor({onError:r,onRetry:i,onComment:c,maxBufferSize:d}={}){let f;super({start(m){f=$d({onEvent:x=>{m.enqueue(x)},onError(x){typeof r=="function"&&r(x),(r==="terminate"||x.type==="max-buffer-size-exceeded")&&m.error(x)},onRetry:i,onComment:c,maxBufferSize:d})},transform(m){f.feed(m)}})}}function oe(t,r,i){function c(x,v){var g;Object.defineProperty(x,"_zod",{value:x._zod??{},enumerable:!1}),(g=x._zod).traits??(g.traits=new Set),x._zod.traits.add(t),r(x,v);for(const E in m.prototype)E in x||Object.defineProperty(x,E,{value:m.prototype[E].bind(x)});x._zod.constr=m,x._zod.def=v}const d=i?.Parent??Object;class f extends d{}Object.defineProperty(f,"name",{value:t});function m(x){var v;const g=i?.Parent?new f:this;c(g,x),(v=g._zod).deferred??(v.deferred=[]);for(const E of g._zod.deferred)E();return g}return Object.defineProperty(m,"init",{value:c}),Object.defineProperty(m,Symbol.hasInstance,{value:x=>i?.Parent&&x instanceof i.Parent?!0:x?._zod?.traits?.has(t)}),Object.defineProperty(m,"name",{value:t}),m}class Qr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const tc={};function Qn(t){return tc}function nc(t){const r=Object.values(t).filter(c=>typeof c=="number");return Object.entries(t).filter(([c,d])=>r.indexOf(+c)===-1).map(([c,d])=>d)}function jd(t,r){return typeof r=="bigint"?r.toString():r}function Ui(t){return{get value(){{const r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function zi(t){return t==null}function Vi(t){const r=t.startsWith("^")?1:0,i=t.endsWith("$")?t.length-1:t.length;return t.slice(r,i)}function Hd(t,r){const i=(t.toString().split(".")[1]||"").length,c=(r.toString().split(".")[1]||"").length,d=i>c?i:c,f=Number.parseInt(t.toFixed(d).replace(".","")),m=Number.parseInt(r.toFixed(d).replace(".",""));return f%m/10**d}function lt(t,r,i){Object.defineProperty(t,r,{get(){{const c=i();return t[r]=c,c}},set(c){Object.defineProperty(t,r,{value:c})},configurable:!0})}function Zi(t,r,i){Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})}function Zr(t){return JSON.stringify(t)}const rc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ko(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Wd=Ui(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ro(t){if(ko(t)===!1)return!1;const r=t.constructor;if(r===void 0)return!0;const i=r.prototype;return!(ko(i)===!1||Object.prototype.hasOwnProperty.call(i,"isPrototypeOf")===!1)}const Gd=new Set(["string","number","symbol"]);function io(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gr(t,r,i){const c=new t._zod.constr(r??t._zod.def);return(!r||i?.parent)&&(c._zod.parent=t),c}function Ie(t){const r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function qd(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}const Xd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Yd(t,r){const i={},c=t._zod.def;for(const d in r){if(!(d in c.shape))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(i[d]=c.shape[d])}return gr(t,{...t._zod.def,shape:i,checks:[]})}function Kd(t,r){const i={...t._zod.def.shape},c=t._zod.def;for(const d in r){if(!(d in c.shape))throw new Error(`Unrecognized key: "${d}"`);r[d]&&delete i[d]}return gr(t,{...t._zod.def,shape:i,checks:[]})}function Jd(t,r){if(!Ro(r))throw new Error("Invalid input to extend: expected a plain object");const i={...t._zod.def,get shape(){const c={...t._zod.def.shape,...r};return Zi(this,"shape",c),c},checks:[]};return gr(t,i)}function Qd(t,r){return gr(t,{...t._zod.def,get shape(){const i={...t._zod.def.shape,...r._zod.def.shape};return Zi(this,"shape",i),i},catchall:r._zod.def.catchall,checks:[]})}function e1(t,r,i){const c=r._zod.def.shape,d={...c};if(i)for(const f in i){if(!(f in c))throw new Error(`Unrecognized key: "${f}"`);i[f]&&(d[f]=t?new t({type:"optional",innerType:c[f]}):c[f])}else for(const f in c)d[f]=t?new t({type:"optional",innerType:c[f]}):c[f];return gr(r,{...r._zod.def,shape:d,checks:[]})}function t1(t,r,i){const c=r._zod.def.shape,d={...c};if(i)for(const f in i){if(!(f in d))throw new Error(`Unrecognized key: "${f}"`);i[f]&&(d[f]=new t({type:"nonoptional",innerType:c[f]}))}else for(const f in c)d[f]=new t({type:"nonoptional",innerType:c[f]});return gr(r,{...r._zod.def,shape:d,checks:[]})}function Yr(t,r=0){for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue!==!0)return!0;return!1}function hr(t,r){return r.map(i=>{var c;return(c=i).path??(c.path=[]),i.path.unshift(t),i})}function _o(t){return typeof t=="string"?t:t?.message}function er(t,r,i){const c={...t,path:t.path??[]};if(!t.message){const d=_o(t.inst?._zod.def?.error?.(t))??_o(r?.error?.(t))??_o(i.customError?.(t))??_o(i.localeError?.(t))??"Invalid input";c.message=d}return delete c.inst,delete c.continue,r?.reportInput||delete c.input,c}function $i(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function eo(...t){const[r,i,c]=t;return typeof r=="string"?{message:r,code:"custom",input:i,inst:c}:{...r}}const oc=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(r,jd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ic=oe("$ZodError",oc),sc=oe("$ZodError",oc,{Parent:Error});function n1(t,r=i=>i.message){const i={},c=[];for(const d of t.issues)d.path.length>0?(i[d.path[0]]=i[d.path[0]]||[],i[d.path[0]].push(r(d))):c.push(r(d));return{formErrors:c,fieldErrors:i}}function r1(t,r){const i=r||function(f){return f.message},c={_errors:[]},d=f=>{for(const m of f.issues)if(m.code==="invalid_union"&&m.errors.length)m.errors.map(x=>d({issues:x}));else if(m.code==="invalid_key")d({issues:m.issues});else if(m.code==="invalid_element")d({issues:m.issues});else if(m.path.length===0)c._errors.push(i(m));else{let x=c,v=0;for(;v<m.path.length;){const g=m.path[v];v===m.path.length-1?(x[g]=x[g]||{_errors:[]},x[g]._errors.push(i(m))):x[g]=x[g]||{_errors:[]},x=x[g],v++}}};return d(t),c}const o1=t=>(r,i,c,d)=>{const f=c?Object.assign(c,{async:!1}):{async:!1},m=r._zod.run({value:i,issues:[]},f);if(m instanceof Promise)throw new Qr;if(m.issues.length){const x=new(d?.Err??t)(m.issues.map(v=>er(v,f,Qn())));throw rc(x,d?.callee),x}return m.value},i1=t=>async(r,i,c,d)=>{const f=c?Object.assign(c,{async:!0}):{async:!0};let m=r._zod.run({value:i,issues:[]},f);if(m instanceof Promise&&(m=await m),m.issues.length){const x=new(d?.Err??t)(m.issues.map(v=>er(v,f,Qn())));throw rc(x,d?.callee),x}return m.value},ac=t=>(r,i,c)=>{const d=c?{...c,async:!1}:{async:!1},f=r._zod.run({value:i,issues:[]},d);if(f instanceof Promise)throw new Qr;return f.issues.length?{success:!1,error:new(t??ic)(f.issues.map(m=>er(m,d,Qn())))}:{success:!0,data:f.value}},s1=ac(sc),lc=t=>async(r,i,c)=>{const d=c?Object.assign(c,{async:!0}):{async:!0};let f=r._zod.run({value:i,issues:[]},d);return f instanceof Promise&&(f=await f),f.issues.length?{success:!1,error:new t(f.issues.map(m=>er(m,d,Qn())))}:{success:!0,data:f.value}},a1=lc(sc),l1=/^[cC][^\s-]{8,}$/,c1=/^[0-9a-z]+$/,u1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,d1=/^[0-9a-vA-V]{20}$/,f1=/^[A-Za-z0-9]{27}$/,h1=/^[a-zA-Z0-9_-]{21}$/,p1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,m1=/^([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})$/,Ts=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,g1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,x1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function y1(){return new RegExp(x1,"u")}const w1=/^(?:(?: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])$/,_1=/^(([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})$/,v1=/^((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])$/,C1=/^(([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])$/,b1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cc=/^[A-Za-z0-9_-]*$/,A1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,E1=/^\+(?:[0-9]){6,14}[0-9]$/,uc="(?:(?:\\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])))",I1=new RegExp(`^${uc}$`);function dc(t){const r="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${r}`:t.precision===0?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function S1(t){return new RegExp(`^${dc(t)}$`)}function T1(t){const r=dc({precision:t.precision}),i=["Z"];t.local&&i.push(""),t.offset&&i.push("([+-]\\d{2}:\\d{2})");const c=`${r}(?:${i.join("|")})`;return new RegExp(`^${uc}T(?:${c})$`)}const N1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},O1=/^\d+$/,k1=/^-?\d+(?:\.\d+)?/i,R1=/true|false/i,M1=/null/i,D1=/^[^A-Z]*$/,P1=/^[^a-z]*$/,on=oe("$ZodCheck",(t,r)=>{var i;t._zod??(t._zod={}),t._zod.def=r,(i=t._zod).onattach??(i.onattach=[])}),fc={number:"number",bigint:"bigint",object:"date"},hc=oe("$ZodCheckLessThan",(t,r)=>{on.init(t,r);const i=fc[typeof r.value];t._zod.onattach.push(c=>{const d=c._zod.bag,f=(r.inclusive?d.maximum:d.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<f&&(r.inclusive?d.maximum=r.value:d.exclusiveMaximum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value<=r.value:c.value<r.value)||c.issues.push({origin:i,code:"too_big",maximum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),pc=oe("$ZodCheckGreaterThan",(t,r)=>{on.init(t,r);const i=fc[typeof r.value];t._zod.onattach.push(c=>{const d=c._zod.bag,f=(r.inclusive?d.minimum:d.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>f&&(r.inclusive?d.minimum=r.value:d.exclusiveMinimum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value>=r.value:c.value>r.value)||c.issues.push({origin:i,code:"too_small",minimum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),B1=oe("$ZodCheckMultipleOf",(t,r)=>{on.init(t,r),t._zod.onattach.push(i=>{var c;(c=i._zod.bag).multipleOf??(c.multipleOf=r.value)}),t._zod.check=i=>{if(typeof i.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof i.value=="bigint"?i.value%r.value===BigInt(0):Hd(i.value,r.value)===0)||i.issues.push({origin:typeof i.value,code:"not_multiple_of",divisor:r.value,input:i.value,inst:t,continue:!r.abort})}}),L1=oe("$ZodCheckNumberFormat",(t,r)=>{on.init(t,r),r.format=r.format||"float64";const i=r.format?.includes("int"),c=i?"int":"number",[d,f]=Xd[r.format];t._zod.onattach.push(m=>{const x=m._zod.bag;x.format=r.format,x.minimum=d,x.maximum=f,i&&(x.pattern=O1)}),t._zod.check=m=>{const x=m.value;if(i){if(!Number.isInteger(x)){m.issues.push({expected:c,format:r.format,code:"invalid_type",input:x,inst:t});return}if(!Number.isSafeInteger(x)){x>0?m.issues.push({input:x,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort}):m.issues.push({input:x,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort});return}}x<d&&m.issues.push({origin:"number",input:x,code:"too_small",minimum:d,inclusive:!0,inst:t,continue:!r.abort}),x>f&&m.issues.push({origin:"number",input:x,code:"too_big",maximum:f,inst:t})}}),F1=oe("$ZodCheckMaxLength",(t,r)=>{var i;on.init(t,r),(i=t._zod.def).when??(i.when=c=>{const d=c.value;return!zi(d)&&d.length!==void 0}),t._zod.onattach.push(c=>{const d=c._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<d&&(c._zod.bag.maximum=r.maximum)}),t._zod.check=c=>{const d=c.value;if(d.length<=r.maximum)return;const m=$i(d);c.issues.push({origin:m,code:"too_big",maximum:r.maximum,inclusive:!0,input:d,inst:t,continue:!r.abort})}}),U1=oe("$ZodCheckMinLength",(t,r)=>{var i;on.init(t,r),(i=t._zod.def).when??(i.when=c=>{const d=c.value;return!zi(d)&&d.length!==void 0}),t._zod.onattach.push(c=>{const d=c._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>d&&(c._zod.bag.minimum=r.minimum)}),t._zod.check=c=>{const d=c.value;if(d.length>=r.minimum)return;const m=$i(d);c.issues.push({origin:m,code:"too_small",minimum:r.minimum,inclusive:!0,input:d,inst:t,continue:!r.abort})}}),z1=oe("$ZodCheckLengthEquals",(t,r)=>{var i;on.init(t,r),(i=t._zod.def).when??(i.when=c=>{const d=c.value;return!zi(d)&&d.length!==void 0}),t._zod.onattach.push(c=>{const d=c._zod.bag;d.minimum=r.length,d.maximum=r.length,d.length=r.length}),t._zod.check=c=>{const d=c.value,f=d.length;if(f===r.length)return;const m=$i(d),x=f>r.length;c.issues.push({origin:m,...x?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:c.value,inst:t,continue:!r.abort})}}),Fo=oe("$ZodCheckStringFormat",(t,r)=>{var i,c;on.init(t,r),t._zod.onattach.push(d=>{const f=d._zod.bag;f.format=r.format,r.pattern&&(f.patterns??(f.patterns=new Set),f.patterns.add(r.pattern))}),r.pattern?(i=t._zod).check??(i.check=d=>{r.pattern.lastIndex=0,!r.pattern.test(d.value)&&d.issues.push({origin:"string",code:"invalid_format",format:r.format,input:d.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(c=t._zod).check??(c.check=()=>{})}),V1=oe("$ZodCheckRegex",(t,r)=>{Fo.init(t,r),t._zod.check=i=>{r.pattern.lastIndex=0,!r.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:"regex",input:i.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),Z1=oe("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=D1),Fo.init(t,r)}),$1=oe("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=P1),Fo.init(t,r)}),j1=oe("$ZodCheckIncludes",(t,r)=>{on.init(t,r);const i=io(r.includes),c=new RegExp(typeof r.position=="number"?`^.{${r.position}}${i}`:i);r.pattern=c,t._zod.onattach.push(d=>{const f=d._zod.bag;f.patterns??(f.patterns=new Set),f.patterns.add(c)}),t._zod.check=d=>{d.value.includes(r.includes,r.position)||d.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:d.value,inst:t,continue:!r.abort})}}),H1=oe("$ZodCheckStartsWith",(t,r)=>{on.init(t,r);const i=new RegExp(`^${io(r.prefix)}.*`);r.pattern??(r.pattern=i),t._zod.onattach.push(c=>{const d=c._zod.bag;d.patterns??(d.patterns=new Set),d.patterns.add(i)}),t._zod.check=c=>{c.value.startsWith(r.prefix)||c.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:c.value,inst:t,continue:!r.abort})}}),W1=oe("$ZodCheckEndsWith",(t,r)=>{on.init(t,r);const i=new RegExp(`.*${io(r.suffix)}$`);r.pattern??(r.pattern=i),t._zod.onattach.push(c=>{const d=c._zod.bag;d.patterns??(d.patterns=new Set),d.patterns.add(i)}),t._zod.check=c=>{c.value.endsWith(r.suffix)||c.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:c.value,inst:t,continue:!r.abort})}}),G1=oe("$ZodCheckOverwrite",(t,r)=>{on.init(t,r),t._zod.check=i=>{i.value=r.tx(i.value)}});class q1{constructor(r=[]){this.content=[],this.indent=0,this&&(this.args=r)}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r=="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}const c=r.split(`
13
+ `).filter(m=>m),d=Math.min(...c.map(m=>m.length-m.trimStart().length)),f=c.map(m=>m.slice(d)).map(m=>" ".repeat(this.indent*2)+m);for(const m of f)this.content.push(m)}compile(){const r=Function,i=this?.args,d=[...(this?.content??[""]).map(f=>` ${f}`)];return new r(...i,d.join(`
14
+ `))}}const X1={major:4,minor:0,patch:0},ht=oe("$ZodType",(t,r)=>{var i;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=X1;const c=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&c.unshift(t);for(const d of c)for(const f of d._zod.onattach)f(t);if(c.length===0)(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const d=(f,m,x)=>{let v=Yr(f),g;for(const E of m){if(E._zod.def.when){if(!E._zod.def.when(f))continue}else if(v)continue;const A=f.issues.length,D=E._zod.check(f);if(D instanceof Promise&&x?.async===!1)throw new Qr;if(g||D instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await D,f.issues.length!==A&&(v||(v=Yr(f,A)))});else{if(f.issues.length===A)continue;v||(v=Yr(f,A))}}return g?g.then(()=>f):f};t._zod.run=(f,m)=>{const x=t._zod.parse(f,m);if(x instanceof Promise){if(m.async===!1)throw new Qr;return x.then(v=>d(v,c,m))}return d(x,c,m)}}t["~standard"]={validate:d=>{try{const f=s1(t,d);return f.success?{value:f.data}:{issues:f.error?.issues}}catch{return a1(t,d).then(m=>m.success?{value:m.data}:{issues:m.error?.issues})}},vendor:"zod",version:1}}),ji=oe("$ZodString",(t,r)=>{ht.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??N1(t._zod.bag),t._zod.parse=(i,c)=>{if(r.coerce)try{i.value=String(i.value)}catch{}return typeof i.value=="string"||i.issues.push({expected:"string",code:"invalid_type",input:i.value,inst:t}),i}}),bt=oe("$ZodStringFormat",(t,r)=>{Fo.init(t,r),ji.init(t,r)}),Y1=oe("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=m1),bt.init(t,r)}),K1=oe("$ZodUUID",(t,r)=>{if(r.version){const c={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(c===void 0)throw new Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=Ts(c))}else r.pattern??(r.pattern=Ts());bt.init(t,r)}),J1=oe("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=g1),bt.init(t,r)}),Q1=oe("$ZodURL",(t,r)=>{bt.init(t,r),t._zod.check=i=>{try{const c=i.value,d=new URL(c),f=d.href;r.hostname&&(r.hostname.lastIndex=0,r.hostname.test(d.hostname)||i.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:A1.source,input:i.value,inst:t,continue:!r.abort})),r.protocol&&(r.protocol.lastIndex=0,r.protocol.test(d.protocol.endsWith(":")?d.protocol.slice(0,-1):d.protocol)||i.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:i.value,inst:t,continue:!r.abort})),!c.endsWith("/")&&f.endsWith("/")?i.value=f.slice(0,-1):i.value=f;return}catch{i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort})}}}),e0=oe("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=y1()),bt.init(t,r)}),t0=oe("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=h1),bt.init(t,r)}),n0=oe("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=l1),bt.init(t,r)}),r0=oe("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=c1),bt.init(t,r)}),o0=oe("$ZodULID",(t,r)=>{r.pattern??(r.pattern=u1),bt.init(t,r)}),i0=oe("$ZodXID",(t,r)=>{r.pattern??(r.pattern=d1),bt.init(t,r)}),s0=oe("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=f1),bt.init(t,r)}),a0=oe("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=T1(r)),bt.init(t,r)}),l0=oe("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=I1),bt.init(t,r)}),c0=oe("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=S1(r)),bt.init(t,r)}),u0=oe("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=p1),bt.init(t,r)}),d0=oe("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=w1),bt.init(t,r),t._zod.onattach.push(i=>{const c=i._zod.bag;c.format="ipv4"})}),f0=oe("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=_1),bt.init(t,r),t._zod.onattach.push(i=>{const c=i._zod.bag;c.format="ipv6"}),t._zod.check=i=>{try{new URL(`http://[${i.value}]`)}catch{i.issues.push({code:"invalid_format",format:"ipv6",input:i.value,inst:t,continue:!r.abort})}}}),h0=oe("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=v1),bt.init(t,r)}),p0=oe("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=C1),bt.init(t,r),t._zod.check=i=>{const[c,d]=i.value.split("/");try{if(!d)throw new Error;const f=Number(d);if(`${f}`!==d)throw new Error;if(f<0||f>128)throw new Error;new URL(`http://[${c}]`)}catch{i.issues.push({code:"invalid_format",format:"cidrv6",input:i.value,inst:t,continue:!r.abort})}}});function mc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const m0=oe("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=b1),bt.init(t,r),t._zod.onattach.push(i=>{i._zod.bag.contentEncoding="base64"}),t._zod.check=i=>{mc(i.value)||i.issues.push({code:"invalid_format",format:"base64",input:i.value,inst:t,continue:!r.abort})}});function g0(t){if(!cc.test(t))return!1;const r=t.replace(/[-_]/g,c=>c==="-"?"+":"/"),i=r.padEnd(Math.ceil(r.length/4)*4,"=");return mc(i)}const x0=oe("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=cc),bt.init(t,r),t._zod.onattach.push(i=>{i._zod.bag.contentEncoding="base64url"}),t._zod.check=i=>{g0(i.value)||i.issues.push({code:"invalid_format",format:"base64url",input:i.value,inst:t,continue:!r.abort})}}),y0=oe("$ZodE164",(t,r)=>{r.pattern??(r.pattern=E1),bt.init(t,r)});function w0(t,r=null){try{const i=t.split(".");if(i.length!==3)return!1;const[c]=i;if(!c)return!1;const d=JSON.parse(atob(c));return!("typ"in d&&d?.typ!=="JWT"||!d.alg||r&&(!("alg"in d)||d.alg!==r))}catch{return!1}}const _0=oe("$ZodJWT",(t,r)=>{bt.init(t,r),t._zod.check=i=>{w0(i.value,r.alg)||i.issues.push({code:"invalid_format",format:"jwt",input:i.value,inst:t,continue:!r.abort})}}),gc=oe("$ZodNumber",(t,r)=>{ht.init(t,r),t._zod.pattern=t._zod.bag.pattern??k1,t._zod.parse=(i,c)=>{if(r.coerce)try{i.value=Number(i.value)}catch{}const d=i.value;if(typeof d=="number"&&!Number.isNaN(d)&&Number.isFinite(d))return i;const f=typeof d=="number"?Number.isNaN(d)?"NaN":Number.isFinite(d)?void 0:"Infinity":void 0;return i.issues.push({expected:"number",code:"invalid_type",input:d,inst:t,...f?{received:f}:{}}),i}}),v0=oe("$ZodNumber",(t,r)=>{L1.init(t,r),gc.init(t,r)}),C0=oe("$ZodBoolean",(t,r)=>{ht.init(t,r),t._zod.pattern=R1,t._zod.parse=(i,c)=>{if(r.coerce)try{i.value=!!i.value}catch{}const d=i.value;return typeof d=="boolean"||i.issues.push({expected:"boolean",code:"invalid_type",input:d,inst:t}),i}}),b0=oe("$ZodNull",(t,r)=>{ht.init(t,r),t._zod.pattern=M1,t._zod.values=new Set([null]),t._zod.parse=(i,c)=>{const d=i.value;return d===null||i.issues.push({expected:"null",code:"invalid_type",input:d,inst:t}),i}}),A0=oe("$ZodAny",(t,r)=>{ht.init(t,r),t._zod.parse=i=>i}),E0=oe("$ZodUnknown",(t,r)=>{ht.init(t,r),t._zod.parse=i=>i}),I0=oe("$ZodNever",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>(i.issues.push({expected:"never",code:"invalid_type",input:i.value,inst:t}),i)});function Ns(t,r,i){t.issues.length&&r.issues.push(...hr(i,t.issues)),r.value[i]=t.value}const S0=oe("$ZodArray",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=i.value;if(!Array.isArray(d))return i.issues.push({expected:"array",code:"invalid_type",input:d,inst:t}),i;i.value=Array(d.length);const f=[];for(let m=0;m<d.length;m++){const x=d[m],v=r.element._zod.run({value:x,issues:[]},c);v instanceof Promise?f.push(v.then(g=>Ns(g,i,m))):Ns(v,i,m)}return f.length?Promise.all(f).then(()=>i):i}});function vo(t,r,i){t.issues.length&&r.issues.push(...hr(i,t.issues)),r.value[i]=t.value}function Os(t,r,i,c){t.issues.length?c[i]===void 0?i in c?r.value[i]=void 0:r.value[i]=t.value:r.issues.push(...hr(i,t.issues)):t.value===void 0?i in c&&(r.value[i]=void 0):r.value[i]=t.value}const T0=oe("$ZodObject",(t,r)=>{ht.init(t,r);const i=Ui(()=>{const A=Object.keys(r.shape);for(const T of A)if(!(r.shape[T]instanceof ht))throw new Error(`Invalid element at key "${T}": expected a Zod schema`);const D=qd(r.shape);return{shape:r.shape,keys:A,keySet:new Set(A),numKeys:A.length,optionalKeys:new Set(D)}});lt(t._zod,"propValues",()=>{const A=r.shape,D={};for(const T in A){const S=A[T]._zod;if(S.values){D[T]??(D[T]=new Set);for(const P of S.values)D[T].add(P)}}return D});const c=A=>{const D=new q1(["shape","payload","ctx"]),T=i.value,S=$=>{const F=Zr($);return`shape[${F}]._zod.run({ value: input[${F}], issues: [] }, ctx)`};D.write("const input = payload.value;");const P=Object.create(null);let M=0;for(const $ of T.keys)P[$]=`key_${M++}`;D.write("const newResult = {}");for(const $ of T.keys)if(T.optionalKeys.has($)){const F=P[$];D.write(`const ${F} = ${S($)};`);const re=Zr($);D.write(`
15
+ if (${F}.issues.length) {
16
+ if (input[${re}] === undefined) {
17
+ if (${re} in input) {
18
+ newResult[${re}] = undefined;
14
19
  }
15
20
  } else {
16
21
  payload.issues = payload.issues.concat(
17
- ${z}.issues.map((iss) => ({
22
+ ${F}.issues.map((iss) => ({
18
23
  ...iss,
19
- path: iss.path ? [${ee}, ...iss.path] : [${ee}],
24
+ path: iss.path ? [${re}, ...iss.path] : [${re}],
20
25
  }))
21
26
  );
22
27
  }
23
- } else if (${z}.value === undefined) {
24
- if (${ee} in input) newResult[${ee}] = undefined;
28
+ } else if (${F}.value === undefined) {
29
+ if (${re} in input) newResult[${re}] = undefined;
25
30
  } else {
26
- newResult[${ee}] = ${z}.value;
31
+ newResult[${re}] = ${F}.value;
27
32
  }
28
- `)}else{const z=D[Z];P.write(`const ${z} = ${M(Z)};`),P.write(`
29
- if (${z}.issues.length) payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
33
+ `)}else{const F=P[$];D.write(`const ${F} = ${S($)};`),D.write(`
34
+ if (${F}.issues.length) payload.issues = payload.issues.concat(${F}.issues.map(iss => ({
30
35
  ...iss,
31
- path: iss.path ? [${Ur(Z)}, ...iss.path] : [${Ur(Z)}]
32
- })));`),P.write(`newResult[${Ur(Z)}] = ${z}.value`)}P.write("payload.value = newResult;"),P.write("return payload;");const G=P.compile();return(Z,z)=>G(v,Z,z)};let u;const f=Ii,m=!jl.jitless,C=m&&Rd.value,x=r.catchall;let A;t._zod.parse=(v,P)=>{A??(A=o.value);const O=v.value;if(!f(O))return v.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),v;const M=[];if(m&&C&&P?.async===!1&&P.jitless!==!0)u||(u=c(r.shape)),v=u(v,P);else{v.value={};const z=A.shape;for(const ee of A.keys){const K=z[ee],V=K._zod.run({value:O[ee],issues:[]},P),U=K._zod.optin==="optional"&&K._zod.optout==="optional";V instanceof Promise?M.push(V.then(J=>U?bs(J,v,ee,O):gi(J,v,ee))):U?bs(V,v,ee,O):gi(V,v,ee)}}if(!x)return M.length?Promise.all(M).then(()=>v):v;const D=[],B=A.keySet,G=x._zod,Z=G.def.type;for(const z of Object.keys(O)){if(B.has(z))continue;if(Z==="never"){D.push(z);continue}const ee=G.run({value:O[z],issues:[]},P);ee instanceof Promise?M.push(ee.then(K=>gi(K,v,z))):gi(ee,v,z)}return D.length&&v.issues.push({code:"unrecognized_keys",keys:D,input:O,inst:t}),M.length?Promise.all(M).then(()=>v):v}});function Es(t,r,o,c){for(const u of t)if(u.issues.length===0)return r.value=u.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:o,errors:t.map(u=>u.issues.map(f=>er(f,c,Qn())))}),r}const lc=te("$ZodUnion",(t,r)=>{at.init(t,r),tt(t._zod,"optin",()=>r.options.some(o=>o._zod.optin==="optional")?"optional":void 0),tt(t._zod,"optout",()=>r.options.some(o=>o._zod.optout==="optional")?"optional":void 0),tt(t._zod,"values",()=>{if(r.options.every(o=>o._zod.values))return new Set(r.options.flatMap(o=>Array.from(o._zod.values)))}),tt(t._zod,"pattern",()=>{if(r.options.every(o=>o._zod.pattern)){const o=r.options.map(c=>c._zod.pattern);return new RegExp(`^(${o.map(c=>Lo(c.source)).join("|")})$`)}}),t._zod.parse=(o,c)=>{let u=!1;const f=[];for(const m of r.options){const g=m._zod.run({value:o.value,issues:[]},c);if(g instanceof Promise)f.push(g),u=!0;else{if(g.issues.length===0)return g;f.push(g)}}return u?Promise.all(f).then(m=>Es(m,o,t,c)):Es(f,o,t,c)}}),m0=te("$ZodDiscriminatedUnion",(t,r)=>{lc.init(t,r);const o=t._zod.parse;tt(t._zod,"propValues",()=>{const u={};for(const f of r.options){const m=f._zod.propValues;if(!m||Object.keys(m).length===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(f)}"`);for(const[g,C]of Object.entries(m)){u[g]||(u[g]=new Set);for(const x of C)u[g].add(x)}}return u});const c=Po(()=>{const u=r.options,f=new Map;for(const m of u){const g=m._zod.propValues[r.discriminator];if(!g||g.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(m)}"`);for(const C of g){if(f.has(C))throw new Error(`Duplicate discriminator value "${String(C)}"`);f.set(C,m)}}return f});t._zod.parse=(u,f)=>{const m=u.value;if(!Ii(m))return u.issues.push({code:"invalid_type",expected:"object",input:m,inst:t}),u;const g=c.value.get(m?.[r.discriminator]);return g?g._zod.run(u,f):r.unionFallback?o(u,f):(u.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:m,path:[r.discriminator],inst:t}),u)}}),g0=te("$ZodIntersection",(t,r)=>{at.init(t,r),t._zod.parse=(o,c)=>{const u=o.value,f=r.left._zod.run({value:u,issues:[]},c),m=r.right._zod.run({value:u,issues:[]},c);return f instanceof Promise||m instanceof Promise?Promise.all([f,m]).then(([C,x])=>As(o,C,x)):As(o,f,m)}});function yo(t,r){if(t===r)return{valid:!0,data:t};if(t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(Si(t)&&Si(r)){const o=Object.keys(r),c=Object.keys(t).filter(f=>o.indexOf(f)!==-1),u={...t,...r};for(const f of c){const m=yo(t[f],r[f]);if(!m.valid)return{valid:!1,mergeErrorPath:[f,...m.mergeErrorPath]};u[f]=m.data}return{valid:!0,data:u}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};const o=[];for(let c=0;c<t.length;c++){const u=t[c],f=r[c],m=yo(u,f);if(!m.valid)return{valid:!1,mergeErrorPath:[c,...m.mergeErrorPath]};o.push(m.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function As(t,r,o){if(r.issues.length&&t.issues.push(...r.issues),o.issues.length&&t.issues.push(...o.issues),jr(t))return t;const c=yo(r.value,o.value);if(!c.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`);return t.value=c.data,t}const x0=te("$ZodRecord",(t,r)=>{at.init(t,r),t._zod.parse=(o,c)=>{const u=o.value;if(!Si(u))return o.issues.push({expected:"record",code:"invalid_type",input:u,inst:t}),o;const f=[];if(r.keyType._zod.values){const m=r.keyType._zod.values;o.value={};for(const C of m)if(typeof C=="string"||typeof C=="number"||typeof C=="symbol"){const x=r.valueType._zod.run({value:u[C],issues:[]},c);x instanceof Promise?f.push(x.then(A=>{A.issues.length&&o.issues.push(...dr(C,A.issues)),o.value[C]=A.value})):(x.issues.length&&o.issues.push(...dr(C,x.issues)),o.value[C]=x.value)}let g;for(const C in u)m.has(C)||(g=g??[],g.push(C));g&&g.length>0&&o.issues.push({code:"unrecognized_keys",input:u,inst:t,keys:g})}else{o.value={};for(const m of Reflect.ownKeys(u)){if(m==="__proto__")continue;const g=r.keyType._zod.run({value:m,issues:[]},c);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(g.issues.length){o.issues.push({origin:"record",code:"invalid_key",issues:g.issues.map(x=>er(x,c,Qn())),input:m,path:[m],inst:t}),o.value[g.value]=g.value;continue}const C=r.valueType._zod.run({value:u[m],issues:[]},c);C instanceof Promise?f.push(C.then(x=>{x.issues.length&&o.issues.push(...dr(m,x.issues)),o.value[g.value]=x.value})):(C.issues.length&&o.issues.push(...dr(m,C.issues)),o.value[g.value]=C.value)}}return f.length?Promise.all(f).then(()=>o):o}}),y0=te("$ZodEnum",(t,r)=>{at.init(t,r);const o=Gl(r.entries);t._zod.values=new Set(o),t._zod.pattern=new RegExp(`^(${o.filter(c=>Md.has(typeof c)).map(c=>typeof c=="string"?ti(c):c.toString()).join("|")})$`),t._zod.parse=(c,u)=>{const f=c.value;return t._zod.values.has(f)||c.issues.push({code:"invalid_value",values:o,input:f,inst:t}),c}}),w0=te("$ZodLiteral",(t,r)=>{at.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(o=>typeof o=="string"?ti(o):o?o.toString():String(o)).join("|")})$`),t._zod.parse=(o,c)=>{const u=o.value;return t._zod.values.has(u)||o.issues.push({code:"invalid_value",values:r.values,input:u,inst:t}),o}}),_0=te("$ZodTransform",(t,r)=>{at.init(t,r),t._zod.parse=(o,c)=>{const u=r.transform(o.value,o);if(c.async)return(u instanceof Promise?u:Promise.resolve(u)).then(m=>(o.value=m,o));if(u instanceof Promise)throw new qr;return o.value=u,o}}),v0=te("$ZodOptional",(t,r)=>{at.init(t,r),t._zod.optin="optional",t._zod.optout="optional",tt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),tt(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Lo(o.source)})?$`):void 0}),t._zod.parse=(o,c)=>r.innerType._zod.optin==="optional"?r.innerType._zod.run(o,c):o.value===void 0?o:r.innerType._zod.run(o,c)}),C0=te("$ZodNullable",(t,r)=>{at.init(t,r),tt(t._zod,"optin",()=>r.innerType._zod.optin),tt(t._zod,"optout",()=>r.innerType._zod.optout),tt(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Lo(o.source)}|null)$`):void 0}),tt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(o,c)=>o.value===null?o:r.innerType._zod.run(o,c)}),b0=te("$ZodDefault",(t,r)=>{at.init(t,r),t._zod.optin="optional",tt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>{if(o.value===void 0)return o.value=r.defaultValue,o;const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>Is(f,r)):Is(u,r)}});function Is(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const E0=te("$ZodPrefault",(t,r)=>{at.init(t,r),t._zod.optin="optional",tt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>(o.value===void 0&&(o.value=r.defaultValue),r.innerType._zod.run(o,c))}),A0=te("$ZodNonOptional",(t,r)=>{at.init(t,r),tt(t._zod,"values",()=>{const o=r.innerType._zod.values;return o?new Set([...o].filter(c=>c!==void 0)):void 0}),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>Ss(f,t)):Ss(u,t)}});function Ss(t,r){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}const I0=te("$ZodCatch",(t,r)=>{at.init(t,r),t._zod.optin="optional",tt(t._zod,"optout",()=>r.innerType._zod.optout),tt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>(o.value=f.value,f.issues.length&&(o.value=r.catchValue({...o,error:{issues:f.issues.map(m=>er(m,c,Qn()))},input:o.value}),o.issues=[]),o)):(o.value=u.value,u.issues.length&&(o.value=r.catchValue({...o,error:{issues:u.issues.map(f=>er(f,c,Qn()))},input:o.value}),o.issues=[]),o)}}),S0=te("$ZodPipe",(t,r)=>{at.init(t,r),tt(t._zod,"values",()=>r.in._zod.values),tt(t._zod,"optin",()=>r.in._zod.optin),tt(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(o,c)=>{const u=r.in._zod.run(o,c);return u instanceof Promise?u.then(f=>Ts(f,r,c)):Ts(u,r,c)}});function Ts(t,r,o){return jr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},o)}const T0=te("$ZodReadonly",(t,r)=>{at.init(t,r),tt(t._zod,"propValues",()=>r.innerType._zod.propValues),tt(t._zod,"values",()=>r.innerType._zod.values),tt(t._zod,"optin",()=>r.innerType._zod.optin),tt(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(Ns):Ns(u)}});function Ns(t){return t.value=Object.freeze(t.value),t}const N0=te("$ZodLazy",(t,r)=>{at.init(t,r),tt(t._zod,"innerType",()=>r.getter()),tt(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),tt(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),tt(t._zod,"optin",()=>t._zod.innerType._zod.optin),tt(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(o,c)=>t._zod.innerType._zod.run(o,c)}),O0=te("$ZodCustom",(t,r)=>{on.init(t,r),at.init(t,r),t._zod.parse=(o,c)=>o,t._zod.check=o=>{const c=o.value,u=r.fn(c);if(u instanceof Promise)return u.then(f=>Os(f,o,c,t));Os(u,o,c,t)}});function Os(t,r,o,c){if(!t){const u={code:"custom",input:o,inst:c,path:[...c._zod.def.path??[]],continue:!c._zod.def.abort};c._zod.def.params&&(u.params=c._zod.def.params),r.issues.push(Yr(u))}}class cc{constructor(){this._map=new Map,this._idmap=new Map}add(r,...o){const c=o[0];if(this._map.set(r,c),c&&typeof c=="object"&&"id"in c){if(this._idmap.has(c.id))throw new Error(`ID ${c.id} already exists in the registry`);this._idmap.set(c.id,r)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(r){const o=this._map.get(r);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(r),this}get(r){const o=r._zod.parent;if(o){const c={...this.get(o)??{}};return delete c.id,{...c,...this._map.get(r)}}return this._map.get(r)}has(r){return this._map.has(r)}}function k0(){return new cc}const $r=k0();function R0(t,r){return new t({type:"string",...Ae(r)})}function M0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Ae(r)})}function ks(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Ae(r)})}function D0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Ae(r)})}function P0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ae(r)})}function B0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ae(r)})}function L0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ae(r)})}function F0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Ae(r)})}function U0(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Ae(r)})}function z0(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ae(r)})}function V0(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Ae(r)})}function Z0(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ae(r)})}function $0(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Ae(r)})}function H0(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Ae(r)})}function W0(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ae(r)})}function j0(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ae(r)})}function G0(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ae(r)})}function X0(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ae(r)})}function q0(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ae(r)})}function Y0(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Ae(r)})}function K0(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Ae(r)})}function J0(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Ae(r)})}function Q0(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Ae(r)})}function ef(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ae(r)})}function tf(t,r){return new t({type:"string",format:"date",check:"string_format",...Ae(r)})}function nf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...Ae(r)})}function rf(t,r){return new t({type:"string",format:"duration",check:"string_format",...Ae(r)})}function of(t,r){return new t({type:"number",checks:[],...Ae(r)})}function sf(t,r){return new t({type:"number",coerce:!0,checks:[],...Ae(r)})}function af(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Ae(r)})}function lf(t,r){return new t({type:"boolean",...Ae(r)})}function cf(t,r){return new t({type:"null",...Ae(r)})}function uf(t){return new t({type:"any"})}function df(t){return new t({type:"unknown"})}function ff(t,r){return new t({type:"never",...Ae(r)})}function Rs(t,r){return new ic({check:"less_than",...Ae(r),value:t,inclusive:!1})}function ro(t,r){return new ic({check:"less_than",...Ae(r),value:t,inclusive:!0})}function Ms(t,r){return new oc({check:"greater_than",...Ae(r),value:t,inclusive:!1})}function io(t,r){return new oc({check:"greater_than",...Ae(r),value:t,inclusive:!0})}function Ds(t,r){return new C1({check:"multiple_of",...Ae(r),value:t})}function uc(t,r){return new E1({check:"max_length",...Ae(r),maximum:t})}function Ti(t,r){return new A1({check:"min_length",...Ae(r),minimum:t})}function dc(t,r){return new I1({check:"length_equals",...Ae(r),length:t})}function hf(t,r){return new S1({check:"string_format",format:"regex",...Ae(r),pattern:t})}function pf(t){return new T1({check:"string_format",format:"lowercase",...Ae(t)})}function mf(t){return new N1({check:"string_format",format:"uppercase",...Ae(t)})}function gf(t,r){return new O1({check:"string_format",format:"includes",...Ae(r),includes:t})}function xf(t,r){return new k1({check:"string_format",format:"starts_with",...Ae(r),prefix:t})}function yf(t,r){return new R1({check:"string_format",format:"ends_with",...Ae(r),suffix:t})}function ni(t){return new M1({check:"overwrite",tx:t})}function wf(t){return ni(r=>r.normalize(t))}function _f(){return ni(t=>t.trim())}function vf(){return ni(t=>t.toLowerCase())}function Cf(){return ni(t=>t.toUpperCase())}function bf(t,r,o){return new t({type:"array",element:r,...Ae(o)})}function Ef(t,r,o){return new t({type:"custom",check:"custom",fn:r,...Ae(o)})}class Ps{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??$r,this.target=r?.target??"draft-2020-12",this.unrepresentable=r?.unrepresentable??"throw",this.override=r?.override??(()=>{}),this.io=r?.io??"output",this.seen=new Map}process(r,o={path:[],schemaPath:[]}){var c;const u=r._zod.def,f={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},m=this.seen.get(r);if(m)return m.count++,o.schemaPath.includes(r)&&(m.cycle=o.path),m.schema;const g={schema:{},count:1,cycle:void 0,path:o.path};this.seen.set(r,g);const C=r._zod.toJSONSchema?.();if(C)g.schema=C;else{const v={...o,schemaPath:[...o.schemaPath,r],path:o.path},P=r._zod.parent;if(P)g.ref=P,this.process(P,v),this.seen.get(P).isParent=!0;else{const O=g.schema;switch(u.type){case"string":{const M=O;M.type="string";const{minimum:D,maximum:B,format:G,patterns:Z,contentEncoding:z}=r._zod.bag;if(typeof D=="number"&&(M.minLength=D),typeof B=="number"&&(M.maxLength=B),G&&(M.format=f[G]??G,M.format===""&&delete M.format),z&&(M.contentEncoding=z),Z&&Z.size>0){const ee=[...Z];ee.length===1?M.pattern=ee[0].source:ee.length>1&&(g.schema.allOf=[...ee.map(K=>({...this.target==="draft-7"?{type:"string"}:{},pattern:K.source}))])}break}case"number":{const M=O,{minimum:D,maximum:B,format:G,multipleOf:Z,exclusiveMaximum:z,exclusiveMinimum:ee}=r._zod.bag;typeof G=="string"&&G.includes("int")?M.type="integer":M.type="number",typeof ee=="number"&&(M.exclusiveMinimum=ee),typeof D=="number"&&(M.minimum=D,typeof ee=="number"&&(ee>=D?delete M.minimum:delete M.exclusiveMinimum)),typeof z=="number"&&(M.exclusiveMaximum=z),typeof B=="number"&&(M.maximum=B,typeof z=="number"&&(z<=B?delete M.maximum:delete M.exclusiveMaximum)),typeof Z=="number"&&(M.multipleOf=Z);break}case"boolean":{const M=O;M.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{O.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{O.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const M=O,{minimum:D,maximum:B}=r._zod.bag;typeof D=="number"&&(M.minItems=D),typeof B=="number"&&(M.maxItems=B),M.type="array",M.items=this.process(u.element,{...v,path:[...v.path,"items"]});break}case"object":{const M=O;M.type="object",M.properties={};const D=u.shape;for(const Z in D)M.properties[Z]=this.process(D[Z],{...v,path:[...v.path,"properties",Z]});const B=new Set(Object.keys(D)),G=new Set([...B].filter(Z=>{const z=u.shape[Z]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));G.size>0&&(M.required=Array.from(G)),u.catchall?._zod.def.type==="never"?M.additionalProperties=!1:u.catchall?u.catchall&&(M.additionalProperties=this.process(u.catchall,{...v,path:[...v.path,"additionalProperties"]})):this.io==="output"&&(M.additionalProperties=!1);break}case"union":{const M=O;M.anyOf=u.options.map((D,B)=>this.process(D,{...v,path:[...v.path,"anyOf",B]}));break}case"intersection":{const M=O,D=this.process(u.left,{...v,path:[...v.path,"allOf",0]}),B=this.process(u.right,{...v,path:[...v.path,"allOf",1]}),G=z=>"allOf"in z&&Object.keys(z).length===1,Z=[...G(D)?D.allOf:[D],...G(B)?B.allOf:[B]];M.allOf=Z;break}case"tuple":{const M=O;M.type="array";const D=u.items.map((Z,z)=>this.process(Z,{...v,path:[...v.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?M.prefixItems=D:M.items=D,u.rest){const Z=this.process(u.rest,{...v,path:[...v.path,"items"]});this.target==="draft-2020-12"?M.items=Z:M.additionalItems=Z}u.rest&&(M.items=this.process(u.rest,{...v,path:[...v.path,"items"]}));const{minimum:B,maximum:G}=r._zod.bag;typeof B=="number"&&(M.minItems=B),typeof G=="number"&&(M.maxItems=G);break}case"record":{const M=O;M.type="object",M.propertyNames=this.process(u.keyType,{...v,path:[...v.path,"propertyNames"]}),M.additionalProperties=this.process(u.valueType,{...v,path:[...v.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const M=O,D=Gl(u.entries);D.every(B=>typeof B=="number")&&(M.type="number"),D.every(B=>typeof B=="string")&&(M.type="string"),M.enum=D;break}case"literal":{const M=O,D=[];for(const B of u.values)if(B===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof B=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");D.push(Number(B))}else D.push(B);if(D.length!==0)if(D.length===1){const B=D[0];M.type=B===null?"null":typeof B,M.const=B}else D.every(B=>typeof B=="number")&&(M.type="number"),D.every(B=>typeof B=="string")&&(M.type="string"),D.every(B=>typeof B=="boolean")&&(M.type="string"),D.every(B=>B===null)&&(M.type="null"),M.enum=D;break}case"file":{const M=O,D={type:"string",format:"binary",contentEncoding:"binary"},{minimum:B,maximum:G,mime:Z}=r._zod.bag;B!==void 0&&(D.minLength=B),G!==void 0&&(D.maxLength=G),Z?Z.length===1?(D.contentMediaType=Z[0],Object.assign(M,D)):M.anyOf=Z.map(z=>({...D,contentMediaType:z})):Object.assign(M,D);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const M=this.process(u.innerType,v);O.anyOf=[M,{type:"null"}];break}case"nonoptional":{this.process(u.innerType,v),g.ref=u.innerType;break}case"success":{const M=O;M.type="boolean";break}case"default":{this.process(u.innerType,v),g.ref=u.innerType,O.default=JSON.parse(JSON.stringify(u.defaultValue));break}case"prefault":{this.process(u.innerType,v),g.ref=u.innerType,this.io==="input"&&(O._prefault=JSON.parse(JSON.stringify(u.defaultValue)));break}case"catch":{this.process(u.innerType,v),g.ref=u.innerType;let M;try{M=u.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}O.default=M;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const M=O,D=r._zod.pattern;if(!D)throw new Error("Pattern not found in template literal");M.type="string",M.pattern=D.source;break}case"pipe":{const M=this.io==="input"?u.in._zod.def.type==="transform"?u.out:u.in:u.out;this.process(M,v),g.ref=M;break}case"readonly":{this.process(u.innerType,v),g.ref=u.innerType,O.readOnly=!0;break}case"promise":{this.process(u.innerType,v),g.ref=u.innerType;break}case"optional":{this.process(u.innerType,v),g.ref=u.innerType;break}case"lazy":{const M=r._zod.innerType;this.process(M,v),g.ref=M;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const x=this.metadataRegistry.get(r);return x&&Object.assign(g.schema,x),this.io==="input"&&Pt(r)&&(delete g.schema.examples,delete g.schema.default),this.io==="input"&&g.schema._prefault&&((c=g.schema).default??(c.default=g.schema._prefault)),delete g.schema._prefault,this.seen.get(r).schema}emit(r,o){const c={cycles:o?.cycles??"ref",reused:o?.reused??"inline",external:o?.external??void 0},u=this.seen.get(r);if(!u)throw new Error("Unprocessed schema. This is a bug in Zod.");const f=A=>{const v=this.target==="draft-2020-12"?"$defs":"definitions";if(c.external){const D=c.external.registry.get(A[0])?.id,B=c.external.uri??(Z=>Z);if(D)return{ref:B(D)};const G=A[1].defId??A[1].schema.id??`schema${this.counter++}`;return A[1].defId=G,{defId:G,ref:`${B("__shared")}#/${v}/${G}`}}if(A[1]===u)return{ref:"#"};const O=`#/${v}/`,M=A[1].schema.id??`__schema${this.counter++}`;return{defId:M,ref:O+M}},m=A=>{if(A[1].schema.$ref)return;const v=A[1],{ref:P,defId:O}=f(A);v.def={...v.schema},O&&(v.defId=O);const M=v.schema;for(const D in M)delete M[D];M.$ref=P};if(c.cycles==="throw")for(const A of this.seen.entries()){const v=A[1];if(v.cycle)throw new Error(`Cycle detected: #/${v.cycle?.join("/")}/<root>
36
+ path: iss.path ? [${Zr($)}, ...iss.path] : [${Zr($)}]
37
+ })));`),D.write(`newResult[${Zr($)}] = ${F}.value`)}D.write("payload.value = newResult;"),D.write("return payload;");const ee=D.compile();return($,F)=>ee(A,$,F)};let d;const f=ko,m=!tc.jitless,v=m&&Wd.value,g=r.catchall;let E;t._zod.parse=(A,D)=>{E??(E=i.value);const T=A.value;if(!f(T))return A.issues.push({expected:"object",code:"invalid_type",input:T,inst:t}),A;const S=[];if(m&&v&&D?.async===!1&&D.jitless!==!0)d||(d=c(r.shape)),A=d(A,D);else{A.value={};const F=E.shape;for(const re of E.keys){const Z=F[re],B=Z._zod.run({value:T[re],issues:[]},D),L=Z._zod.optin==="optional"&&Z._zod.optout==="optional";B instanceof Promise?S.push(B.then(W=>L?Os(W,A,re,T):vo(W,A,re))):L?Os(B,A,re,T):vo(B,A,re)}}if(!g)return S.length?Promise.all(S).then(()=>A):A;const P=[],M=E.keySet,ee=g._zod,$=ee.def.type;for(const F of Object.keys(T)){if(M.has(F))continue;if($==="never"){P.push(F);continue}const re=ee.run({value:T[F],issues:[]},D);re instanceof Promise?S.push(re.then(Z=>vo(Z,A,F))):vo(re,A,F)}return P.length&&A.issues.push({code:"unrecognized_keys",keys:P,input:T,inst:t}),S.length?Promise.all(S).then(()=>A):A}});function ks(t,r,i,c){for(const d of t)if(d.issues.length===0)return r.value=d.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:i,errors:t.map(d=>d.issues.map(f=>er(f,c,Qn())))}),r}const xc=oe("$ZodUnion",(t,r)=>{ht.init(t,r),lt(t._zod,"optin",()=>r.options.some(i=>i._zod.optin==="optional")?"optional":void 0),lt(t._zod,"optout",()=>r.options.some(i=>i._zod.optout==="optional")?"optional":void 0),lt(t._zod,"values",()=>{if(r.options.every(i=>i._zod.values))return new Set(r.options.flatMap(i=>Array.from(i._zod.values)))}),lt(t._zod,"pattern",()=>{if(r.options.every(i=>i._zod.pattern)){const i=r.options.map(c=>c._zod.pattern);return new RegExp(`^(${i.map(c=>Vi(c.source)).join("|")})$`)}}),t._zod.parse=(i,c)=>{let d=!1;const f=[];for(const m of r.options){const x=m._zod.run({value:i.value,issues:[]},c);if(x instanceof Promise)f.push(x),d=!0;else{if(x.issues.length===0)return x;f.push(x)}}return d?Promise.all(f).then(m=>ks(m,i,t,c)):ks(f,i,t,c)}}),N0=oe("$ZodDiscriminatedUnion",(t,r)=>{xc.init(t,r);const i=t._zod.parse;lt(t._zod,"propValues",()=>{const d={};for(const f of r.options){const m=f._zod.propValues;if(!m||Object.keys(m).length===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(f)}"`);for(const[x,v]of Object.entries(m)){d[x]||(d[x]=new Set);for(const g of v)d[x].add(g)}}return d});const c=Ui(()=>{const d=r.options,f=new Map;for(const m of d){const x=m._zod.propValues[r.discriminator];if(!x||x.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(m)}"`);for(const v of x){if(f.has(v))throw new Error(`Duplicate discriminator value "${String(v)}"`);f.set(v,m)}}return f});t._zod.parse=(d,f)=>{const m=d.value;if(!ko(m))return d.issues.push({code:"invalid_type",expected:"object",input:m,inst:t}),d;const x=c.value.get(m?.[r.discriminator]);return x?x._zod.run(d,f):r.unionFallback?i(d,f):(d.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:m,path:[r.discriminator],inst:t}),d)}}),O0=oe("$ZodIntersection",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=i.value,f=r.left._zod.run({value:d,issues:[]},c),m=r.right._zod.run({value:d,issues:[]},c);return f instanceof Promise||m instanceof Promise?Promise.all([f,m]).then(([v,g])=>Rs(i,v,g)):Rs(i,f,m)}});function bi(t,r){if(t===r)return{valid:!0,data:t};if(t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(Ro(t)&&Ro(r)){const i=Object.keys(r),c=Object.keys(t).filter(f=>i.indexOf(f)!==-1),d={...t,...r};for(const f of c){const m=bi(t[f],r[f]);if(!m.valid)return{valid:!1,mergeErrorPath:[f,...m.mergeErrorPath]};d[f]=m.data}return{valid:!0,data:d}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};const i=[];for(let c=0;c<t.length;c++){const d=t[c],f=r[c],m=bi(d,f);if(!m.valid)return{valid:!1,mergeErrorPath:[c,...m.mergeErrorPath]};i.push(m.data)}return{valid:!0,data:i}}return{valid:!1,mergeErrorPath:[]}}function Rs(t,r,i){if(r.issues.length&&t.issues.push(...r.issues),i.issues.length&&t.issues.push(...i.issues),Yr(t))return t;const c=bi(r.value,i.value);if(!c.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`);return t.value=c.data,t}const k0=oe("$ZodRecord",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=i.value;if(!Ro(d))return i.issues.push({expected:"record",code:"invalid_type",input:d,inst:t}),i;const f=[];if(r.keyType._zod.values){const m=r.keyType._zod.values;i.value={};for(const v of m)if(typeof v=="string"||typeof v=="number"||typeof v=="symbol"){const g=r.valueType._zod.run({value:d[v],issues:[]},c);g instanceof Promise?f.push(g.then(E=>{E.issues.length&&i.issues.push(...hr(v,E.issues)),i.value[v]=E.value})):(g.issues.length&&i.issues.push(...hr(v,g.issues)),i.value[v]=g.value)}let x;for(const v in d)m.has(v)||(x=x??[],x.push(v));x&&x.length>0&&i.issues.push({code:"unrecognized_keys",input:d,inst:t,keys:x})}else{i.value={};for(const m of Reflect.ownKeys(d)){if(m==="__proto__")continue;const x=r.keyType._zod.run({value:m,issues:[]},c);if(x instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(x.issues.length){i.issues.push({origin:"record",code:"invalid_key",issues:x.issues.map(g=>er(g,c,Qn())),input:m,path:[m],inst:t}),i.value[x.value]=x.value;continue}const v=r.valueType._zod.run({value:d[m],issues:[]},c);v instanceof Promise?f.push(v.then(g=>{g.issues.length&&i.issues.push(...hr(m,g.issues)),i.value[x.value]=g.value})):(v.issues.length&&i.issues.push(...hr(m,v.issues)),i.value[x.value]=v.value)}}return f.length?Promise.all(f).then(()=>i):i}}),R0=oe("$ZodEnum",(t,r)=>{ht.init(t,r);const i=nc(r.entries);t._zod.values=new Set(i),t._zod.pattern=new RegExp(`^(${i.filter(c=>Gd.has(typeof c)).map(c=>typeof c=="string"?io(c):c.toString()).join("|")})$`),t._zod.parse=(c,d)=>{const f=c.value;return t._zod.values.has(f)||c.issues.push({code:"invalid_value",values:i,input:f,inst:t}),c}}),M0=oe("$ZodLiteral",(t,r)=>{ht.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(i=>typeof i=="string"?io(i):i?i.toString():String(i)).join("|")})$`),t._zod.parse=(i,c)=>{const d=i.value;return t._zod.values.has(d)||i.issues.push({code:"invalid_value",values:r.values,input:d,inst:t}),i}}),D0=oe("$ZodTransform",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=r.transform(i.value,i);if(c.async)return(d instanceof Promise?d:Promise.resolve(d)).then(m=>(i.value=m,i));if(d instanceof Promise)throw new Qr;return i.value=d,i}}),P0=oe("$ZodOptional",(t,r)=>{ht.init(t,r),t._zod.optin="optional",t._zod.optout="optional",lt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),lt(t._zod,"pattern",()=>{const i=r.innerType._zod.pattern;return i?new RegExp(`^(${Vi(i.source)})?$`):void 0}),t._zod.parse=(i,c)=>r.innerType._zod.optin==="optional"?r.innerType._zod.run(i,c):i.value===void 0?i:r.innerType._zod.run(i,c)}),B0=oe("$ZodNullable",(t,r)=>{ht.init(t,r),lt(t._zod,"optin",()=>r.innerType._zod.optin),lt(t._zod,"optout",()=>r.innerType._zod.optout),lt(t._zod,"pattern",()=>{const i=r.innerType._zod.pattern;return i?new RegExp(`^(${Vi(i.source)}|null)$`):void 0}),lt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(i,c)=>i.value===null?i:r.innerType._zod.run(i,c)}),L0=oe("$ZodDefault",(t,r)=>{ht.init(t,r),t._zod.optin="optional",lt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(i,c)=>{if(i.value===void 0)return i.value=r.defaultValue,i;const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(f=>Ms(f,r)):Ms(d,r)}});function Ms(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const F0=oe("$ZodPrefault",(t,r)=>{ht.init(t,r),t._zod.optin="optional",lt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(i,c)=>(i.value===void 0&&(i.value=r.defaultValue),r.innerType._zod.run(i,c))}),U0=oe("$ZodNonOptional",(t,r)=>{ht.init(t,r),lt(t._zod,"values",()=>{const i=r.innerType._zod.values;return i?new Set([...i].filter(c=>c!==void 0)):void 0}),t._zod.parse=(i,c)=>{const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(f=>Ds(f,t)):Ds(d,t)}});function Ds(t,r){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}const z0=oe("$ZodCatch",(t,r)=>{ht.init(t,r),t._zod.optin="optional",lt(t._zod,"optout",()=>r.innerType._zod.optout),lt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(i,c)=>{const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(f=>(i.value=f.value,f.issues.length&&(i.value=r.catchValue({...i,error:{issues:f.issues.map(m=>er(m,c,Qn()))},input:i.value}),i.issues=[]),i)):(i.value=d.value,d.issues.length&&(i.value=r.catchValue({...i,error:{issues:d.issues.map(f=>er(f,c,Qn()))},input:i.value}),i.issues=[]),i)}}),V0=oe("$ZodPipe",(t,r)=>{ht.init(t,r),lt(t._zod,"values",()=>r.in._zod.values),lt(t._zod,"optin",()=>r.in._zod.optin),lt(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(i,c)=>{const d=r.in._zod.run(i,c);return d instanceof Promise?d.then(f=>Ps(f,r,c)):Ps(d,r,c)}});function Ps(t,r,i){return Yr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},i)}const Z0=oe("$ZodReadonly",(t,r)=>{ht.init(t,r),lt(t._zod,"propValues",()=>r.innerType._zod.propValues),lt(t._zod,"values",()=>r.innerType._zod.values),lt(t._zod,"optin",()=>r.innerType._zod.optin),lt(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(i,c)=>{const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(Bs):Bs(d)}});function Bs(t){return t.value=Object.freeze(t.value),t}const $0=oe("$ZodLazy",(t,r)=>{ht.init(t,r),lt(t._zod,"innerType",()=>r.getter()),lt(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),lt(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),lt(t._zod,"optin",()=>t._zod.innerType._zod.optin),lt(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(i,c)=>t._zod.innerType._zod.run(i,c)}),j0=oe("$ZodCustom",(t,r)=>{on.init(t,r),ht.init(t,r),t._zod.parse=(i,c)=>i,t._zod.check=i=>{const c=i.value,d=r.fn(c);if(d instanceof Promise)return d.then(f=>Ls(f,i,c,t));Ls(d,i,c,t)}});function Ls(t,r,i,c){if(!t){const d={code:"custom",input:i,inst:c,path:[...c._zod.def.path??[]],continue:!c._zod.def.abort};c._zod.def.params&&(d.params=c._zod.def.params),r.issues.push(eo(d))}}class yc{constructor(){this._map=new Map,this._idmap=new Map}add(r,...i){const c=i[0];if(this._map.set(r,c),c&&typeof c=="object"&&"id"in c){if(this._idmap.has(c.id))throw new Error(`ID ${c.id} already exists in the registry`);this._idmap.set(c.id,r)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(r){const i=this._map.get(r);return i&&typeof i=="object"&&"id"in i&&this._idmap.delete(i.id),this._map.delete(r),this}get(r){const i=r._zod.parent;if(i){const c={...this.get(i)??{}};return delete c.id,{...c,...this._map.get(r)}}return this._map.get(r)}has(r){return this._map.has(r)}}function H0(){return new yc}const Gr=H0();function W0(t,r){return new t({type:"string",...Ie(r)})}function G0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Ie(r)})}function Fs(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Ie(r)})}function q0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Ie(r)})}function X0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ie(r)})}function Y0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ie(r)})}function K0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ie(r)})}function J0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Ie(r)})}function Q0(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Ie(r)})}function ef(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ie(r)})}function tf(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Ie(r)})}function nf(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ie(r)})}function rf(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Ie(r)})}function of(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Ie(r)})}function sf(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ie(r)})}function af(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ie(r)})}function lf(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ie(r)})}function cf(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ie(r)})}function uf(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ie(r)})}function df(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Ie(r)})}function ff(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Ie(r)})}function hf(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Ie(r)})}function pf(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Ie(r)})}function mf(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ie(r)})}function gf(t,r){return new t({type:"string",format:"date",check:"string_format",...Ie(r)})}function xf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...Ie(r)})}function yf(t,r){return new t({type:"string",format:"duration",check:"string_format",...Ie(r)})}function wf(t,r){return new t({type:"number",checks:[],...Ie(r)})}function _f(t,r){return new t({type:"number",coerce:!0,checks:[],...Ie(r)})}function vf(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Ie(r)})}function Cf(t,r){return new t({type:"boolean",...Ie(r)})}function bf(t,r){return new t({type:"null",...Ie(r)})}function Af(t){return new t({type:"any"})}function Ef(t){return new t({type:"unknown"})}function If(t,r){return new t({type:"never",...Ie(r)})}function Us(t,r){return new hc({check:"less_than",...Ie(r),value:t,inclusive:!1})}function ci(t,r){return new hc({check:"less_than",...Ie(r),value:t,inclusive:!0})}function zs(t,r){return new pc({check:"greater_than",...Ie(r),value:t,inclusive:!1})}function ui(t,r){return new pc({check:"greater_than",...Ie(r),value:t,inclusive:!0})}function Vs(t,r){return new B1({check:"multiple_of",...Ie(r),value:t})}function wc(t,r){return new F1({check:"max_length",...Ie(r),maximum:t})}function Mo(t,r){return new U1({check:"min_length",...Ie(r),minimum:t})}function _c(t,r){return new z1({check:"length_equals",...Ie(r),length:t})}function Sf(t,r){return new V1({check:"string_format",format:"regex",...Ie(r),pattern:t})}function Tf(t){return new Z1({check:"string_format",format:"lowercase",...Ie(t)})}function Nf(t){return new $1({check:"string_format",format:"uppercase",...Ie(t)})}function Of(t,r){return new j1({check:"string_format",format:"includes",...Ie(r),includes:t})}function kf(t,r){return new H1({check:"string_format",format:"starts_with",...Ie(r),prefix:t})}function Rf(t,r){return new W1({check:"string_format",format:"ends_with",...Ie(r),suffix:t})}function so(t){return new G1({check:"overwrite",tx:t})}function Mf(t){return so(r=>r.normalize(t))}function Df(){return so(t=>t.trim())}function Pf(){return so(t=>t.toLowerCase())}function Bf(){return so(t=>t.toUpperCase())}function Lf(t,r,i){return new t({type:"array",element:r,...Ie(i)})}function Ff(t,r,i){return new t({type:"custom",check:"custom",fn:r,...Ie(i)})}class Zs{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??Gr,this.target=r?.target??"draft-2020-12",this.unrepresentable=r?.unrepresentable??"throw",this.override=r?.override??(()=>{}),this.io=r?.io??"output",this.seen=new Map}process(r,i={path:[],schemaPath:[]}){var c;const d=r._zod.def,f={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},m=this.seen.get(r);if(m)return m.count++,i.schemaPath.includes(r)&&(m.cycle=i.path),m.schema;const x={schema:{},count:1,cycle:void 0,path:i.path};this.seen.set(r,x);const v=r._zod.toJSONSchema?.();if(v)x.schema=v;else{const A={...i,schemaPath:[...i.schemaPath,r],path:i.path},D=r._zod.parent;if(D)x.ref=D,this.process(D,A),this.seen.get(D).isParent=!0;else{const T=x.schema;switch(d.type){case"string":{const S=T;S.type="string";const{minimum:P,maximum:M,format:ee,patterns:$,contentEncoding:F}=r._zod.bag;if(typeof P=="number"&&(S.minLength=P),typeof M=="number"&&(S.maxLength=M),ee&&(S.format=f[ee]??ee,S.format===""&&delete S.format),F&&(S.contentEncoding=F),$&&$.size>0){const re=[...$];re.length===1?S.pattern=re[0].source:re.length>1&&(x.schema.allOf=[...re.map(Z=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Z.source}))])}break}case"number":{const S=T,{minimum:P,maximum:M,format:ee,multipleOf:$,exclusiveMaximum:F,exclusiveMinimum:re}=r._zod.bag;typeof ee=="string"&&ee.includes("int")?S.type="integer":S.type="number",typeof re=="number"&&(S.exclusiveMinimum=re),typeof P=="number"&&(S.minimum=P,typeof re=="number"&&(re>=P?delete S.minimum:delete S.exclusiveMinimum)),typeof F=="number"&&(S.exclusiveMaximum=F),typeof M=="number"&&(S.maximum=M,typeof F=="number"&&(F<=M?delete S.maximum:delete S.exclusiveMaximum)),typeof $=="number"&&(S.multipleOf=$);break}case"boolean":{const S=T;S.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{T.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{T.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const S=T,{minimum:P,maximum:M}=r._zod.bag;typeof P=="number"&&(S.minItems=P),typeof M=="number"&&(S.maxItems=M),S.type="array",S.items=this.process(d.element,{...A,path:[...A.path,"items"]});break}case"object":{const S=T;S.type="object",S.properties={};const P=d.shape;for(const $ in P)S.properties[$]=this.process(P[$],{...A,path:[...A.path,"properties",$]});const M=new Set(Object.keys(P)),ee=new Set([...M].filter($=>{const F=d.shape[$]._zod;return this.io==="input"?F.optin===void 0:F.optout===void 0}));ee.size>0&&(S.required=Array.from(ee)),d.catchall?._zod.def.type==="never"?S.additionalProperties=!1:d.catchall?d.catchall&&(S.additionalProperties=this.process(d.catchall,{...A,path:[...A.path,"additionalProperties"]})):this.io==="output"&&(S.additionalProperties=!1);break}case"union":{const S=T;S.anyOf=d.options.map((P,M)=>this.process(P,{...A,path:[...A.path,"anyOf",M]}));break}case"intersection":{const S=T,P=this.process(d.left,{...A,path:[...A.path,"allOf",0]}),M=this.process(d.right,{...A,path:[...A.path,"allOf",1]}),ee=F=>"allOf"in F&&Object.keys(F).length===1,$=[...ee(P)?P.allOf:[P],...ee(M)?M.allOf:[M]];S.allOf=$;break}case"tuple":{const S=T;S.type="array";const P=d.items.map(($,F)=>this.process($,{...A,path:[...A.path,"prefixItems",F]}));if(this.target==="draft-2020-12"?S.prefixItems=P:S.items=P,d.rest){const $=this.process(d.rest,{...A,path:[...A.path,"items"]});this.target==="draft-2020-12"?S.items=$:S.additionalItems=$}d.rest&&(S.items=this.process(d.rest,{...A,path:[...A.path,"items"]}));const{minimum:M,maximum:ee}=r._zod.bag;typeof M=="number"&&(S.minItems=M),typeof ee=="number"&&(S.maxItems=ee);break}case"record":{const S=T;S.type="object",S.propertyNames=this.process(d.keyType,{...A,path:[...A.path,"propertyNames"]}),S.additionalProperties=this.process(d.valueType,{...A,path:[...A.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const S=T,P=nc(d.entries);P.every(M=>typeof M=="number")&&(S.type="number"),P.every(M=>typeof M=="string")&&(S.type="string"),S.enum=P;break}case"literal":{const S=T,P=[];for(const M of d.values)if(M===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof M=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");P.push(Number(M))}else P.push(M);if(P.length!==0)if(P.length===1){const M=P[0];S.type=M===null?"null":typeof M,S.const=M}else P.every(M=>typeof M=="number")&&(S.type="number"),P.every(M=>typeof M=="string")&&(S.type="string"),P.every(M=>typeof M=="boolean")&&(S.type="string"),P.every(M=>M===null)&&(S.type="null"),S.enum=P;break}case"file":{const S=T,P={type:"string",format:"binary",contentEncoding:"binary"},{minimum:M,maximum:ee,mime:$}=r._zod.bag;M!==void 0&&(P.minLength=M),ee!==void 0&&(P.maxLength=ee),$?$.length===1?(P.contentMediaType=$[0],Object.assign(S,P)):S.anyOf=$.map(F=>({...P,contentMediaType:F})):Object.assign(S,P);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const S=this.process(d.innerType,A);T.anyOf=[S,{type:"null"}];break}case"nonoptional":{this.process(d.innerType,A),x.ref=d.innerType;break}case"success":{const S=T;S.type="boolean";break}case"default":{this.process(d.innerType,A),x.ref=d.innerType,T.default=JSON.parse(JSON.stringify(d.defaultValue));break}case"prefault":{this.process(d.innerType,A),x.ref=d.innerType,this.io==="input"&&(T._prefault=JSON.parse(JSON.stringify(d.defaultValue)));break}case"catch":{this.process(d.innerType,A),x.ref=d.innerType;let S;try{S=d.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}T.default=S;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const S=T,P=r._zod.pattern;if(!P)throw new Error("Pattern not found in template literal");S.type="string",S.pattern=P.source;break}case"pipe":{const S=this.io==="input"?d.in._zod.def.type==="transform"?d.out:d.in:d.out;this.process(S,A),x.ref=S;break}case"readonly":{this.process(d.innerType,A),x.ref=d.innerType,T.readOnly=!0;break}case"promise":{this.process(d.innerType,A),x.ref=d.innerType;break}case"optional":{this.process(d.innerType,A),x.ref=d.innerType;break}case"lazy":{const S=r._zod.innerType;this.process(S,A),x.ref=S;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const g=this.metadataRegistry.get(r);return g&&Object.assign(x.schema,g),this.io==="input"&&Lt(r)&&(delete x.schema.examples,delete x.schema.default),this.io==="input"&&x.schema._prefault&&((c=x.schema).default??(c.default=x.schema._prefault)),delete x.schema._prefault,this.seen.get(r).schema}emit(r,i){const c={cycles:i?.cycles??"ref",reused:i?.reused??"inline",external:i?.external??void 0},d=this.seen.get(r);if(!d)throw new Error("Unprocessed schema. This is a bug in Zod.");const f=E=>{const A=this.target==="draft-2020-12"?"$defs":"definitions";if(c.external){const P=c.external.registry.get(E[0])?.id,M=c.external.uri??($=>$);if(P)return{ref:M(P)};const ee=E[1].defId??E[1].schema.id??`schema${this.counter++}`;return E[1].defId=ee,{defId:ee,ref:`${M("__shared")}#/${A}/${ee}`}}if(E[1]===d)return{ref:"#"};const T=`#/${A}/`,S=E[1].schema.id??`__schema${this.counter++}`;return{defId:S,ref:T+S}},m=E=>{if(E[1].schema.$ref)return;const A=E[1],{ref:D,defId:T}=f(E);A.def={...A.schema},T&&(A.defId=T);const S=A.schema;for(const P in S)delete S[P];S.$ref=D};if(c.cycles==="throw")for(const E of this.seen.entries()){const A=E[1];if(A.cycle)throw new Error(`Cycle detected: #/${A.cycle?.join("/")}/<root>
33
38
 
34
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const A of this.seen.entries()){const v=A[1];if(r===A[0]){m(A);continue}if(c.external){const O=c.external.registry.get(A[0])?.id;if(r!==A[0]&&O){m(A);continue}}if(this.metadataRegistry.get(A[0])?.id){m(A);continue}if(v.cycle){m(A);continue}if(v.count>1&&c.reused==="ref"){m(A);continue}}const g=(A,v)=>{const P=this.seen.get(A),O=P.def??P.schema,M={...O};if(P.ref===null)return;const D=P.ref;if(P.ref=null,D){g(D,v);const B=this.seen.get(D).schema;B.$ref&&v.target==="draft-7"?(O.allOf=O.allOf??[],O.allOf.push(B)):(Object.assign(O,B),Object.assign(O,M))}P.isParent||this.override({zodSchema:A,jsonSchema:O,path:P.path??[]})};for(const A of[...this.seen.entries()].reverse())g(A[0],{target:this.target});const C={};if(this.target==="draft-2020-12"?C.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?C.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const A=c.external.registry.get(r)?.id;if(!A)throw new Error("Schema is missing an `id` property");C.$id=c.external.uri(A)}Object.assign(C,u.def);const x=c.external?.defs??{};for(const A of this.seen.entries()){const v=A[1];v.def&&v.defId&&(x[v.defId]=v.def)}c.external||Object.keys(x).length>0&&(this.target==="draft-2020-12"?C.$defs=x:C.definitions=x);try{return JSON.parse(JSON.stringify(C))}catch{throw new Error("Error converting schema to JSON.")}}}function Af(t,r){if(t instanceof cc){const c=new Ps(r),u={};for(const g of t._idmap.entries()){const[C,x]=g;c.process(x)}const f={},m={registry:t,uri:r?.uri,defs:u};for(const g of t._idmap.entries()){const[C,x]=g;f[C]=c.emit(x,{...r,external:m})}if(Object.keys(u).length>0){const g=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[g]:u}}return{schemas:f}}const o=new Ps(r);return o.process(t),o.emit(t,r)}function Pt(t,r){const o=r??{seen:new Set};if(o.seen.has(t))return!1;o.seen.add(t);const u=t._zod.def;switch(u.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Pt(u.element,o);case"object":{for(const f in u.shape)if(Pt(u.shape[f],o))return!0;return!1}case"union":{for(const f of u.options)if(Pt(f,o))return!0;return!1}case"intersection":return Pt(u.left,o)||Pt(u.right,o);case"tuple":{for(const f of u.items)if(Pt(f,o))return!0;return!!(u.rest&&Pt(u.rest,o))}case"record":return Pt(u.keyType,o)||Pt(u.valueType,o);case"map":return Pt(u.keyType,o)||Pt(u.valueType,o);case"set":return Pt(u.valueType,o);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Pt(u.innerType,o);case"lazy":return Pt(u.getter(),o);case"default":return Pt(u.innerType,o);case"prefault":return Pt(u.innerType,o);case"custom":return!1;case"transform":return!0;case"pipe":return Pt(u.in,o)||Pt(u.out,o);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${u.type}`)}const If=te("ZodISODateTime",(t,r)=>{G1.init(t,r),_t.init(t,r)});function Sf(t){return ef(If,t)}const Tf=te("ZodISODate",(t,r)=>{X1.init(t,r),_t.init(t,r)});function Nf(t){return tf(Tf,t)}const Of=te("ZodISOTime",(t,r)=>{q1.init(t,r),_t.init(t,r)});function kf(t){return nf(Of,t)}const Rf=te("ZodISODuration",(t,r)=>{Y1.init(t,r),_t.init(t,r)});function Mf(t){return rf(Rf,t)}const Df=(t,r)=>{Yl.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:o=>$d(t,o)},flatten:{value:o=>Zd(t,o)},addIssue:{value:o=>t.issues.push(o)},addIssues:{value:o=>t.issues.push(...o)},isEmpty:{get(){return t.issues.length===0}}})},Di=te("ZodError",Df,{Parent:Error}),Pf=Hd(Di),Bf=Wd(Di),Lf=Jl(Di),fc=Ql(Di),pt=te("ZodType",(t,r)=>(at.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...o)=>t.clone({...r,checks:[...r.checks??[],...o.map(c=>typeof c=="function"?{_zod:{check:c,def:{check:"custom"},onattach:[]}}:c)]}),t.clone=(o,c)=>pr(t,o,c),t.brand=()=>t,t.register=((o,c)=>(o.add(t,c),t)),t.parse=(o,c)=>Pf(t,o,c,{callee:t.parse}),t.safeParse=(o,c)=>Lf(t,o,c),t.parseAsync=async(o,c)=>Bf(t,o,c,{callee:t.parseAsync}),t.safeParseAsync=async(o,c)=>fc(t,o,c),t.spa=t.safeParseAsync,t.refine=(o,c)=>t.check(Rh(o,c)),t.superRefine=o=>t.check(Mh(o)),t.overwrite=o=>t.check(ni(o)),t.optional=()=>Fs(t),t.nullable=()=>Us(t),t.nullish=()=>Fs(Us(t)),t.nonoptional=o=>bh(t,o),t.array=()=>ue(t),t.or=o=>Qe([t,o]),t.and=o=>hh(t,o),t.transform=o=>zs(t,xh(o)),t.default=o=>_h(t,o),t.prefault=o=>Ch(t,o),t.catch=o=>Ah(t,o),t.pipe=o=>zs(t,o),t.readonly=()=>Th(t),t.describe=o=>{const c=t.clone();return $r.add(c,{description:o}),c},Object.defineProperty(t,"description",{get(){return $r.get(t)?.description},configurable:!0}),t.meta=(...o)=>{if(o.length===0)return $r.get(t);const c=t.clone();return $r.add(c,o[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),hc=te("_ZodString",(t,r)=>{zo.init(t,r),pt.init(t,r);const o=t._zod.bag;t.format=o.format??null,t.minLength=o.minimum??null,t.maxLength=o.maximum??null,t.regex=(...c)=>t.check(hf(...c)),t.includes=(...c)=>t.check(gf(...c)),t.startsWith=(...c)=>t.check(xf(...c)),t.endsWith=(...c)=>t.check(yf(...c)),t.min=(...c)=>t.check(Ti(...c)),t.max=(...c)=>t.check(uc(...c)),t.length=(...c)=>t.check(dc(...c)),t.nonempty=(...c)=>t.check(Ti(1,...c)),t.lowercase=c=>t.check(pf(c)),t.uppercase=c=>t.check(mf(c)),t.trim=()=>t.check(_f()),t.normalize=(...c)=>t.check(wf(...c)),t.toLowerCase=()=>t.check(vf()),t.toUpperCase=()=>t.check(Cf())}),Ff=te("ZodString",(t,r)=>{zo.init(t,r),hc.init(t,r),t.email=o=>t.check(M0(Uf,o)),t.url=o=>t.check(F0(zf,o)),t.jwt=o=>t.check(Q0(th,o)),t.emoji=o=>t.check(U0(Vf,o)),t.guid=o=>t.check(ks(Bs,o)),t.uuid=o=>t.check(D0(xi,o)),t.uuidv4=o=>t.check(P0(xi,o)),t.uuidv6=o=>t.check(B0(xi,o)),t.uuidv7=o=>t.check(L0(xi,o)),t.nanoid=o=>t.check(z0(Zf,o)),t.guid=o=>t.check(ks(Bs,o)),t.cuid=o=>t.check(V0($f,o)),t.cuid2=o=>t.check(Z0(Hf,o)),t.ulid=o=>t.check($0(Wf,o)),t.base64=o=>t.check(Y0(Jf,o)),t.base64url=o=>t.check(K0(Qf,o)),t.xid=o=>t.check(H0(jf,o)),t.ksuid=o=>t.check(W0(Gf,o)),t.ipv4=o=>t.check(j0(Xf,o)),t.ipv6=o=>t.check(G0(qf,o)),t.cidrv4=o=>t.check(X0(Yf,o)),t.cidrv6=o=>t.check(q0(Kf,o)),t.e164=o=>t.check(J0(eh,o)),t.datetime=o=>t.check(Sf(o)),t.date=o=>t.check(Nf(o)),t.time=o=>t.check(kf(o)),t.duration=o=>t.check(Mf(o))});function w(t){return R0(Ff,t)}const _t=te("ZodStringFormat",(t,r)=>{xt.init(t,r),hc.init(t,r)}),Uf=te("ZodEmail",(t,r)=>{F1.init(t,r),_t.init(t,r)}),Bs=te("ZodGUID",(t,r)=>{B1.init(t,r),_t.init(t,r)}),xi=te("ZodUUID",(t,r)=>{L1.init(t,r),_t.init(t,r)}),zf=te("ZodURL",(t,r)=>{U1.init(t,r),_t.init(t,r)}),Vf=te("ZodEmoji",(t,r)=>{z1.init(t,r),_t.init(t,r)}),Zf=te("ZodNanoID",(t,r)=>{V1.init(t,r),_t.init(t,r)}),$f=te("ZodCUID",(t,r)=>{Z1.init(t,r),_t.init(t,r)}),Hf=te("ZodCUID2",(t,r)=>{$1.init(t,r),_t.init(t,r)}),Wf=te("ZodULID",(t,r)=>{H1.init(t,r),_t.init(t,r)}),jf=te("ZodXID",(t,r)=>{W1.init(t,r),_t.init(t,r)}),Gf=te("ZodKSUID",(t,r)=>{j1.init(t,r),_t.init(t,r)}),Xf=te("ZodIPv4",(t,r)=>{K1.init(t,r),_t.init(t,r)}),qf=te("ZodIPv6",(t,r)=>{J1.init(t,r),_t.init(t,r)}),Yf=te("ZodCIDRv4",(t,r)=>{Q1.init(t,r),_t.init(t,r)}),Kf=te("ZodCIDRv6",(t,r)=>{e0.init(t,r),_t.init(t,r)}),Jf=te("ZodBase64",(t,r)=>{t0.init(t,r),_t.init(t,r)}),Qf=te("ZodBase64URL",(t,r)=>{r0.init(t,r),_t.init(t,r)}),eh=te("ZodE164",(t,r)=>{i0.init(t,r),_t.init(t,r)}),th=te("ZodJWT",(t,r)=>{s0.init(t,r),_t.init(t,r)}),Vo=te("ZodNumber",(t,r)=>{ac.init(t,r),pt.init(t,r),t.gt=(c,u)=>t.check(Ms(c,u)),t.gte=(c,u)=>t.check(io(c,u)),t.min=(c,u)=>t.check(io(c,u)),t.lt=(c,u)=>t.check(Rs(c,u)),t.lte=(c,u)=>t.check(ro(c,u)),t.max=(c,u)=>t.check(ro(c,u)),t.int=c=>t.check(Ls(c)),t.safe=c=>t.check(Ls(c)),t.positive=c=>t.check(Ms(0,c)),t.nonnegative=c=>t.check(io(0,c)),t.negative=c=>t.check(Rs(0,c)),t.nonpositive=c=>t.check(ro(0,c)),t.multipleOf=(c,u)=>t.check(Ds(c,u)),t.step=(c,u)=>t.check(Ds(c,u)),t.finite=()=>t;const o=t._zod.bag;t.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),t.isFinite=!0,t.format=o.format??null});function j(t){return of(Vo,t)}const nh=te("ZodNumberFormat",(t,r)=>{a0.init(t,r),Vo.init(t,r)});function Ls(t){return af(nh,t)}const rh=te("ZodBoolean",(t,r)=>{l0.init(t,r),pt.init(t,r)});function Rt(t){return lf(rh,t)}const ih=te("ZodNull",(t,r)=>{c0.init(t,r),pt.init(t,r)});function pc(t){return cf(ih,t)}const oh=te("ZodAny",(t,r)=>{u0.init(t,r),pt.init(t,r)});function mr(){return uf(oh)}const sh=te("ZodUnknown",(t,r)=>{d0.init(t,r),pt.init(t,r)});function bn(){return df(sh)}const ah=te("ZodNever",(t,r)=>{f0.init(t,r),pt.init(t,r)});function lh(t){return ff(ah,t)}const ch=te("ZodArray",(t,r)=>{h0.init(t,r),pt.init(t,r),t.element=r.element,t.min=(o,c)=>t.check(Ti(o,c)),t.nonempty=o=>t.check(Ti(1,o)),t.max=(o,c)=>t.check(uc(o,c)),t.length=(o,c)=>t.check(dc(o,c)),t.unwrap=()=>t.element});function ue(t,r){return bf(ch,t,r)}const uh=te("ZodObject",(t,r)=>{p0.init(t,r),pt.init(t,r),tt(t,"shape",()=>r.shape),t.keyof=()=>Se(Object.keys(t._zod.def.shape)),t.catchall=o=>t.clone({...t._zod.def,catchall:o}),t.passthrough=()=>t.clone({...t._zod.def,catchall:bn()}),t.loose=()=>t.clone({...t._zod.def,catchall:bn()}),t.strict=()=>t.clone({...t._zod.def,catchall:lh()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=o=>Fd(t,o),t.merge=o=>Ud(t,o),t.pick=o=>Bd(t,o),t.omit=o=>Ld(t,o),t.partial=(...o)=>zd(gc,t,o[0]),t.required=(...o)=>Vd(xc,t,o[0])});function T(t,r){const o={type:"object",get shape(){return Fo(this,"shape",{...t}),this.shape},...Ae(r)};return new uh(o)}const mc=te("ZodUnion",(t,r)=>{lc.init(t,r),pt.init(t,r),t.options=r.options});function Qe(t,r){return new mc({type:"union",options:t,...Ae(r)})}const dh=te("ZodDiscriminatedUnion",(t,r)=>{mc.init(t,r),m0.init(t,r)});function ut(t,r,o){return new dh({type:"union",options:r,discriminator:t,...Ae(o)})}const fh=te("ZodIntersection",(t,r)=>{g0.init(t,r),pt.init(t,r)});function hh(t,r){return new fh({type:"intersection",left:t,right:r})}const ph=te("ZodRecord",(t,r)=>{x0.init(t,r),pt.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function ht(t,r,o){return new ph({type:"record",keyType:t,valueType:r,...Ae(o)})}const wo=te("ZodEnum",(t,r)=>{y0.init(t,r),pt.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);const o=new Set(Object.keys(r.entries));t.extract=(c,u)=>{const f={};for(const m of c)if(o.has(m))f[m]=r.entries[m];else throw new Error(`Key ${m} not found in enum`);return new wo({...r,checks:[],...Ae(u),entries:f})},t.exclude=(c,u)=>{const f={...r.entries};for(const m of c)if(o.has(m))delete f[m];else throw new Error(`Key ${m} not found in enum`);return new wo({...r,checks:[],...Ae(u),entries:f})}});function Se(t,r){const o=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new wo({type:"enum",entries:o,...Ae(r)})}const mh=te("ZodLiteral",(t,r)=>{w0.init(t,r),pt.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function X(t,r){return new mh({type:"literal",values:Array.isArray(t)?t:[t],...Ae(r)})}const gh=te("ZodTransform",(t,r)=>{_0.init(t,r),pt.init(t,r),t._zod.parse=(o,c)=>{o.addIssue=f=>{if(typeof f=="string")o.issues.push(Yr(f,o.value,r));else{const m=f;m.fatal&&(m.continue=!1),m.code??(m.code="custom"),m.input??(m.input=o.value),m.inst??(m.inst=t),m.continue??(m.continue=!0),o.issues.push(Yr(m))}};const u=r.transform(o.value,o);return u instanceof Promise?u.then(f=>(o.value=f,o)):(o.value=u,o)}});function xh(t){return new gh({type:"transform",transform:t})}const gc=te("ZodOptional",(t,r)=>{v0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Fs(t){return new gc({type:"optional",innerType:t})}const yh=te("ZodNullable",(t,r)=>{C0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Us(t){return new yh({type:"nullable",innerType:t})}const wh=te("ZodDefault",(t,r)=>{b0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function _h(t,r){return new wh({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const vh=te("ZodPrefault",(t,r)=>{E0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Ch(t,r){return new vh({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const xc=te("ZodNonOptional",(t,r)=>{A0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function bh(t,r){return new xc({type:"nonoptional",innerType:t,...Ae(r)})}const Eh=te("ZodCatch",(t,r)=>{I0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Ah(t,r){return new Eh({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const Ih=te("ZodPipe",(t,r)=>{S0.init(t,r),pt.init(t,r),t.in=r.in,t.out=r.out});function zs(t,r){return new Ih({type:"pipe",in:t,out:r})}const Sh=te("ZodReadonly",(t,r)=>{T0.init(t,r),pt.init(t,r)});function Th(t){return new Sh({type:"readonly",innerType:t})}const Nh=te("ZodLazy",(t,r)=>{N0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.getter()});function Zo(t){return new Nh({type:"lazy",getter:t})}const Oh=te("ZodCustom",(t,r)=>{O0.init(t,r),pt.init(t,r)});function kh(t){const r=new on({check:"custom"});return r._zod.check=t,r}function Rh(t,r={}){return Ef(Oh,t,r)}function Mh(t){const r=kh(o=>(o.addIssue=c=>{if(typeof c=="string")o.issues.push(Yr(c,o.value,r._zod.def));else{const u=c;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=o.value),u.inst??(u.inst=r),u.continue??(u.continue=!r._zod.def.abort),o.issues.push(Yr(u))}},t(o.value,o)));return r}function Dh(t){return sf(Vo,t)}var Le;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Le||(Le={}));function Vs(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Pi(t){return Object.fromEntries([...t.headers])}var Ph=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,m=new Array(r);for(let g=0;g<r;g++)m[g]=o[Math.random()*f|0];return m.join("")};if(t==null)return u;if(o.includes(c))throw new Al({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},yi=Ph();function _o(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Bh=["fetch failed","failed to fetch"];function Lh({error:t,url:r,requestBodyValues:o}){if(_o(t))return t;if(t instanceof TypeError&&Bh.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Un({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return t}function Fh(t=globalThis){var r,o,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(o=t.process)==null?void 0:o.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Uh(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((o,c)=>{r[c.toLowerCase()]=o});else{Array.isArray(t)||(t=Object.entries(t));for(const[o,c]of t)c!=null&&(r[o.toLowerCase()]=c)}return r}function yc(t,...r){const o=new Headers(Uh(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var zh="3.0.18";function Vh({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new pi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new pi({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new pi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new pi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var Zh=/"__proto__"\s*:/,$h=/"constructor"\s*:/;function Zs(t){const r=JSON.parse(t);return r===null||typeof r!="object"||Zh.test(t)===!1&&$h.test(t)===!1?r:Hh(r)}function Hh(t){let r=[t];for(;r.length;){const o=r;r=[];for(const c of o){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const u in c){const f=c[u];f&&typeof f=="object"&&r.push(f)}}}return t}function $o(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Zs(t)}try{return Zs(t)}finally{Error.stackTraceLimit=r}}var vo=Symbol.for("vercel.ai.validator");function Wh(t){return{[vo]:!0,validate:t}}function jh(t){return typeof t=="object"&&t!==null&&vo in t&&t[vo]===!0&&"validate"in t}function Gh(t){return jh(t)?t:typeof t=="function"?t():Xh(t)}function Xh(t){return Wh(async r=>{const o=await t["~standard"].validate(r);return o.issues==null?{success:!0,value:o.value}:{success:!1,error:new Xr({value:r,cause:o.issues})}})}async function qh({value:t,schema:r}){const o=await Kr({value:t,schema:r});if(!o.success)throw Xr.wrap({value:t,cause:o.error});return o.value}async function Kr({value:t,schema:r}){const o=Gh(r);try{if(o.validate==null)return{success:!0,value:t,rawValue:t};const c=await o.validate(t);return c.success?{success:!0,value:c.value,rawValue:t}:{success:!1,error:Xr.wrap({value:t,cause:c.error}),rawValue:t}}catch(c){return{success:!1,error:Xr.wrap({value:t,cause:c}),rawValue:t}}}async function Yh({text:t,schema:r}){try{const o=$o(t);return r==null?o:qh({value:o,schema:r})}catch(o){throw Ai.isInstance(o)||Xr.isInstance(o)?o:new Ai({text:t,cause:o})}}async function wc({text:t,schema:r}){try{const o=$o(t);return r==null?{success:!0,value:o,rawValue:o}:await Kr({value:o,schema:r})}catch(o){return{success:!1,error:Ai.isInstance(o)?o:new Ai({text:t,cause:o}),rawValue:void 0}}}function $s(t){try{return $o(t),!0}catch{return!1}}function Kh({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Wl).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await wc({text:o,schema:r}))}}))}async function Hs({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Kr({value:r[t],schema:o});if(!c.success)throw new Al({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var Jh=()=>globalThis.fetch,Ws=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>Qh({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),Qh=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=Jh()})=>{try{const g=await m(t,{method:"POST",headers:yc(r,`ai-sdk/provider-utils/${zh}`,Fh()),body:o.content,signal:f}),C=Pi(g);if(!g.ok){let x;try{x=await u({response:g,url:t,requestBodyValues:o.values})}catch(A){throw _o(A)||Un.isInstance(A)?A:new Un({message:"Failed to process error response",cause:A,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}throw x.value}try{return await c({response:g,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(_o(x)||Un.isInstance(x))?x:new Un({message:"Failed to process successful response",cause:x,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}}catch(g){throw Lh({error:g,url:t,requestBodyValues:o.values})}},ep=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const m=await c.text(),g=Pi(c);if(m.trim()==="")return{responseHeaders:g,value:new Un({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})};try{const C=await Yh({text:m,schema:t});return{responseHeaders:g,value:new Un({message:r(C),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,data:C,isRetryable:o?.(c,C)})}}catch{return{responseHeaders:g,value:new Un({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})}}},tp=t=>async({response:r})=>{const o=Pi(r);if(r.body==null)throw new wd({});return{responseHeaders:o,value:Kh({stream:r.body,schema:t})}},np=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await wc({text:u,schema:t}),m=Pi(r);if(!f.success)throw new Un({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:rp}=globalThis;function ip(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return rp(r)}function op(t){return t instanceof Uint8Array?ip(t):t}function sp(t){return t?.replace(/\/$/,"")}function zr(t){var r,o;return(o=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?o:{}}function ap(t){const r=[];for(const{role:o,content:c,...u}of t){const f=zr({...u});switch(o){case"system":{r.push({role:"system",content:c,...f});break}case"user":{if(c.length===1&&c[0].type==="text"){r.push({role:"user",content:c[0].text,...zr(c[0])});break}r.push({role:"user",content:c.map(m=>{const g=zr(m);switch(m.type){case"text":return{type:"text",text:m.text,...g};case"file":if(m.mediaType.startsWith("image/")){const C=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${C};base64,${op(m.data)}`},...g}}else throw new Hl({functionality:`file part media type ${m.mediaType}`})}}),...f});break}case"assistant":{let m="";const g=[];for(const C of c){const x=zr(C);switch(C.type){case"text":{m+=C.text;break}case"tool-call":{g.push({id:C.toolCallId,type:"function",function:{name:C.toolName,arguments:JSON.stringify(C.input)},...x});break}}}r.push({role:"assistant",content:m,tool_calls:g.length>0?g:void 0,...f});break}case"tool":{for(const m of c){const g=m.output;let C;switch(g.type){case"text":case"error-text":C=g.value;break;case"content":case"json":case"error-json":C=JSON.stringify(g.value);break}const x=zr(m);r.push({role:"tool",tool_call_id:m.toolCallId,content:C,...x})}break}default:{const m=o;throw new Error(`Unsupported role: ${m}`)}}}return r}function js({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o!=null?new Date(o*1e3):void 0}}function Gs(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var oo=T({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),lp=T({error:T({message:w(),type:w().nullish(),param:mr().nullish(),code:Qe([w(),j()]).nullish()})}),cp={errorSchema:lp,errorToMessage:t=>t.error.message};function up({tools:t,toolChoice:r}){t=t?.length?t:void 0;const o=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const c=[];for(const f of t)f.type==="provider-defined"?o.push({type:"unsupported-tool",tool:f}):c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema}});if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:o};const u=r.type;switch(u){case"auto":case"none":case"required":return{tools:c,toolChoice:u,toolWarnings:o};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:o};default:{const f=u;throw new Hl({functionality:`tool choice type: ${f}`})}}}var dp=class{constructor(t,r){this.specificationVersion="v2";var o,c;this.modelId=t,this.config=r;const u=(o=r.errorStructure)!=null?o:cp;this.chunkSchema=hp(u.errorSchema),this.failedResponseHandler=ep(u),this.supportsStructuredOutputs=(c=r.supportsStructuredOutputs)!=null?c:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,r,o;return(o=(r=(t=this.config).supportedUrls)==null?void 0:r.call(t))!=null?o:{}}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:m,providerOptions:g,stopSequences:C,responseFormat:x,seed:A,toolChoice:v,tools:P}){var O,M,D,B;const G=[],Z=Object.assign((O=await Hs({provider:"openai-compatible",providerOptions:g,schema:oo}))!=null?O:{},(M=await Hs({provider:this.providerOptionsName,providerOptions:g,schema:oo}))!=null?M:{});u!=null&&G.push({type:"unsupported-setting",setting:"topK"}),x?.type==="json"&&x.schema!=null&&!this.supportsStructuredOutputs&&G.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:z,toolChoice:ee,toolWarnings:K}=up({tools:P,toolChoice:v});return{args:{model:this.modelId,user:Z.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:x?.type==="json"?this.supportsStructuredOutputs===!0&&x.schema!=null?{type:"json_schema",json_schema:{schema:x.schema,name:(D=x.name)!=null?D:"response",description:x.description}}:{type:"json_object"}:void 0,stop:C,seed:A,...Object.fromEntries(Object.entries((B=g?.[this.providerOptionsName])!=null?B:{}).filter(([V])=>!Object.keys(oo.shape).includes(V))),reasoning_effort:Z.reasoningEffort,verbosity:Z.textVerbosity,messages:ap(t),tools:z,tool_choice:ee},warnings:[...G,...K]}}async doGenerate(t){var r,o,c,u,f,m,g,C,x,A,v,P,O,M,D,B,G;const{args:Z,warnings:z}=await this.getArgs({...t}),ee=JSON.stringify(Z),{responseHeaders:K,value:V,rawValue:U}=await Ws({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Vs(this.config.headers(),t.headers),body:Z,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:np(fp),abortSignal:t.abortSignal,fetch:this.config.fetch}),J=V.choices[0],S=[],Te=J.message.content;Te!=null&&Te.length>0&&S.push({type:"text",text:Te});const ye=(r=J.message.reasoning_content)!=null?r:J.message.reasoning;if(ye!=null&&ye.length>0&&S.push({type:"reasoning",text:ye}),J.message.tool_calls!=null)for(const Me of J.message.tool_calls)S.push({type:"tool-call",toolCallId:(o=Me.id)!=null?o:yi(),toolName:Me.function.name,input:Me.function.arguments});const re={[this.providerOptionsName]:{},...await((u=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:u.call(c,{parsedBody:U}))},xe=(f=V.usage)==null?void 0:f.completion_tokens_details;return xe?.accepted_prediction_tokens!=null&&(re[this.providerOptionsName].acceptedPredictionTokens=xe?.accepted_prediction_tokens),xe?.rejected_prediction_tokens!=null&&(re[this.providerOptionsName].rejectedPredictionTokens=xe?.rejected_prediction_tokens),{content:S,finishReason:Gs(J.finish_reason),usage:{inputTokens:(g=(m=V.usage)==null?void 0:m.prompt_tokens)!=null?g:void 0,outputTokens:(x=(C=V.usage)==null?void 0:C.completion_tokens)!=null?x:void 0,totalTokens:(v=(A=V.usage)==null?void 0:A.total_tokens)!=null?v:void 0,reasoningTokens:(M=(O=(P=V.usage)==null?void 0:P.completion_tokens_details)==null?void 0:O.reasoning_tokens)!=null?M:void 0,cachedInputTokens:(G=(B=(D=V.usage)==null?void 0:D.prompt_tokens_details)==null?void 0:B.cached_tokens)!=null?G:void 0},providerMetadata:re,request:{body:ee},response:{...js(V),headers:K,body:U},warnings:z}}async doStream(t){var r;const{args:o,warnings:c}=await this.getArgs({...t}),u={...o,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},f=(r=this.config.metadataExtractor)==null?void 0:r.createStreamExtractor(),{responseHeaders:m,value:g}=await Ws({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Vs(this.config.headers(),t.headers),body:u,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:tp(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),C=[];let x="unknown";const A={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let v=!0;const P=this.providerOptionsName;let O=!1,M=!1;return{stream:g.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:c})},transform(D,B){var G,Z,z,ee,K,V,U,J,S,Te,ye,re,xe;if(t.includeRawChunks&&B.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){x="error",B.enqueue({type:"error",error:D.error});return}const Me=D.value;if(f?.processChunk(D.rawValue),"error"in Me){x="error",B.enqueue({type:"error",error:Me.error.message});return}if(v&&(v=!1,B.enqueue({type:"response-metadata",...js(Me)})),Me.usage!=null){const{prompt_tokens:Q,completion_tokens:me,total_tokens:fe,prompt_tokens_details:ie,completion_tokens_details:pe}=Me.usage;A.promptTokens=Q??void 0,A.completionTokens=me??void 0,A.totalTokens=fe??void 0,pe?.reasoning_tokens!=null&&(A.completionTokensDetails.reasoningTokens=pe?.reasoning_tokens),pe?.accepted_prediction_tokens!=null&&(A.completionTokensDetails.acceptedPredictionTokens=pe?.accepted_prediction_tokens),pe?.rejected_prediction_tokens!=null&&(A.completionTokensDetails.rejectedPredictionTokens=pe?.rejected_prediction_tokens),ie?.cached_tokens!=null&&(A.promptTokensDetails.cachedTokens=ie?.cached_tokens)}const $=Me.choices[0];if($?.finish_reason!=null&&(x=Gs($.finish_reason)),$?.delta==null)return;const ge=$.delta,ne=(G=ge.reasoning_content)!=null?G:ge.reasoning;if(ne&&(O||(B.enqueue({type:"reasoning-start",id:"reasoning-0"}),O=!0),B.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ne})),ge.content&&(M||(B.enqueue({type:"text-start",id:"txt-0"}),M=!0),B.enqueue({type:"text-delta",id:"txt-0",delta:ge.content})),ge.tool_calls!=null)for(const Q of ge.tool_calls){const me=Q.index;if(C[me]==null){if(Q.id==null)throw new ys({data:Q,message:"Expected 'id' to be a string."});if(((Z=Q.function)==null?void 0:Z.name)==null)throw new ys({data:Q,message:"Expected 'function.name' to be a string."});B.enqueue({type:"tool-input-start",id:Q.id,toolName:Q.function.name}),C[me]={id:Q.id,type:"function",function:{name:Q.function.name,arguments:(z=Q.function.arguments)!=null?z:""},hasFinished:!1};const ie=C[me];((ee=ie.function)==null?void 0:ee.name)!=null&&((K=ie.function)==null?void 0:K.arguments)!=null&&(ie.function.arguments.length>0&&B.enqueue({type:"tool-input-delta",id:ie.id,delta:ie.function.arguments}),$s(ie.function.arguments)&&(B.enqueue({type:"tool-input-end",id:ie.id}),B.enqueue({type:"tool-call",toolCallId:(V=ie.id)!=null?V:yi(),toolName:ie.function.name,input:ie.function.arguments}),ie.hasFinished=!0));continue}const fe=C[me];fe.hasFinished||(((U=Q.function)==null?void 0:U.arguments)!=null&&(fe.function.arguments+=(S=(J=Q.function)==null?void 0:J.arguments)!=null?S:""),B.enqueue({type:"tool-input-delta",id:fe.id,delta:(Te=Q.function.arguments)!=null?Te:""}),((ye=fe.function)==null?void 0:ye.name)!=null&&((re=fe.function)==null?void 0:re.arguments)!=null&&$s(fe.function.arguments)&&(B.enqueue({type:"tool-input-end",id:fe.id}),B.enqueue({type:"tool-call",toolCallId:(xe=fe.id)!=null?xe:yi(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}},flush(D){var B,G,Z,z,ee,K;O&&D.enqueue({type:"reasoning-end",id:"reasoning-0"}),M&&D.enqueue({type:"text-end",id:"txt-0"});for(const U of C.filter(J=>!J.hasFinished))D.enqueue({type:"tool-input-end",id:U.id}),D.enqueue({type:"tool-call",toolCallId:(B=U.id)!=null?B:yi(),toolName:U.function.name,input:U.function.arguments});const V={[P]:{},...f?.buildMetadata()};A.completionTokensDetails.acceptedPredictionTokens!=null&&(V[P].acceptedPredictionTokens=A.completionTokensDetails.acceptedPredictionTokens),A.completionTokensDetails.rejectedPredictionTokens!=null&&(V[P].rejectedPredictionTokens=A.completionTokensDetails.rejectedPredictionTokens),D.enqueue({type:"finish",finishReason:x,usage:{inputTokens:(G=A.promptTokens)!=null?G:void 0,outputTokens:(Z=A.completionTokens)!=null?Z:void 0,totalTokens:(z=A.totalTokens)!=null?z:void 0,reasoningTokens:(ee=A.completionTokensDetails.reasoningTokens)!=null?ee:void 0,cachedInputTokens:(K=A.promptTokensDetails.cachedTokens)!=null?K:void 0},providerMetadata:V})}})),request:{body:u},response:{headers:m}}}},_c=T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),fp=T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({message:T({role:X("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(T({id:w().nullish(),function:T({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:_c}),hp=t=>Qe([T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({delta:T({role:Se(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(T({index:j(),id:w().nullish(),function:T({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:_c}),t]);T({echo:Rt().optional(),logitBias:ht(w(),j()).optional(),suffix:w().optional(),user:w().optional()});var pp=T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({text:w(),finish_reason:w()})),usage:pp.nullish()});T({dimensions:j().optional(),user:w().optional()});T({data:ue(T({embedding:ue(j())})),usage:T({prompt_tokens:j()}).nullish(),providerMetadata:ht(w(),ht(w(),mr())).optional()});T({data:ue(T({b64_json:w()}))});var Xs=t=>{var r,o;return t==null?void 0:{deepseek:{promptCacheHitTokens:(r=t.prompt_cache_hit_tokens)!=null?r:NaN,promptCacheMissTokens:(o=t.prompt_cache_miss_tokens)!=null?o:NaN}}},mp={extractMetadata:async({parsedBody:t})=>{const r=await Kr({value:t,schema:gp});return!r.success||r.value.usage==null?void 0:Xs(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var o,c;const u=await Kr({value:r,schema:xp});u.success&&((c=(o=u.value.choices)==null?void 0:o[0])==null?void 0:c.finish_reason)==="stop"&&u.value.usage&&(t=u.value.usage)},buildMetadata:()=>Xs(t)}}},vc=T({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),gp=T({usage:vc.nullish()}),xp=T({choices:ue(T({finish_reason:w().nullish()})).nullish(),usage:vc.nullish()}),yp="1.0.30";function Cc(t={}){var r;const o=sp((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>yc({Authorization:`Bearer ${Vh({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${yp}`);class u extends dp{addJsonInstruction(C){var x;if(((x=C.responseFormat)==null?void 0:x.type)!=="json")return C;const P=[...Array.isArray(C.prompt)?C.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...C,prompt:P}}async doGenerate(C){return super.doGenerate(this.addJsonInstruction(C))}async doStream(C){return super.doStream(this.addJsonInstruction(C))}}const f=g=>new u(g,{provider:"deepseek.chat",url:({path:C})=>`${o}${C}`,headers:c,fetch:t.fetch,metadataExtractor:mp}),m=g=>f(g);return m.languageModel=f,m.chat=f,m.textEmbeddingModel=g=>{throw new ws({modelId:g,modelType:"textEmbeddingModel"})},m.imageModel=g=>{throw new ws({modelId:g,modelType:"imageModel"})},m}Cc();var bc="vercel.ai.error",wp=Symbol.for(bc),qs,Ys,St=class Ec extends(Ys=Error,qs=wp,Ys){constructor({name:r,message:o,cause:c}){super(o),this[qs]=!0,this.name=r,this.cause=c}static isInstance(r){return Ec.hasMarker(r,bc)}static hasMarker(r,o){const c=Symbol.for(o);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}},Ac="AI_APICallError",Ic=`vercel.ai.error.${Ac}`,_p=Symbol.for(Ic),Ks,Js,cn=class extends(Js=St,Ks=_p,Js){constructor({message:t,url:r,requestBodyValues:o,statusCode:c,responseHeaders:u,responseBody:f,cause:m,isRetryable:g=c!=null&&(c===408||c===409||c===429||c>=500),data:C}){super({name:Ac,message:t,cause:m}),this[Ks]=!0,this.url=r,this.requestBodyValues=o,this.statusCode=c,this.responseHeaders=u,this.responseBody=f,this.isRetryable=g,this.data=C}static isInstance(t){return St.hasMarker(t,Ic)}},Sc="AI_EmptyResponseBodyError",Tc=`vercel.ai.error.${Sc}`,vp=Symbol.for(Tc),Qs,ea,Cp=class extends(ea=St,Qs=vp,ea){constructor({message:t="Empty response body"}={}){super({name:Sc,message:t}),this[Qs]=!0}static isInstance(t){return St.hasMarker(t,Tc)}};function Nc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Oc="AI_InvalidArgumentError",kc=`vercel.ai.error.${Oc}`,bp=Symbol.for(kc),ta,na,Rc=class extends(na=St,ta=bp,na){constructor({message:t,cause:r,argument:o}){super({name:Oc,message:t,cause:r}),this[ta]=!0,this.argument=o}static isInstance(t){return St.hasMarker(t,kc)}},Mc="AI_InvalidPromptError",Dc=`vercel.ai.error.${Mc}`,Ep=Symbol.for(Dc),ra,ia,Ap=class extends(ia=St,ra=Ep,ia){constructor({prompt:t,message:r,cause:o}){super({name:Mc,message:`Invalid prompt: ${r}`,cause:o}),this[ra]=!0,this.prompt=t}static isInstance(t){return St.hasMarker(t,Dc)}},Pc="AI_InvalidResponseDataError",Bc=`vercel.ai.error.${Pc}`,Ip=Symbol.for(Bc),oa,sa,so=class extends(sa=St,oa=Ip,sa){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Pc,message:r}),this[oa]=!0,this.data=t}static isInstance(t){return St.hasMarker(t,Bc)}},Lc="AI_JSONParseError",Fc=`vercel.ai.error.${Lc}`,Sp=Symbol.for(Fc),aa,la,Ni=class extends(la=St,aa=Sp,la){constructor({text:t,cause:r}){super({name:Lc,message:`JSON parsing failed: Text: ${t}.
35
- Error message: ${Nc(r)}`,cause:r}),this[aa]=!0,this.text=t}static isInstance(t){return St.hasMarker(t,Fc)}},Uc="AI_LoadAPIKeyError",zc=`vercel.ai.error.${Uc}`,Tp=Symbol.for(zc),ca,ua,wi=class extends(ua=St,ca=Tp,ua){constructor({message:t}){super({name:Uc,message:t}),this[ca]=!0}static isInstance(t){return St.hasMarker(t,zc)}},Vc="AI_TooManyEmbeddingValuesForCallError",Zc=`vercel.ai.error.${Vc}`,Np=Symbol.for(Zc),da,fa,Op=class extends(fa=St,da=Np,fa){constructor(t){super({name:Vc,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[da]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return St.hasMarker(t,Zc)}},$c="AI_TypeValidationError",Hc=`vercel.ai.error.${$c}`,kp=Symbol.for(Hc),ha,pa,Jr=class Co extends(pa=St,ha=kp,pa){constructor({value:r,cause:o,context:c}){let u="Type validation failed";if(c?.field&&(u+=` for ${c.field}`),c?.entityName||c?.entityId){u+=" (";const f=[];c.entityName&&f.push(c.entityName),c.entityId&&f.push(`id: "${c.entityId}"`),u+=f.join(", "),u+=")"}super({name:$c,message:`${u}: Value: ${JSON.stringify(r)}.
36
- Error message: ${Nc(o)}`,cause:o}),this[ha]=!0,this.value=r,this.context=c}static isInstance(r){return St.hasMarker(r,Hc)}static wrap({value:r,cause:o,context:c}){var u,f,m;return Co.isInstance(o)&&o.value===r&&((u=o.context)==null?void 0:u.field)===c?.field&&((f=o.context)==null?void 0:f.entityName)===c?.entityName&&((m=o.context)==null?void 0:m.entityId)===c?.entityId?o:new Co({value:r,cause:o,context:c})}},Wc="AI_UnsupportedFunctionalityError",jc=`vercel.ai.error.${Wc}`,Rp=Symbol.for(jc),ma,ga,zn=class extends(ga=St,ma=Rp,ga){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:Wc,message:r}),this[ma]=!0,this.functionality=t}static isInstance(t){return St.hasMarker(t,jc)}};function En(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Mp({tools:t=[],providerToolNames:r,resolveProviderToolName:o}){var c;const u={},f={};for(const m of t)if(m.type==="provider"){const g=(c=o?.(m))!=null?c:m.id in r?r[m.id]:void 0;if(g==null)continue;u[m.name]=g,f[g]=m.name}return{toProviderToolName:m=>{var g;return(g=u[m])!=null?g:m},toCustomToolName:m=>{var g;return(g=f[m])!=null?g:m}}}var Dp=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,r)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&r(this.status.error),this._resolve=t,this._reject=r}),this._promise)}resolve(t){var r;this.status={type:"resolved",value:t},this._promise&&((r=this._resolve)==null||r.call(this,t))}reject(t){var r;this.status={type:"rejected",error:t},this._promise&&((r=this._reject)==null||r.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function ri(t){return Object.fromEntries([...t.headers])}var{btoa:Pp,atob:Bp}=globalThis;function Ho(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),o=Bp(r);return Uint8Array.from(o,c=>c.codePointAt(0))}function Lp(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return Pp(r)}function Tr(t){return t instanceof Uint8Array?Lp(t):t}function Fp(t,r={}){const{useArrayBrackets:o=!0}=r,c=new FormData;for(const[u,f]of Object.entries(t))if(f!=null){if(Array.isArray(f)){if(f.length===1){c.append(u,f[0]);continue}const m=o?`${u}[]`:u;for(const g of f)c.append(m,g);continue}c.append(u,f)}return c}var Gc="AI_DownloadError",Xc=`vercel.ai.error.${Gc}`,Up=Symbol.for(Xc),xa,ya,vn=class extends(ya=St,xa=Up,ya){constructor({url:t,statusCode:r,statusText:o,cause:c,message:u=c==null?`Failed to download ${t}: ${r} ${o}`:`Failed to download ${t}: ${c}`}){super({name:Gc,message:u,cause:c}),this[xa]=!0,this.url=t,this.statusCode=r,this.statusText=o}static isInstance(t){return St.hasMarker(t,Xc)}},qc=2*1024*1024*1024;async function zp({response:t,url:r,maxBytes:o=qc}){const c=t.headers.get("content-length");if(c!=null){const A=parseInt(c,10);if(!isNaN(A)&&A>o)throw new vn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes (Content-Length: ${A}).`})}const u=t.body;if(u==null)return new Uint8Array(0);const f=u.getReader(),m=[];let g=0;try{for(;;){const{done:A,value:v}=await f.read();if(A)break;if(g+=v.length,g>o)throw new vn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes.`});m.push(v)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const C=new Uint8Array(g);let x=0;for(const A of m)C.set(A,x),x+=A.length;return C}function wa(t){let r;try{r=new URL(t)}catch{throw new vn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol==="data:")return;if(r.protocol!=="http:"&&r.protocol!=="https:")throw new vn({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});const o=r.hostname;if(!o)throw new vn({url:t,message:"URL must have a hostname"});if(o==="localhost"||o.endsWith(".local")||o.endsWith(".localhost"))throw new vn({url:t,message:`URL with hostname ${o} is not allowed`});if(o.startsWith("[")&&o.endsWith("]")){const c=o.slice(1,-1);if(Vp(c))throw new vn({url:t,message:`URL with IPv6 address ${o} is not allowed`});return}if(Yc(o)){if(bo(o))throw new vn({url:t,message:`URL with IP address ${o} is not allowed`});return}}function Yc(t){const r=t.split(".");return r.length!==4?!1:r.every(o=>{const c=Number(o);return Number.isInteger(c)&&c>=0&&c<=255&&String(c)===o})}function bo(t){const r=t.split(".").map(Number),[o,c]=r;return o===0||o===10||o===127||o===169&&c===254||o===172&&c>=16&&c<=31||o===192&&c===168}function Vp(t){const r=t.toLowerCase();if(r==="::1"||r==="::")return!0;if(r.startsWith("::ffff:")){const o=r.slice(7);if(Yc(o))return bo(o);const c=o.split(":");if(c.length===2){const u=parseInt(c[0],16),f=parseInt(c[1],16);if(!isNaN(u)&&!isNaN(f)){const m=u>>8&255,g=u&255,C=f>>8&255,x=f&255;return bo(`${m}.${g}.${C}.${x}`)}}}return!!(r.startsWith("fc")||r.startsWith("fd")||r.startsWith("fe80"))}async function Kc(t,r){var o,c;wa(t);try{const u=await fetch(t,{signal:r?.abortSignal});if(u.redirected&&wa(u.url),!u.ok)throw new vn({url:t,statusCode:u.status,statusText:u.statusText});const f=await zp({response:u,url:t,maxBytes:(o=r?.maxBytes)!=null?o:qc}),m=(c=u.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(u){throw vn.isInstance(u)?u:new vn({url:t,cause:u})}}var Zp=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,m=new Array(r);for(let g=0;g<r;g++)m[g]=o[Math.random()*f|0];return m.join("")};if(t==null)return u;if(o.includes(c))throw new Rc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},Kt=Zp();function Eo(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var $p=["fetch failed","failed to fetch"],Hp=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function Wp(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&Hp.includes(r))}function jp({error:t,url:r,requestBodyValues:o}){if(Eo(t))return t;if(t instanceof TypeError&&$p.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new cn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return Wp(t)?new cn({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:o,isRetryable:!0}):t}function Gp(t=globalThis){var r,o,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(o=t.process)==null?void 0:o.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Xp(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((o,c)=>{r[c.toLowerCase()]=o});else{Array.isArray(t)||(t=Object.entries(t));for(const[o,c]of t)c!=null&&(r[o.toLowerCase()]=c)}return r}function Jc(t,...r){const o=new Headers(Xp(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var qp="4.0.23";function _a(t){return t!=null}function Yp({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new wi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new wi({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables are not supported in this environment.`});if(t=process.env[r],t==null)throw new wi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new wi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function Kp({settingValue:t,environmentVariableName:r}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[r],!(t==null||typeof t!="string")))return t}function Jp(t){var r;const[o,c=""]=t.toLowerCase().split("/");return(r={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[c])!=null?r:c}var Qp=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,em=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function va(t){const r=JSON.parse(t);return r===null||typeof r!="object"||Qp.test(t)===!1&&em.test(t)===!1?r:tm(r)}function tm(t){let r=[t];for(;r.length;){const o=r;r=[];for(const c of o){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&c.constructor!==null&&typeof c.constructor=="object"&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const u in c){const f=c[u];f&&typeof f=="object"&&r.push(f)}}}return t}function Wo(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return va(t)}try{return va(t)}finally{Error.stackTraceLimit=r}}function jo(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:o}=t;if(o!=null)for(const c of Object.keys(o))o[c]=cr(o[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(cr):cr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(cr)),t.allOf!=null&&(t.allOf=t.allOf.map(cr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(cr));const{definitions:r}=t;if(r!=null)for(const o of Object.keys(r))r[o]=cr(r[o]);return t}function cr(t){return typeof t=="boolean"?t:jo(t)}var nm=Symbol("Let zodToJsonSchema decide on which parser to use"),Ca={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},rm=t=>typeof t=="string"?{...Ca,name:t}:{...Ca,...t};function fn(){return{}}function im(t,r){var o,c,u;const f={type:"array"};return(o=t.type)!=null&&o._def&&((u=(c=t.type)==null?void 0:c._def)==null?void 0:u.typeName)!==Le.ZodAny&&(f.items=rt(t.type._def,{...r,currentPath:[...r.currentPath,"items"]})),t.minLength&&(f.minItems=t.minLength.value),t.maxLength&&(f.maxItems=t.maxLength.value),t.exactLength&&(f.minItems=t.exactLength.value,f.maxItems=t.exactLength.value),f}function om(t){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const o of t.checks)switch(o.kind){case"min":o.inclusive?r.minimum=o.value:r.exclusiveMinimum=o.value;break;case"max":o.inclusive?r.maximum=o.value:r.exclusiveMaximum=o.value;break;case"multipleOf":r.multipleOf=o.value;break}return r}function sm(){return{type:"boolean"}}function Qc(t,r){return rt(t.type._def,r)}var am=(t,r)=>rt(t.innerType._def,r);function eu(t,r,o){const c=o??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((u,f)=>eu(t,r,u))};switch(c){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return lm(t)}}var lm=t=>{const r={type:"integer",format:"unix-time"};for(const o of t.checks)switch(o.kind){case"min":r.minimum=o.value;break;case"max":r.maximum=o.value;break}return r};function cm(t,r){return{...rt(t.innerType._def,r),default:t.defaultValue()}}function um(t,r){return r.effectStrategy==="input"?rt(t.schema._def,r):fn()}function dm(t){return{type:"string",enum:Array.from(t.values)}}var fm=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function hm(t,r){const o=[rt(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),rt(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(u=>!!u),c=[];return o.forEach(u=>{if(fm(u))c.push(...u.allOf);else{let f=u;if("additionalProperties"in u&&u.additionalProperties===!1){const{additionalProperties:m,...g}=u;f=g}c.push(f)}}),c.length?{allOf:c}:void 0}function pm(t){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:r==="bigint"?"integer":r,const:t.value}}var ao=void 0,wn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ao===void 0&&(ao=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ao),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function tu(t,r){const o={type:"string"};if(t.checks)for(const c of t.checks)switch(c.kind){case"min":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,c.value):c.value;break;case"max":o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,c.value):c.value;break;case"email":switch(r.emailStrategy){case"format:email":_n(o,"email",c.message,r);break;case"format:idn-email":_n(o,"idn-email",c.message,r);break;case"pattern:zod":Yt(o,wn.email,c.message,r);break}break;case"url":_n(o,"uri",c.message,r);break;case"uuid":_n(o,"uuid",c.message,r);break;case"regex":Yt(o,c.regex,c.message,r);break;case"cuid":Yt(o,wn.cuid,c.message,r);break;case"cuid2":Yt(o,wn.cuid2,c.message,r);break;case"startsWith":Yt(o,RegExp(`^${lo(c.value,r)}`),c.message,r);break;case"endsWith":Yt(o,RegExp(`${lo(c.value,r)}$`),c.message,r);break;case"datetime":_n(o,"date-time",c.message,r);break;case"date":_n(o,"date",c.message,r);break;case"time":_n(o,"time",c.message,r);break;case"duration":_n(o,"duration",c.message,r);break;case"length":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,c.value):c.value,o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,c.value):c.value;break;case"includes":{Yt(o,RegExp(lo(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&_n(o,"ipv4",c.message,r),c.version!=="v4"&&_n(o,"ipv6",c.message,r);break}case"base64url":Yt(o,wn.base64url,c.message,r);break;case"jwt":Yt(o,wn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Yt(o,wn.ipv4Cidr,c.message,r),c.version!=="v4"&&Yt(o,wn.ipv6Cidr,c.message,r);break}case"emoji":Yt(o,wn.emoji(),c.message,r);break;case"ulid":{Yt(o,wn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{_n(o,"binary",c.message,r);break}case"contentEncoding:base64":{o.contentEncoding="base64";break}case"pattern:zod":{Yt(o,wn.base64,c.message,r);break}}break}case"nanoid":Yt(o,wn.nanoid,c.message,r)}return o}function lo(t,r){return r.patternStrategy==="escape"?gm(t):t}var mm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function gm(t){let r="";for(let o=0;o<t.length;o++)mm.has(t[o])||(r+="\\"),r+=t[o];return r}function _n(t,r,o,c){var u;t.format||(u=t.anyOf)!=null&&u.some(f=>f.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...o&&c.errorMessages&&{errorMessage:{format:o}}})):t.format=r}function Yt(t,r,o,c){var u;t.pattern||(u=t.allOf)!=null&&u.some(f=>f.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:ba(r,c),...o&&c.errorMessages&&{errorMessage:{pattern:o}}})):t.pattern=ba(r,c)}function ba(t,r){var o;if(!r.applyRegexFlags||!t.flags)return t.source;const c={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},u=c.i?t.source.toLowerCase():t.source;let f="",m=!1,g=!1,C=!1;for(let x=0;x<u.length;x++){if(m){f+=u[x],m=!1;continue}if(c.i){if(g){if(u[x].match(/[a-z]/)){C?(f+=u[x],f+=`${u[x-2]}-${u[x]}`.toUpperCase(),C=!1):u[x+1]==="-"&&((o=u[x+2])!=null&&o.match(/[a-z]/))?(f+=u[x],C=!0):f+=`${u[x]}${u[x].toUpperCase()}`;continue}}else if(u[x].match(/[a-z]/)){f+=`[${u[x]}${u[x].toUpperCase()}]`;continue}}if(c.m){if(u[x]==="^"){f+=`(^|(?<=[\r
37
- ]))`;continue}else if(u[x]==="$"){f+=`($|(?=[\r
38
- ]))`;continue}}if(c.s&&u[x]==="."){f+=g?`${u[x]}\r
39
- `:`[${u[x]}\r
40
- ]`;continue}f+=u[x],u[x]==="\\"?m=!0:g&&u[x]==="]"?g=!1:!g&&u[x]==="["&&(g=!0)}try{new RegExp(f)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return f}function nu(t,r){var o,c,u,f,m,g;const C={type:"object",additionalProperties:(o=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?o:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===Le.ZodString&&((u=t.keyType._def.checks)!=null&&u.length)){const{type:x,...A}=tu(t.keyType._def,r);return{...C,propertyNames:A}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===Le.ZodEnum)return{...C,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===Le.ZodBranded&&t.keyType._def.type._def.typeName===Le.ZodString&&((g=t.keyType._def.type._def.checks)!=null&&g.length)){const{type:x,...A}=Qc(t.keyType._def,r);return{...C,propertyNames:A}}}return C}function xm(t,r){if(r.mapStrategy==="record")return nu(t,r);const o=rt(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fn(),c=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fn();return{type:"array",maxItems:125,items:{type:"array",items:[o,c],minItems:2,maxItems:2}}}function ym(t){const r=t.values,c=Object.keys(t.values).filter(f=>typeof r[r[f]]!="number").map(f=>r[f]),u=Array.from(new Set(c.map(f=>typeof f)));return{type:u.length===1?u[0]==="string"?"string":"number":["string","number"],enum:c}}function wm(){return{not:fn()}}function _m(){return{type:"null"}}var Ao={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vm(t,r){const o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every(c=>c._def.typeName in Ao&&(!c._def.checks||!c._def.checks.length))){const c=o.reduce((u,f)=>{const m=Ao[f._def.typeName];return m&&!u.includes(m)?[...u,m]:u},[]);return{type:c.length>1?c:c[0]}}else if(o.every(c=>c._def.typeName==="ZodLiteral"&&!c.description)){const c=o.reduce((u,f)=>{const m=typeof f._def.value;switch(m){case"string":case"number":case"boolean":return[...u,m];case"bigint":return[...u,"integer"];case"object":if(f._def.value===null)return[...u,"null"];case"symbol":case"undefined":case"function":default:return u}},[]);if(c.length===o.length){const u=c.filter((f,m,g)=>g.indexOf(f)===m);return{type:u.length>1?u:u[0],enum:o.reduce((f,m)=>f.includes(m._def.value)?f:[...f,m._def.value],[])}}}else if(o.every(c=>c._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((c,u)=>[...c,...u._def.values.filter(f=>!c.includes(f))],[])};return Cm(t,r)}var Cm=(t,r)=>{const o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,u)=>rt(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${u}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return o.length?{anyOf:o}:void 0};function bm(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ao[t.innerType._def.typeName],"null"]};const o=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function Em(t){const r={type:"number"};if(!t.checks)return r;for(const o of t.checks)switch(o.kind){case"int":r.type="integer";break;case"min":o.inclusive?r.minimum=o.value:r.exclusiveMinimum=o.value;break;case"max":o.inclusive?r.maximum=o.value:r.exclusiveMaximum=o.value;break;case"multipleOf":r.multipleOf=o.value;break}return r}function Am(t,r){const o={type:"object",properties:{}},c=[],u=t.shape();for(const m in u){let g=u[m];if(g===void 0||g._def===void 0)continue;const C=Sm(g),x=rt(g._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});x!==void 0&&(o.properties[m]=x,C||c.push(m))}c.length&&(o.required=c);const f=Im(t,r);return f!==void 0&&(o.additionalProperties=f),o}function Im(t,r){if(t.catchall._def.typeName!=="ZodNever")return rt(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return r.removeAdditionalStrategy==="strict"?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}function Sm(t){try{return t.isOptional()}catch{return!0}}var Tm=(t,r)=>{var o;if(r.currentPath.toString()===((o=r.propertyPath)==null?void 0:o.toString()))return rt(t.innerType._def,r);const c=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:fn()},c]}:fn()},Nm=(t,r)=>{if(r.pipeStrategy==="input")return rt(t.in._def,r);if(r.pipeStrategy==="output")return rt(t.out._def,r);const o=rt(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=rt(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,c].filter(u=>u!==void 0)}};function Om(t,r){return rt(t.type._def,r)}function km(t,r){const c={type:"array",uniqueItems:!0,items:rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return t.minSize&&(c.minItems=t.minSize.value),t.maxSize&&(c.maxItems=t.maxSize.value),c}function Rm(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[]),additionalItems:rt(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[])}}function Mm(){return{not:fn()}}function Dm(){return fn()}var Pm=(t,r)=>rt(t.innerType._def,r),Bm=(t,r,o)=>{switch(r){case Le.ZodString:return tu(t,o);case Le.ZodNumber:return Em(t);case Le.ZodObject:return Am(t,o);case Le.ZodBigInt:return om(t);case Le.ZodBoolean:return sm();case Le.ZodDate:return eu(t,o);case Le.ZodUndefined:return Mm();case Le.ZodNull:return _m();case Le.ZodArray:return im(t,o);case Le.ZodUnion:case Le.ZodDiscriminatedUnion:return vm(t,o);case Le.ZodIntersection:return hm(t,o);case Le.ZodTuple:return Rm(t,o);case Le.ZodRecord:return nu(t,o);case Le.ZodLiteral:return pm(t);case Le.ZodEnum:return dm(t);case Le.ZodNativeEnum:return ym(t);case Le.ZodNullable:return bm(t,o);case Le.ZodOptional:return Tm(t,o);case Le.ZodMap:return xm(t,o);case Le.ZodSet:return km(t,o);case Le.ZodLazy:return()=>t.getter()._def;case Le.ZodPromise:return Om(t,o);case Le.ZodNaN:case Le.ZodNever:return wm();case Le.ZodEffects:return um(t,o);case Le.ZodAny:return fn();case Le.ZodUnknown:return Dm();case Le.ZodDefault:return cm(t,o);case Le.ZodBranded:return Qc(t,o);case Le.ZodReadonly:return Pm(t,o);case Le.ZodCatch:return am(t,o);case Le.ZodPipeline:return Nm(t,o);case Le.ZodFunction:case Le.ZodVoid:case Le.ZodSymbol:return;default:return(c=>{})()}},Lm=(t,r)=>{let o=0;for(;o<t.length&&o<r.length&&t[o]===r[o];o++);return[(t.length-o).toString(),...r.slice(o)].join("/")};function rt(t,r,o=!1){var c;const u=r.seen.get(t);if(r.override){const C=(c=r.override)==null?void 0:c.call(r,t,r,u,o);if(C!==nm)return C}if(u&&!o){const C=Fm(u,r);if(C!==void 0)return C}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=Bm(t,t.typeName,r),g=typeof m=="function"?rt(m(),r):m;if(g&&Um(t,r,g),r.postProcess){const C=r.postProcess(g,t,r);return f.jsonSchema=g,C}return f.jsonSchema=g,g}var Fm=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Lm(r.currentPath,t.path)};case"none":case"seen":return t.path.length<r.currentPath.length&&t.path.every((o,c)=>r.currentPath[c]===o)?(console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),fn()):r.$refStrategy==="seen"?fn():void 0}},Um=(t,r,o)=>(t.description&&(o.description=t.description),o),zm=t=>{const r=rm(t),o=r.name!==void 0?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([c,u])=>[u._def,{def:u._def,path:[...r.basePath,r.definitionPath,c],jsonSchema:void 0}]))}},Vm=(t,r)=>{var o;const c=zm(r);let u=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((x,[A,v])=>{var P;return{...x,[A]:(P=rt(v._def,{...c,currentPath:[...c.basePath,c.definitionPath,A]},!0))!=null?P:fn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(o=rt(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?o:fn(),g=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;g!==void 0&&(m.title=g);const C=f===void 0?u?{...m,[c.definitionPath]:u}:m:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...u,[f]:m}};return C.$schema="http://json-schema.org/draft-07/schema#",C},Io=Symbol.for("vercel.ai.schema");function Be(t){let r;return()=>(r==null&&(r=t()),r)}function Bi(t,{validate:r}={}){return{[Io]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function Zm(t){return typeof t=="object"&&t!==null&&Io in t&&t[Io]===!0&&"jsonSchema"in t&&"validate"in t}function $m(t){return t==null?Bi({properties:{},additionalProperties:!1}):Zm(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Pe(t):Hm(t):t()}function Hm(t){return Bi(()=>jo(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async r=>{const o=await t["~standard"].validate(r);return"value"in o?{success:!0,value:o.value}:{success:!1,error:new Jr({value:r,cause:o.issues})}}})}function Wm(t,r){var o;const c=(o=void 0)!=null?o:!1;return Bi(()=>Vm(t,{$refStrategy:c?"root":"none"}),{validate:async u=>{const f=await t.safeParseAsync(u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function jm(t,r){var o;const c=(o=void 0)!=null?o:!1;return Bi(()=>jo(Af(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async u=>{const f=await fc(t,u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function Gm(t){return"_zod"in t}function Pe(t,r){return Gm(t)?jm(t):Wm(t)}async function kt({value:t,schema:r,context:o}){const c=await Go({value:t,schema:r,context:o});if(!c.success)throw Jr.wrap({value:t,cause:c.error,context:o});return c.value}async function Go({value:t,schema:r,context:o}){const c=$m(r);try{if(c.validate==null)return{success:!0,value:t,rawValue:t};const u=await c.validate(t);return u.success?{success:!0,value:u.value,rawValue:t}:{success:!1,error:Jr.wrap({value:t,cause:u.error,context:o}),rawValue:t}}catch(u){return{success:!1,error:Jr.wrap({value:t,cause:u,context:o}),rawValue:t}}}async function ru({text:t,schema:r}){try{const o=Wo(t);return r==null?o:kt({value:o,schema:r})}catch(o){throw Ni.isInstance(o)||Jr.isInstance(o)?o:new Ni({text:t,cause:o})}}async function iu({text:t,schema:r}){try{const o=Wo(t);return r==null?{success:!0,value:o,rawValue:o}:await Go({value:o,schema:r})}catch(o){return{success:!1,error:Ni.isInstance(o)?o:new Ni({text:t,cause:o}),rawValue:void 0}}}function Ea(t){try{return Wo(t),!0}catch{return!1}}function Xm({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Wl).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await iu({text:o,schema:r}))}}))}async function Zn({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Go({value:r[t],schema:o});if(!c.success)throw new Rc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var qm=()=>globalThis.fetch,$n=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>su({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),ou=async({url:t,headers:r,formData:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>su({url:t,headers:r,body:{content:o,values:Object.fromEntries(o.entries())},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),su=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=qm()})=>{try{const g=await m(t,{method:"POST",headers:Jc(r,`ai-sdk/provider-utils/${qp}`,Gp()),body:o.content,signal:f}),C=ri(g);if(!g.ok){let x;try{x=await u({response:g,url:t,requestBodyValues:o.values})}catch(A){throw Eo(A)||cn.isInstance(A)?A:new cn({message:"Failed to process error response",cause:A,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}throw x.value}try{return await c({response:g,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(Eo(x)||cn.isInstance(x))?x:new cn({message:"Failed to process successful response",cause:x,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}}catch(g){throw jp({error:g,url:t,requestBodyValues:o.values})}};function Ym({id:t,inputSchema:r}){return({execute:o,outputSchema:c,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:g,onInputAvailable:C,...x})=>({type:"provider",id:t,args:x,inputSchema:r,outputSchema:c,execute:o,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:g,onInputAvailable:C})}function Dn({id:t,inputSchema:r,outputSchema:o,supportsDeferredResults:c}){return({execute:u,needsApproval:f,toModelOutput:m,onInputStart:g,onInputDelta:C,onInputAvailable:x,...A})=>({type:"provider",id:t,args:A,inputSchema:r,outputSchema:o,execute:u,needsApproval:f,toModelOutput:m,onInputStart:g,onInputDelta:C,onInputAvailable:x,supportsDeferredResults:c})}var Km=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const m=await c.text(),g=ri(c);if(m.trim()==="")return{responseHeaders:g,value:new cn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})};try{const C=await ru({text:m,schema:t});return{responseHeaders:g,value:new cn({message:r(C),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,data:C,isRetryable:o?.(c,C)})}}catch{return{responseHeaders:g,value:new cn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})}}},Xo=t=>async({response:r})=>{const o=ri(r);if(r.body==null)throw new Cp({});return{responseHeaders:o,value:Xm({stream:r.body,schema:t})}},hr=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await iu({text:u,schema:t}),m=ri(r);if(!f.success)throw new cn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}},Jm=()=>async({response:t,url:r,requestBodyValues:o})=>{const c=ri(t);if(!t.body)throw new cn({message:"Response body is empty",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0});try{const u=await t.arrayBuffer();return{responseHeaders:c,value:new Uint8Array(u)}}catch(u){throw new cn({message:"Failed to read response as array buffer",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:u})}};function Qm(t){return t?.replace(/\/$/,"")}var qo=T({error:T({message:w(),type:w().nullish(),param:mr().nullish(),code:Qe([w(),j()]).nullish()})}),An=Km({errorSchema:qo,errorToMessage:t=>t.error.message});function au(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),o=t.startsWith("gpt-4")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")&&!t.startsWith("gpt-5.4-nano")||t.startsWith("o3")||t.startsWith("o4-mini"),c=t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),u=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2")||t.startsWith("gpt-5.3")||t.startsWith("gpt-5.4");return{supportsFlexProcessing:r,supportsPriorityProcessing:o,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:u}}function Aa(t){var r,o,c,u,f,m;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const g=(r=t.prompt_tokens)!=null?r:0,C=(o=t.completion_tokens)!=null?o:0,x=(u=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?u:0,A=(m=(f=t.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:0;return{inputTokens:{total:g,noCache:g-x,cacheRead:x,cacheWrite:void 0},outputTokens:{total:C,text:C-A,reasoning:A},raw:t}}function eg({prompt:t,systemMessageMode:r="system"}){var o;const c=[],u=[];for(const{role:f,content:m}of t)switch(f){case"system":{switch(r){case"system":{c.push({role:"system",content:m});break}case"developer":{c.push({role:"developer",content:m});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const g=r;throw new Error(`Unsupported system message mode: ${g}`)}}break}case"user":{if(m.length===1&&m[0].type==="text"){c.push({role:"user",content:m[0].text});break}c.push({role:"user",content:m.map((g,C)=>{var x,A,v;switch(g.type){case"text":return{type:"text",text:g.text};case"file":if(g.mediaType.startsWith("image/")){const P=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${P};base64,${Tr(g.data)}`,detail:(A=(x=g.providerOptions)==null?void 0:x.openai)==null?void 0:A.imageDetail}}}else if(g.mediaType.startsWith("audio/")){if(g.data instanceof URL)throw new zn({functionality:"audio file parts with URLs"});switch(g.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Tr(g.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Tr(g.data),format:"mp3"}};default:throw new zn({functionality:`audio content parts with media type ${g.mediaType}`})}}else if(g.mediaType==="application/pdf"){if(g.data instanceof URL)throw new zn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof g.data=="string"&&g.data.startsWith("file-")?{file_id:g.data}:{filename:(v=g.filename)!=null?v:`part-${C}.pdf`,file_data:`data:application/pdf;base64,${Tr(g.data)}`}}}else throw new zn({functionality:`file part media type ${g.mediaType}`})}})});break}case"assistant":{let g="";const C=[];for(const x of m)switch(x.type){case"text":{g+=x.text;break}case"tool-call":{C.push({id:x.toolCallId,type:"function",function:{name:x.toolName,arguments:JSON.stringify(x.input)}});break}}c.push({role:"assistant",content:g,tool_calls:C.length>0?C:void 0});break}case"tool":{for(const g of m){if(g.type==="tool-approval-response")continue;const C=g.output;let x;switch(C.type){case"text":case"error-text":x=C.value;break;case"execution-denied":x=(o=C.reason)!=null?o:"Tool execution denied.";break;case"content":case"json":case"error-json":x=JSON.stringify(C.value);break}c.push({role:"tool",tool_call_id:g.toolCallId,content:x})}break}default:{const g=f;throw new Error(`Unsupported role: ${g}`)}}return{messages:c,warnings:u}}function co({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o?new Date(o*1e3):void 0}}function Ia(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var tg=Be(()=>Pe(T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({message:T({role:X("assistant").nullish(),content:w().nullish(),tool_calls:ue(T({id:w().nullish(),type:X("function"),function:T({name:w(),arguments:w()})})).nullish(),annotations:ue(T({type:X("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}),index:j(),logprobs:T({content:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),ng=Be(()=>Pe(Qe([T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({delta:T({role:Se(["assistant"]).nullish(),content:w().nullish(),tool_calls:ue(T({index:j(),id:w().nullish(),type:X("function").nullish(),function:T({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ue(T({type:X("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:T({content:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:j()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),qo]))),rg=Be(()=>Pe(T({logitBias:ht(Dh(),j()).optional(),logprobs:Qe([Rt(),j()]).optional(),parallelToolCalls:Rt().optional(),user:w().optional(),reasoningEffort:Se(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:Rt().optional(),metadata:ht(w().max(64),w().max(512)).optional(),prediction:ht(w(),mr()).optional(),serviceTier:Se(["auto","flex","priority","default"]).optional(),strictJsonSchema:Rt().optional(),textVerbosity:Se(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheRetention:Se(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Se(["system","developer","remove"]).optional(),forceReasoning:Rt().optional()})));function ig({tools:t,toolChoice:r}){t=t?.length?t:void 0;const o=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const c=[];for(const f of t)switch(f.type){case"function":c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema,...f.strict!=null?{strict:f.strict}:{}}});break;default:o.push({type:"unsupported",feature:`tool type: ${f.type}`});break}if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:o};const u=r.type;switch(u){case"auto":case"none":case"required":return{tools:c,toolChoice:u,toolWarnings:o};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:o};default:{const f=u;throw new zn({functionality:`tool choice type: ${f}`})}}}var og=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:m,stopSequences:g,responseFormat:C,seed:x,tools:A,toolChoice:v,providerOptions:P}){var O,M,D,B,G;const Z=[],z=(O=await Zn({provider:"openai",providerOptions:P,schema:rg}))!=null?O:{},ee=au(this.modelId),K=(M=z.forceReasoning)!=null?M:ee.isReasoningModel;u!=null&&Z.push({type:"unsupported",feature:"topK"});const{messages:V,warnings:U}=eg({prompt:t,systemMessageMode:(D=z.systemMessageMode)!=null?D:K?"developer":ee.systemMessageMode});Z.push(...U);const J=(B=z.strictJsonSchema)!=null?B:!0,S={model:this.modelId,logit_bias:z.logitBias,logprobs:z.logprobs===!0||typeof z.logprobs=="number"?!0:void 0,top_logprobs:typeof z.logprobs=="number"?z.logprobs:typeof z.logprobs=="boolean"&&z.logprobs?0:void 0,user:z.user,parallel_tool_calls:z.parallelToolCalls,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:C?.type==="json"?C.schema!=null?{type:"json_schema",json_schema:{schema:C.schema,strict:J,name:(G=C.name)!=null?G:"response",description:C.description}}:{type:"json_object"}:void 0,stop:g,seed:x,verbosity:z.textVerbosity,max_completion_tokens:z.maxCompletionTokens,store:z.store,metadata:z.metadata,prediction:z.prediction,reasoning_effort:z.reasoningEffort,service_tier:z.serviceTier,prompt_cache_key:z.promptCacheKey,prompt_cache_retention:z.promptCacheRetention,safety_identifier:z.safetyIdentifier,messages:V};K?((z.reasoningEffort!=="none"||!ee.supportsNonReasoningParameters)&&(S.temperature!=null&&(S.temperature=void 0,Z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,Z.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),S.logprobs!=null&&(S.logprobs=void 0,Z.push({type:"other",message:"logprobs is not supported for reasoning models"}))),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,Z.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),S.presence_penalty!=null&&(S.presence_penalty=void 0,Z.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),S.logit_bias!=null&&(S.logit_bias=void 0,Z.push({type:"other",message:"logitBias is not supported for reasoning models"})),S.top_logprobs!=null&&(S.top_logprobs=void 0,Z.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),S.max_tokens!=null&&(S.max_completion_tokens==null&&(S.max_completion_tokens=S.max_tokens),S.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&S.temperature!=null&&(S.temperature=void 0,Z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),z.serviceTier==="flex"&&!ee.supportsFlexProcessing&&(Z.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),S.service_tier=void 0),z.serviceTier==="priority"&&!ee.supportsPriorityProcessing&&(Z.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),S.service_tier=void 0);const{tools:Te,toolChoice:ye,toolWarnings:re}=ig({tools:A,toolChoice:v});return{args:{...S,tools:Te,tool_choice:ye},warnings:[...Z,...re]}}async doGenerate(t){var r,o,c,u,f,m,g;const{args:C,warnings:x}=await this.getArgs(t),{responseHeaders:A,value:v,rawValue:P}=await $n({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:C,failedResponseHandler:An,successfulResponseHandler:hr(tg),abortSignal:t.abortSignal,fetch:this.config.fetch}),O=v.choices[0],M=[],D=O.message.content;D!=null&&D.length>0&&M.push({type:"text",text:D});for(const Z of(r=O.message.tool_calls)!=null?r:[])M.push({type:"tool-call",toolCallId:(o=Z.id)!=null?o:Kt(),toolName:Z.function.name,input:Z.function.arguments});for(const Z of(c=O.message.annotations)!=null?c:[])M.push({type:"source",sourceType:"url",id:Kt(),url:Z.url_citation.url,title:Z.url_citation.title});const B=(u=v.usage)==null?void 0:u.completion_tokens_details;(f=v.usage)==null||f.prompt_tokens_details;const G={openai:{}};return B?.accepted_prediction_tokens!=null&&(G.openai.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(G.openai.rejectedPredictionTokens=B?.rejected_prediction_tokens),((m=O.logprobs)==null?void 0:m.content)!=null&&(G.openai.logprobs=O.logprobs.content),{content:M,finishReason:{unified:Ia(O.finish_reason),raw:(g=O.finish_reason)!=null?g:void 0},usage:Aa(v.usage),request:{body:C},response:{...co(v),headers:A,body:P},warnings:x,providerMetadata:G}}async doStream(t){const{args:r,warnings:o}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:u,value:f}=await $n({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:c,failedResponseHandler:An,successfulResponseHandler:Xo(ng),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=[];let g={unified:"other",raw:void 0},C,x=!1,A=!1;const v={openai:{}};return{stream:f.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:o})},transform(P,O){var M,D,B,G,Z,z,ee,K,V,U,J,S,Te,ye,re,xe,Me;if(t.includeRawChunks&&O.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g={unified:"error",raw:void 0},O.enqueue({type:"error",error:P.error});return}const $=P.value;if("error"in $){g={unified:"error",raw:void 0},O.enqueue({type:"error",error:$.error});return}if(!x){const Q=co($);Object.values(Q).some(Boolean)&&(x=!0,O.enqueue({type:"response-metadata",...co($)}))}$.usage!=null&&(C=$.usage,((M=$.usage.completion_tokens_details)==null?void 0:M.accepted_prediction_tokens)!=null&&(v.openai.acceptedPredictionTokens=(D=$.usage.completion_tokens_details)==null?void 0:D.accepted_prediction_tokens),((B=$.usage.completion_tokens_details)==null?void 0:B.rejected_prediction_tokens)!=null&&(v.openai.rejectedPredictionTokens=(G=$.usage.completion_tokens_details)==null?void 0:G.rejected_prediction_tokens));const ge=$.choices[0];if(ge?.finish_reason!=null&&(g={unified:Ia(ge.finish_reason),raw:ge.finish_reason}),((Z=ge?.logprobs)==null?void 0:Z.content)!=null&&(v.openai.logprobs=ge.logprobs.content),ge?.delta==null)return;const ne=ge.delta;if(ne.content!=null&&(A||(O.enqueue({type:"text-start",id:"0"}),A=!0),O.enqueue({type:"text-delta",id:"0",delta:ne.content})),ne.tool_calls!=null)for(const Q of ne.tool_calls){const me=Q.index;if(m[me]==null){if(Q.type!=null&&Q.type!=="function")throw new so({data:Q,message:"Expected 'function' type."});if(Q.id==null)throw new so({data:Q,message:"Expected 'id' to be a string."});if(((z=Q.function)==null?void 0:z.name)==null)throw new so({data:Q,message:"Expected 'function.name' to be a string."});O.enqueue({type:"tool-input-start",id:Q.id,toolName:Q.function.name}),m[me]={id:Q.id,type:"function",function:{name:Q.function.name,arguments:(ee=Q.function.arguments)!=null?ee:""},hasFinished:!1};const ie=m[me];((K=ie.function)==null?void 0:K.name)!=null&&((V=ie.function)==null?void 0:V.arguments)!=null&&(ie.function.arguments.length>0&&O.enqueue({type:"tool-input-delta",id:ie.id,delta:ie.function.arguments}),Ea(ie.function.arguments)&&(O.enqueue({type:"tool-input-end",id:ie.id}),O.enqueue({type:"tool-call",toolCallId:(U=ie.id)!=null?U:Kt(),toolName:ie.function.name,input:ie.function.arguments}),ie.hasFinished=!0));continue}const fe=m[me];fe.hasFinished||(((J=Q.function)==null?void 0:J.arguments)!=null&&(fe.function.arguments+=(Te=(S=Q.function)==null?void 0:S.arguments)!=null?Te:""),O.enqueue({type:"tool-input-delta",id:fe.id,delta:(ye=Q.function.arguments)!=null?ye:""}),((re=fe.function)==null?void 0:re.name)!=null&&((xe=fe.function)==null?void 0:xe.arguments)!=null&&Ea(fe.function.arguments)&&(O.enqueue({type:"tool-input-end",id:fe.id}),O.enqueue({type:"tool-call",toolCallId:(Me=fe.id)!=null?Me:Kt(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}if(ne.annotations!=null)for(const Q of ne.annotations)O.enqueue({type:"source",sourceType:"url",id:Kt(),url:Q.url_citation.url,title:Q.url_citation.title})},flush(P){A&&P.enqueue({type:"text-end",id:"0"}),P.enqueue({type:"finish",finishReason:g,usage:Aa(C),...v!=null?{providerMetadata:v}:{}})}})),request:{body:c},response:{headers:u}}}};function Sa(t){var r,o,c,u;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=(r=t.prompt_tokens)!=null?r:0,m=(o=t.completion_tokens)!=null?o:0;return{inputTokens:{total:(c=t.prompt_tokens)!=null?c:void 0,noCache:f,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(u=t.completion_tokens)!=null?u:void 0,text:m,reasoning:void 0},raw:t}}function sg({prompt:t,user:r="user",assistant:o="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
39
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const E of this.seen.entries()){const A=E[1];if(r===E[0]){m(E);continue}if(c.external){const T=c.external.registry.get(E[0])?.id;if(r!==E[0]&&T){m(E);continue}}if(this.metadataRegistry.get(E[0])?.id){m(E);continue}if(A.cycle){m(E);continue}if(A.count>1&&c.reused==="ref"){m(E);continue}}const x=(E,A)=>{const D=this.seen.get(E),T=D.def??D.schema,S={...T};if(D.ref===null)return;const P=D.ref;if(D.ref=null,P){x(P,A);const M=this.seen.get(P).schema;M.$ref&&A.target==="draft-7"?(T.allOf=T.allOf??[],T.allOf.push(M)):(Object.assign(T,M),Object.assign(T,S))}D.isParent||this.override({zodSchema:E,jsonSchema:T,path:D.path??[]})};for(const E of[...this.seen.entries()].reverse())x(E[0],{target:this.target});const v={};if(this.target==="draft-2020-12"?v.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?v.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const E=c.external.registry.get(r)?.id;if(!E)throw new Error("Schema is missing an `id` property");v.$id=c.external.uri(E)}Object.assign(v,d.def);const g=c.external?.defs??{};for(const E of this.seen.entries()){const A=E[1];A.def&&A.defId&&(g[A.defId]=A.def)}c.external||Object.keys(g).length>0&&(this.target==="draft-2020-12"?v.$defs=g:v.definitions=g);try{return JSON.parse(JSON.stringify(v))}catch{throw new Error("Error converting schema to JSON.")}}}function Uf(t,r){if(t instanceof yc){const c=new Zs(r),d={};for(const x of t._idmap.entries()){const[v,g]=x;c.process(g)}const f={},m={registry:t,uri:r?.uri,defs:d};for(const x of t._idmap.entries()){const[v,g]=x;f[v]=c.emit(g,{...r,external:m})}if(Object.keys(d).length>0){const x=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[x]:d}}return{schemas:f}}const i=new Zs(r);return i.process(t),i.emit(t,r)}function Lt(t,r){const i=r??{seen:new Set};if(i.seen.has(t))return!1;i.seen.add(t);const d=t._zod.def;switch(d.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Lt(d.element,i);case"object":{for(const f in d.shape)if(Lt(d.shape[f],i))return!0;return!1}case"union":{for(const f of d.options)if(Lt(f,i))return!0;return!1}case"intersection":return Lt(d.left,i)||Lt(d.right,i);case"tuple":{for(const f of d.items)if(Lt(f,i))return!0;return!!(d.rest&&Lt(d.rest,i))}case"record":return Lt(d.keyType,i)||Lt(d.valueType,i);case"map":return Lt(d.keyType,i)||Lt(d.valueType,i);case"set":return Lt(d.valueType,i);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Lt(d.innerType,i);case"lazy":return Lt(d.getter(),i);case"default":return Lt(d.innerType,i);case"prefault":return Lt(d.innerType,i);case"custom":return!1;case"transform":return!0;case"pipe":return Lt(d.in,i)||Lt(d.out,i);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${d.type}`)}const zf=oe("ZodISODateTime",(t,r)=>{a0.init(t,r),It.init(t,r)});function Vf(t){return mf(zf,t)}const Zf=oe("ZodISODate",(t,r)=>{l0.init(t,r),It.init(t,r)});function $f(t){return gf(Zf,t)}const jf=oe("ZodISOTime",(t,r)=>{c0.init(t,r),It.init(t,r)});function Hf(t){return xf(jf,t)}const Wf=oe("ZodISODuration",(t,r)=>{u0.init(t,r),It.init(t,r)});function Gf(t){return yf(Wf,t)}const qf=(t,r)=>{ic.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:i=>r1(t,i)},flatten:{value:i=>n1(t,i)},addIssue:{value:i=>t.issues.push(i)},addIssues:{value:i=>t.issues.push(...i)},isEmpty:{get(){return t.issues.length===0}}})},Uo=oe("ZodError",qf,{Parent:Error}),Xf=o1(Uo),Yf=i1(Uo),Kf=ac(Uo),vc=lc(Uo),_t=oe("ZodType",(t,r)=>(ht.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...i)=>t.clone({...r,checks:[...r.checks??[],...i.map(c=>typeof c=="function"?{_zod:{check:c,def:{check:"custom"},onattach:[]}}:c)]}),t.clone=(i,c)=>gr(t,i,c),t.brand=()=>t,t.register=((i,c)=>(i.add(t,c),t)),t.parse=(i,c)=>Xf(t,i,c,{callee:t.parse}),t.safeParse=(i,c)=>Kf(t,i,c),t.parseAsync=async(i,c)=>Yf(t,i,c,{callee:t.parseAsync}),t.safeParseAsync=async(i,c)=>vc(t,i,c),t.spa=t.safeParseAsync,t.refine=(i,c)=>t.check(Wh(i,c)),t.superRefine=i=>t.check(Gh(i)),t.overwrite=i=>t.check(so(i)),t.optional=()=>Hs(t),t.nullable=()=>Ws(t),t.nullish=()=>Hs(Ws(t)),t.nonoptional=i=>Lh(t,i),t.array=()=>ue(t),t.or=i=>st([t,i]),t.and=i=>Sh(t,i),t.transform=i=>Gs(t,kh(i)),t.default=i=>Dh(t,i),t.prefault=i=>Bh(t,i),t.catch=i=>Uh(t,i),t.pipe=i=>Gs(t,i),t.readonly=()=>Zh(t),t.describe=i=>{const c=t.clone();return Gr.add(c,{description:i}),c},Object.defineProperty(t,"description",{get(){return Gr.get(t)?.description},configurable:!0}),t.meta=(...i)=>{if(i.length===0)return Gr.get(t);const c=t.clone();return Gr.add(c,i[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cc=oe("_ZodString",(t,r)=>{ji.init(t,r),_t.init(t,r);const i=t._zod.bag;t.format=i.format??null,t.minLength=i.minimum??null,t.maxLength=i.maximum??null,t.regex=(...c)=>t.check(Sf(...c)),t.includes=(...c)=>t.check(Of(...c)),t.startsWith=(...c)=>t.check(kf(...c)),t.endsWith=(...c)=>t.check(Rf(...c)),t.min=(...c)=>t.check(Mo(...c)),t.max=(...c)=>t.check(wc(...c)),t.length=(...c)=>t.check(_c(...c)),t.nonempty=(...c)=>t.check(Mo(1,...c)),t.lowercase=c=>t.check(Tf(c)),t.uppercase=c=>t.check(Nf(c)),t.trim=()=>t.check(Df()),t.normalize=(...c)=>t.check(Mf(...c)),t.toLowerCase=()=>t.check(Pf()),t.toUpperCase=()=>t.check(Bf())}),Jf=oe("ZodString",(t,r)=>{ji.init(t,r),Cc.init(t,r),t.email=i=>t.check(G0(Qf,i)),t.url=i=>t.check(J0(eh,i)),t.jwt=i=>t.check(pf(mh,i)),t.emoji=i=>t.check(Q0(th,i)),t.guid=i=>t.check(Fs($s,i)),t.uuid=i=>t.check(q0(Co,i)),t.uuidv4=i=>t.check(X0(Co,i)),t.uuidv6=i=>t.check(Y0(Co,i)),t.uuidv7=i=>t.check(K0(Co,i)),t.nanoid=i=>t.check(ef(nh,i)),t.guid=i=>t.check(Fs($s,i)),t.cuid=i=>t.check(tf(rh,i)),t.cuid2=i=>t.check(nf(oh,i)),t.ulid=i=>t.check(rf(ih,i)),t.base64=i=>t.check(df(fh,i)),t.base64url=i=>t.check(ff(hh,i)),t.xid=i=>t.check(of(sh,i)),t.ksuid=i=>t.check(sf(ah,i)),t.ipv4=i=>t.check(af(lh,i)),t.ipv6=i=>t.check(lf(ch,i)),t.cidrv4=i=>t.check(cf(uh,i)),t.cidrv6=i=>t.check(uf(dh,i)),t.e164=i=>t.check(hf(ph,i)),t.datetime=i=>t.check(Vf(i)),t.date=i=>t.check($f(i)),t.time=i=>t.check(Hf(i)),t.duration=i=>t.check(Gf(i))});function w(t){return W0(Jf,t)}const It=oe("ZodStringFormat",(t,r)=>{bt.init(t,r),Cc.init(t,r)}),Qf=oe("ZodEmail",(t,r)=>{J1.init(t,r),It.init(t,r)}),$s=oe("ZodGUID",(t,r)=>{Y1.init(t,r),It.init(t,r)}),Co=oe("ZodUUID",(t,r)=>{K1.init(t,r),It.init(t,r)}),eh=oe("ZodURL",(t,r)=>{Q1.init(t,r),It.init(t,r)}),th=oe("ZodEmoji",(t,r)=>{e0.init(t,r),It.init(t,r)}),nh=oe("ZodNanoID",(t,r)=>{t0.init(t,r),It.init(t,r)}),rh=oe("ZodCUID",(t,r)=>{n0.init(t,r),It.init(t,r)}),oh=oe("ZodCUID2",(t,r)=>{r0.init(t,r),It.init(t,r)}),ih=oe("ZodULID",(t,r)=>{o0.init(t,r),It.init(t,r)}),sh=oe("ZodXID",(t,r)=>{i0.init(t,r),It.init(t,r)}),ah=oe("ZodKSUID",(t,r)=>{s0.init(t,r),It.init(t,r)}),lh=oe("ZodIPv4",(t,r)=>{d0.init(t,r),It.init(t,r)}),ch=oe("ZodIPv6",(t,r)=>{f0.init(t,r),It.init(t,r)}),uh=oe("ZodCIDRv4",(t,r)=>{h0.init(t,r),It.init(t,r)}),dh=oe("ZodCIDRv6",(t,r)=>{p0.init(t,r),It.init(t,r)}),fh=oe("ZodBase64",(t,r)=>{m0.init(t,r),It.init(t,r)}),hh=oe("ZodBase64URL",(t,r)=>{x0.init(t,r),It.init(t,r)}),ph=oe("ZodE164",(t,r)=>{y0.init(t,r),It.init(t,r)}),mh=oe("ZodJWT",(t,r)=>{_0.init(t,r),It.init(t,r)}),Hi=oe("ZodNumber",(t,r)=>{gc.init(t,r),_t.init(t,r),t.gt=(c,d)=>t.check(zs(c,d)),t.gte=(c,d)=>t.check(ui(c,d)),t.min=(c,d)=>t.check(ui(c,d)),t.lt=(c,d)=>t.check(Us(c,d)),t.lte=(c,d)=>t.check(ci(c,d)),t.max=(c,d)=>t.check(ci(c,d)),t.int=c=>t.check(js(c)),t.safe=c=>t.check(js(c)),t.positive=c=>t.check(zs(0,c)),t.nonnegative=c=>t.check(ui(0,c)),t.negative=c=>t.check(Us(0,c)),t.nonpositive=c=>t.check(ci(0,c)),t.multipleOf=(c,d)=>t.check(Vs(c,d)),t.step=(c,d)=>t.check(Vs(c,d)),t.finite=()=>t;const i=t._zod.bag;t.minValue=Math.max(i.minimum??Number.NEGATIVE_INFINITY,i.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(i.maximum??Number.POSITIVE_INFINITY,i.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(i.format??"").includes("int")||Number.isSafeInteger(i.multipleOf??.5),t.isFinite=!0,t.format=i.format??null});function j(t){return wf(Hi,t)}const gh=oe("ZodNumberFormat",(t,r)=>{v0.init(t,r),Hi.init(t,r)});function js(t){return vf(gh,t)}const xh=oe("ZodBoolean",(t,r)=>{C0.init(t,r),_t.init(t,r)});function Mt(t){return Cf(xh,t)}const yh=oe("ZodNull",(t,r)=>{b0.init(t,r),_t.init(t,r)});function bc(t){return bf(yh,t)}const wh=oe("ZodAny",(t,r)=>{A0.init(t,r),_t.init(t,r)});function xr(){return Af(wh)}const _h=oe("ZodUnknown",(t,r)=>{E0.init(t,r),_t.init(t,r)});function Cn(){return Ef(_h)}const vh=oe("ZodNever",(t,r)=>{I0.init(t,r),_t.init(t,r)});function Ch(t){return If(vh,t)}const bh=oe("ZodArray",(t,r)=>{S0.init(t,r),_t.init(t,r),t.element=r.element,t.min=(i,c)=>t.check(Mo(i,c)),t.nonempty=i=>t.check(Mo(1,i)),t.max=(i,c)=>t.check(wc(i,c)),t.length=(i,c)=>t.check(_c(i,c)),t.unwrap=()=>t.element});function ue(t,r){return Lf(bh,t,r)}const Ah=oe("ZodObject",(t,r)=>{T0.init(t,r),_t.init(t,r),lt(t,"shape",()=>r.shape),t.keyof=()=>Ae(Object.keys(t._zod.def.shape)),t.catchall=i=>t.clone({...t._zod.def,catchall:i}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Cn()}),t.loose=()=>t.clone({...t._zod.def,catchall:Cn()}),t.strict=()=>t.clone({...t._zod.def,catchall:Ch()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=i=>Jd(t,i),t.merge=i=>Qd(t,i),t.pick=i=>Yd(t,i),t.omit=i=>Kd(t,i),t.partial=(...i)=>e1(Ec,t,i[0]),t.required=(...i)=>t1(Ic,t,i[0])});function N(t,r){const i={type:"object",get shape(){return Zi(this,"shape",{...t}),this.shape},...Ie(r)};return new Ah(i)}const Ac=oe("ZodUnion",(t,r)=>{xc.init(t,r),_t.init(t,r),t.options=r.options});function st(t,r){return new Ac({type:"union",options:t,...Ie(r)})}const Eh=oe("ZodDiscriminatedUnion",(t,r)=>{Ac.init(t,r),N0.init(t,r)});function mt(t,r,i){return new Eh({type:"union",options:r,discriminator:t,...Ie(i)})}const Ih=oe("ZodIntersection",(t,r)=>{O0.init(t,r),_t.init(t,r)});function Sh(t,r){return new Ih({type:"intersection",left:t,right:r})}const Th=oe("ZodRecord",(t,r)=>{k0.init(t,r),_t.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function wt(t,r,i){return new Th({type:"record",keyType:t,valueType:r,...Ie(i)})}const Ai=oe("ZodEnum",(t,r)=>{R0.init(t,r),_t.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);const i=new Set(Object.keys(r.entries));t.extract=(c,d)=>{const f={};for(const m of c)if(i.has(m))f[m]=r.entries[m];else throw new Error(`Key ${m} not found in enum`);return new Ai({...r,checks:[],...Ie(d),entries:f})},t.exclude=(c,d)=>{const f={...r.entries};for(const m of c)if(i.has(m))delete f[m];else throw new Error(`Key ${m} not found in enum`);return new Ai({...r,checks:[],...Ie(d),entries:f})}});function Ae(t,r){const i=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new Ai({type:"enum",entries:i,...Ie(r)})}const Nh=oe("ZodLiteral",(t,r)=>{M0.init(t,r),_t.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function Y(t,r){return new Nh({type:"literal",values:Array.isArray(t)?t:[t],...Ie(r)})}const Oh=oe("ZodTransform",(t,r)=>{D0.init(t,r),_t.init(t,r),t._zod.parse=(i,c)=>{i.addIssue=f=>{if(typeof f=="string")i.issues.push(eo(f,i.value,r));else{const m=f;m.fatal&&(m.continue=!1),m.code??(m.code="custom"),m.input??(m.input=i.value),m.inst??(m.inst=t),m.continue??(m.continue=!0),i.issues.push(eo(m))}};const d=r.transform(i.value,i);return d instanceof Promise?d.then(f=>(i.value=f,i)):(i.value=d,i)}});function kh(t){return new Oh({type:"transform",transform:t})}const Ec=oe("ZodOptional",(t,r)=>{P0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Hs(t){return new Ec({type:"optional",innerType:t})}const Rh=oe("ZodNullable",(t,r)=>{B0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Ws(t){return new Rh({type:"nullable",innerType:t})}const Mh=oe("ZodDefault",(t,r)=>{L0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Dh(t,r){return new Mh({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ph=oe("ZodPrefault",(t,r)=>{F0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Bh(t,r){return new Ph({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ic=oe("ZodNonOptional",(t,r)=>{U0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Lh(t,r){return new Ic({type:"nonoptional",innerType:t,...Ie(r)})}const Fh=oe("ZodCatch",(t,r)=>{z0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Uh(t,r){return new Fh({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const zh=oe("ZodPipe",(t,r)=>{V0.init(t,r),_t.init(t,r),t.in=r.in,t.out=r.out});function Gs(t,r){return new zh({type:"pipe",in:t,out:r})}const Vh=oe("ZodReadonly",(t,r)=>{Z0.init(t,r),_t.init(t,r)});function Zh(t){return new Vh({type:"readonly",innerType:t})}const $h=oe("ZodLazy",(t,r)=>{$0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.getter()});function Wi(t){return new $h({type:"lazy",getter:t})}const jh=oe("ZodCustom",(t,r)=>{j0.init(t,r),_t.init(t,r)});function Hh(t){const r=new on({check:"custom"});return r._zod.check=t,r}function Wh(t,r={}){return Ff(jh,t,r)}function Gh(t){const r=Hh(i=>(i.addIssue=c=>{if(typeof c=="string")i.issues.push(eo(c,i.value,r._zod.def));else{const d=c;d.fatal&&(d.continue=!1),d.code??(d.code="custom"),d.input??(d.input=i.value),d.inst??(d.inst=r),d.continue??(d.continue=!r._zod.def.abort),i.issues.push(eo(d))}},t(i.value,i)));return r}function qh(t){return _f(Hi,t)}var je;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(je||(je={}));function qs(...t){return t.reduce((r,i)=>({...r,...i??{}}),{})}function zo(t){return Object.fromEntries([...t.headers])}var Xh=({prefix:t,size:r=16,alphabet:i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const d=()=>{const f=i.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=i[Math.random()*f|0];return m.join("")};if(t==null)return d;if(i.includes(c))throw new Dl({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${i}".`});return()=>`${t}${c}${d()}`},bo=Xh();function Ei(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Yh=["fetch failed","failed to fetch"];function Kh({error:t,url:r,requestBodyValues:i}){if(Ei(t))return t;if(t instanceof TypeError&&Yh.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Vn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return t}function Jh(t=globalThis){var r,i,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(i=t.process)==null?void 0:i.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Qh(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((i,c)=>{r[c.toLowerCase()]=i});else{Array.isArray(t)||(t=Object.entries(t));for(const[i,c]of t)c!=null&&(r[i.toLowerCase()]=c)}return r}function Sc(t,...r){const i=new Headers(Qh(t)),c=i.get("user-agent")||"";return i.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(i.entries())}var ep="3.0.18";function tp({apiKey:t,environmentVariableName:r,apiKeyParameterName:i="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new wo({message:`${c} API key must be a string.`});if(typeof process>"u")throw new wo({message:`${c} API key is missing. Pass it using the '${i}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new wo({message:`${c} API key is missing. Pass it using the '${i}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new wo({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var np=/"__proto__"\s*:/,rp=/"constructor"\s*:/;function Xs(t){const r=JSON.parse(t);return r===null||typeof r!="object"||np.test(t)===!1&&rp.test(t)===!1?r:op(r)}function op(t){let r=[t];for(;r.length;){const i=r;r=[];for(const c of i){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const d in c){const f=c[d];f&&typeof f=="object"&&r.push(f)}}}return t}function Gi(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Xs(t)}try{return Xs(t)}finally{Error.stackTraceLimit=r}}var Ii=Symbol.for("vercel.ai.validator");function ip(t){return{[Ii]:!0,validate:t}}function sp(t){return typeof t=="object"&&t!==null&&Ii in t&&t[Ii]===!0&&"validate"in t}function ap(t){return sp(t)?t:typeof t=="function"?t():lp(t)}function lp(t){return ip(async r=>{const i=await t["~standard"].validate(r);return i.issues==null?{success:!0,value:i.value}:{success:!1,error:new Jr({value:r,cause:i.issues})}})}async function cp({value:t,schema:r}){const i=await to({value:t,schema:r});if(!i.success)throw Jr.wrap({value:t,cause:i.error});return i.value}async function to({value:t,schema:r}){const i=ap(r);try{if(i.validate==null)return{success:!0,value:t,rawValue:t};const c=await i.validate(t);return c.success?{success:!0,value:c.value,rawValue:t}:{success:!1,error:Jr.wrap({value:t,cause:c.error}),rawValue:t}}catch(c){return{success:!1,error:Jr.wrap({value:t,cause:c}),rawValue:t}}}async function up({text:t,schema:r}){try{const i=Gi(t);return r==null?i:cp({value:i,schema:r})}catch(i){throw Oo.isInstance(i)||Jr.isInstance(i)?i:new Oo({text:t,cause:i})}}async function Tc({text:t,schema:r}){try{const i=Gi(t);return r==null?{success:!0,value:i,rawValue:i}:await to({value:i,schema:r})}catch(i){return{success:!1,error:Oo.isInstance(i)?i:new Oo({text:t,cause:i}),rawValue:void 0}}}function Ys(t){try{return Gi(t),!0}catch{return!1}}function dp({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ec).pipeThrough(new TransformStream({async transform({data:i},c){i!=="[DONE]"&&c.enqueue(await Tc({text:i,schema:r}))}}))}async function Ks({provider:t,providerOptions:r,schema:i}){if(r?.[t]==null)return;const c=await to({value:r[t],schema:i});if(!c.success)throw new Dl({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var fp=()=>globalThis.fetch,Js=async({url:t,headers:r,body:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>hp({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(i),values:i},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),hp=async({url:t,headers:r={},body:i,successfulResponseHandler:c,failedResponseHandler:d,abortSignal:f,fetch:m=fp()})=>{try{const x=await m(t,{method:"POST",headers:Sc(r,`ai-sdk/provider-utils/${ep}`,Jh()),body:i.content,signal:f}),v=zo(x);if(!x.ok){let g;try{g=await d({response:x,url:t,requestBodyValues:i.values})}catch(E){throw Ei(E)||Vn.isInstance(E)?E:new Vn({message:"Failed to process error response",cause:E,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:i.values})}catch(g){throw g instanceof Error&&(Ei(g)||Vn.isInstance(g))?g:new Vn({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}}catch(x){throw Kh({error:x,url:t,requestBodyValues:i.values})}},pp=({errorSchema:t,errorToMessage:r,isRetryable:i})=>async({response:c,url:d,requestBodyValues:f})=>{const m=await c.text(),x=zo(c);if(m.trim()==="")return{responseHeaders:x,value:new Vn({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})};try{const v=await up({text:m,schema:t});return{responseHeaders:x,value:new Vn({message:r(v),url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:v,isRetryable:i?.(c,v)})}}catch{return{responseHeaders:x,value:new Vn({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})}}},mp=t=>async({response:r})=>{const i=zo(r);if(r.body==null)throw new Md({});return{responseHeaders:i,value:dp({stream:r.body,schema:t})}},gp=t=>async({response:r,url:i,requestBodyValues:c})=>{const d=await r.text(),f=await Tc({text:d,schema:t}),m=zo(r);if(!f.success)throw new Vn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:d,url:i,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:xp}=globalThis;function yp(t){let r="";for(let i=0;i<t.length;i++)r+=String.fromCodePoint(t[i]);return xp(r)}function wp(t){return t instanceof Uint8Array?yp(t):t}function _p(t){return t?.replace(/\/$/,"")}function $r(t){var r,i;return(i=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?i:{}}function vp(t){const r=[];for(const{role:i,content:c,...d}of t){const f=$r({...d});switch(i){case"system":{r.push({role:"system",content:c,...f});break}case"user":{if(c.length===1&&c[0].type==="text"){r.push({role:"user",content:c[0].text,...$r(c[0])});break}r.push({role:"user",content:c.map(m=>{const x=$r(m);switch(m.type){case"text":return{type:"text",text:m.text,...x};case"file":if(m.mediaType.startsWith("image/")){const v=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${v};base64,${wp(m.data)}`},...x}}else throw new Ql({functionality:`file part media type ${m.mediaType}`})}}),...f});break}case"assistant":{let m="";const x=[];for(const v of c){const g=$r(v);switch(v.type){case"text":{m+=v.text;break}case"tool-call":{x.push({id:v.toolCallId,type:"function",function:{name:v.toolName,arguments:JSON.stringify(v.input)},...g});break}}}r.push({role:"assistant",content:m,tool_calls:x.length>0?x:void 0,...f});break}case"tool":{for(const m of c){const x=m.output;let v;switch(x.type){case"text":case"error-text":v=x.value;break;case"content":case"json":case"error-json":v=JSON.stringify(x.value);break}const g=$r(m);r.push({role:"tool",tool_call_id:m.toolCallId,content:v,...g})}break}default:{const m=i;throw new Error(`Unsupported role: ${m}`)}}}return r}function Qs({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i!=null?new Date(i*1e3):void 0}}function ea(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var di=N({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),Cp=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),bp={errorSchema:Cp,errorToMessage:t=>t.error.message};function Ap({tools:t,toolChoice:r}){t=t?.length?t:void 0;const i=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};const c=[];for(const f of t)f.type==="provider-defined"?i.push({type:"unsupported-tool",tool:f}):c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema}});if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:i};const d=r.type;switch(d){case"auto":case"none":case"required":return{tools:c,toolChoice:d,toolWarnings:i};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:i};default:{const f=d;throw new Ql({functionality:`tool choice type: ${f}`})}}}var Ep=class{constructor(t,r){this.specificationVersion="v2";var i,c;this.modelId=t,this.config=r;const d=(i=r.errorStructure)!=null?i:bp;this.chunkSchema=Sp(d.errorSchema),this.failedResponseHandler=pp(d),this.supportsStructuredOutputs=(c=r.supportsStructuredOutputs)!=null?c:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,r,i;return(i=(r=(t=this.config).supportedUrls)==null?void 0:r.call(t))!=null?i:{}}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,providerOptions:x,stopSequences:v,responseFormat:g,seed:E,toolChoice:A,tools:D}){var T,S,P,M;const ee=[],$=Object.assign((T=await Ks({provider:"openai-compatible",providerOptions:x,schema:di}))!=null?T:{},(S=await Ks({provider:this.providerOptionsName,providerOptions:x,schema:di}))!=null?S:{});d!=null&&ee.push({type:"unsupported-setting",setting:"topK"}),g?.type==="json"&&g.schema!=null&&!this.supportsStructuredOutputs&&ee.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:F,toolChoice:re,toolWarnings:Z}=Ap({tools:D,toolChoice:A});return{args:{model:this.modelId,user:$.user,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:g?.type==="json"?this.supportsStructuredOutputs===!0&&g.schema!=null?{type:"json_schema",json_schema:{schema:g.schema,name:(P=g.name)!=null?P:"response",description:g.description}}:{type:"json_object"}:void 0,stop:v,seed:E,...Object.fromEntries(Object.entries((M=x?.[this.providerOptionsName])!=null?M:{}).filter(([B])=>!Object.keys(di.shape).includes(B))),reasoning_effort:$.reasoningEffort,verbosity:$.textVerbosity,messages:vp(t),tools:F,tool_choice:re},warnings:[...ee,...Z]}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,D,T,S,P,M,ee;const{args:$,warnings:F}=await this.getArgs({...t}),re=JSON.stringify($),{responseHeaders:Z,value:B,rawValue:L}=await Js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qs(this.config.headers(),t.headers),body:$,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:gp(Ip),abortSignal:t.abortSignal,fetch:this.config.fetch}),W=B.choices[0],z=[],we=W.message.content;we!=null&&we.length>0&&z.push({type:"text",text:we});const G=(r=W.message.reasoning_content)!=null?r:W.message.reasoning;if(G!=null&&G.length>0&&z.push({type:"reasoning",text:G}),W.message.tool_calls!=null)for(const te of W.message.tool_calls)z.push({type:"tool-call",toolCallId:(i=te.id)!=null?i:bo(),toolName:te.function.name,input:te.function.arguments});const me={[this.providerOptionsName]:{},...await((d=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:d.call(c,{parsedBody:L}))},fe=(f=B.usage)==null?void 0:f.completion_tokens_details;return fe?.accepted_prediction_tokens!=null&&(me[this.providerOptionsName].acceptedPredictionTokens=fe?.accepted_prediction_tokens),fe?.rejected_prediction_tokens!=null&&(me[this.providerOptionsName].rejectedPredictionTokens=fe?.rejected_prediction_tokens),{content:z,finishReason:ea(W.finish_reason),usage:{inputTokens:(x=(m=B.usage)==null?void 0:m.prompt_tokens)!=null?x:void 0,outputTokens:(g=(v=B.usage)==null?void 0:v.completion_tokens)!=null?g:void 0,totalTokens:(A=(E=B.usage)==null?void 0:E.total_tokens)!=null?A:void 0,reasoningTokens:(S=(T=(D=B.usage)==null?void 0:D.completion_tokens_details)==null?void 0:T.reasoning_tokens)!=null?S:void 0,cachedInputTokens:(ee=(M=(P=B.usage)==null?void 0:P.prompt_tokens_details)==null?void 0:M.cached_tokens)!=null?ee:void 0},providerMetadata:me,request:{body:re},response:{...Qs(B),headers:Z,body:L},warnings:F}}async doStream(t){var r;const{args:i,warnings:c}=await this.getArgs({...t}),d={...i,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},f=(r=this.config.metadataExtractor)==null?void 0:r.createStreamExtractor(),{responseHeaders:m,value:x}=await Js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qs(this.config.headers(),t.headers),body:d,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:mp(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=[];let g="unknown";const E={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let A=!0;const D=this.providerOptionsName;let T=!1,S=!1;return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:c})},transform(P,M){var ee,$,F,re,Z,B,L,W,z,we,G,me,fe;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g="error",M.enqueue({type:"error",error:P.error});return}const te=P.value;if(f?.processChunk(P.rawValue),"error"in te){g="error",M.enqueue({type:"error",error:te.error.message});return}if(A&&(A=!1,M.enqueue({type:"response-metadata",...Qs(te)})),te.usage!=null){const{prompt_tokens:Te,completion_tokens:Je,total_tokens:xe,prompt_tokens_details:$e,completion_tokens_details:Ue}=te.usage;E.promptTokens=Te??void 0,E.completionTokens=Je??void 0,E.totalTokens=xe??void 0,Ue?.reasoning_tokens!=null&&(E.completionTokensDetails.reasoningTokens=Ue?.reasoning_tokens),Ue?.accepted_prediction_tokens!=null&&(E.completionTokensDetails.acceptedPredictionTokens=Ue?.accepted_prediction_tokens),Ue?.rejected_prediction_tokens!=null&&(E.completionTokensDetails.rejectedPredictionTokens=Ue?.rejected_prediction_tokens),$e?.cached_tokens!=null&&(E.promptTokensDetails.cachedTokens=$e?.cached_tokens)}const q=te.choices[0];if(q?.finish_reason!=null&&(g=ea(q.finish_reason)),q?.delta==null)return;const ke=q.delta,le=(ee=ke.reasoning_content)!=null?ee:ke.reasoning;if(le&&(T||(M.enqueue({type:"reasoning-start",id:"reasoning-0"}),T=!0),M.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:le})),ke.content&&(S||(M.enqueue({type:"text-start",id:"txt-0"}),S=!0),M.enqueue({type:"text-delta",id:"txt-0",delta:ke.content})),ke.tool_calls!=null)for(const Te of ke.tool_calls){const Je=Te.index;if(v[Je]==null){if(Te.id==null)throw new bs({data:Te,message:"Expected 'id' to be a string."});if((($=Te.function)==null?void 0:$.name)==null)throw new bs({data:Te,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:Te.id,toolName:Te.function.name}),v[Je]={id:Te.id,type:"function",function:{name:Te.function.name,arguments:(F=Te.function.arguments)!=null?F:""},hasFinished:!1};const $e=v[Je];((re=$e.function)==null?void 0:re.name)!=null&&((Z=$e.function)==null?void 0:Z.arguments)!=null&&($e.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:$e.id,delta:$e.function.arguments}),Ys($e.function.arguments)&&(M.enqueue({type:"tool-input-end",id:$e.id}),M.enqueue({type:"tool-call",toolCallId:(B=$e.id)!=null?B:bo(),toolName:$e.function.name,input:$e.function.arguments}),$e.hasFinished=!0));continue}const xe=v[Je];xe.hasFinished||(((L=Te.function)==null?void 0:L.arguments)!=null&&(xe.function.arguments+=(z=(W=Te.function)==null?void 0:W.arguments)!=null?z:""),M.enqueue({type:"tool-input-delta",id:xe.id,delta:(we=Te.function.arguments)!=null?we:""}),((G=xe.function)==null?void 0:G.name)!=null&&((me=xe.function)==null?void 0:me.arguments)!=null&&Ys(xe.function.arguments)&&(M.enqueue({type:"tool-input-end",id:xe.id}),M.enqueue({type:"tool-call",toolCallId:(fe=xe.id)!=null?fe:bo(),toolName:xe.function.name,input:xe.function.arguments}),xe.hasFinished=!0))}},flush(P){var M,ee,$,F,re,Z;T&&P.enqueue({type:"reasoning-end",id:"reasoning-0"}),S&&P.enqueue({type:"text-end",id:"txt-0"});for(const L of v.filter(W=>!W.hasFinished))P.enqueue({type:"tool-input-end",id:L.id}),P.enqueue({type:"tool-call",toolCallId:(M=L.id)!=null?M:bo(),toolName:L.function.name,input:L.function.arguments});const B={[D]:{},...f?.buildMetadata()};E.completionTokensDetails.acceptedPredictionTokens!=null&&(B[D].acceptedPredictionTokens=E.completionTokensDetails.acceptedPredictionTokens),E.completionTokensDetails.rejectedPredictionTokens!=null&&(B[D].rejectedPredictionTokens=E.completionTokensDetails.rejectedPredictionTokens),P.enqueue({type:"finish",finishReason:g,usage:{inputTokens:(ee=E.promptTokens)!=null?ee:void 0,outputTokens:($=E.completionTokens)!=null?$:void 0,totalTokens:(F=E.totalTokens)!=null?F:void 0,reasoningTokens:(re=E.completionTokensDetails.reasoningTokens)!=null?re:void 0,cachedInputTokens:(Z=E.promptTokensDetails.cachedTokens)!=null?Z:void 0},providerMetadata:B})}})),request:{body:d},response:{headers:m}}}},Nc=N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),Ip=N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({message:N({role:Y("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(N({id:w().nullish(),function:N({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:Nc}),Sp=t=>st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({delta:N({role:Ae(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(N({index:j(),id:w().nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:Nc}),t]);N({echo:Mt().optional(),logitBias:wt(w(),j()).optional(),suffix:w().optional(),user:w().optional()});var Tp=N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w()})),usage:Tp.nullish()});N({dimensions:j().optional(),user:w().optional()});N({data:ue(N({embedding:ue(j())})),usage:N({prompt_tokens:j()}).nullish(),providerMetadata:wt(w(),wt(w(),xr())).optional()});N({data:ue(N({b64_json:w()}))});var ta=t=>{var r,i;return t==null?void 0:{deepseek:{promptCacheHitTokens:(r=t.prompt_cache_hit_tokens)!=null?r:NaN,promptCacheMissTokens:(i=t.prompt_cache_miss_tokens)!=null?i:NaN}}},Np={extractMetadata:async({parsedBody:t})=>{const r=await to({value:t,schema:Op});return!r.success||r.value.usage==null?void 0:ta(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var i,c;const d=await to({value:r,schema:kp});d.success&&((c=(i=d.value.choices)==null?void 0:i[0])==null?void 0:c.finish_reason)==="stop"&&d.value.usage&&(t=d.value.usage)},buildMetadata:()=>ta(t)}}},Oc=N({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),Op=N({usage:Oc.nullish()}),kp=N({choices:ue(N({finish_reason:w().nullish()})).nullish(),usage:Oc.nullish()}),Rp="1.0.30";function kc(t={}){var r;const i=_p((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>Sc({Authorization:`Bearer ${tp({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${Rp}`);class d extends Ep{addJsonInstruction(v){var g;if(((g=v.responseFormat)==null?void 0:g.type)!=="json")return v;const D=[...Array.isArray(v.prompt)?v.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...v,prompt:D}}async doGenerate(v){return super.doGenerate(this.addJsonInstruction(v))}async doStream(v){return super.doStream(this.addJsonInstruction(v))}}const f=x=>new d(x,{provider:"deepseek.chat",url:({path:v})=>`${i}${v}`,headers:c,fetch:t.fetch,metadataExtractor:Np}),m=x=>f(x);return m.languageModel=f,m.chat=f,m.textEmbeddingModel=x=>{throw new As({modelId:x,modelType:"textEmbeddingModel"})},m.imageModel=x=>{throw new As({modelId:x,modelType:"imageModel"})},m}kc();var Rc="vercel.ai.error",Mp=Symbol.for(Rc),na,ra,kt=class Mc extends(ra=Error,na=Mp,ra){constructor({name:r,message:i,cause:c}){super(i),this[na]=!0,this.name=r,this.cause=c}static isInstance(r){return Mc.hasMarker(r,Rc)}static hasMarker(r,i){const c=Symbol.for(i);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}},Dc="AI_APICallError",Pc=`vercel.ai.error.${Dc}`,Dp=Symbol.for(Pc),oa,ia,Kt=class extends(ia=kt,oa=Dp,ia){constructor({message:t,url:r,requestBodyValues:i,statusCode:c,responseHeaders:d,responseBody:f,cause:m,isRetryable:x=c!=null&&(c===408||c===409||c===429||c>=500),data:v}){super({name:Dc,message:t,cause:m}),this[oa]=!0,this.url=r,this.requestBodyValues=i,this.statusCode=c,this.responseHeaders=d,this.responseBody=f,this.isRetryable=x,this.data=v}static isInstance(t){return kt.hasMarker(t,Pc)}},Bc="AI_EmptyResponseBodyError",Lc=`vercel.ai.error.${Bc}`,Pp=Symbol.for(Lc),sa,aa,Bp=class extends(aa=kt,sa=Pp,aa){constructor({message:t="Empty response body"}={}){super({name:Bc,message:t}),this[sa]=!0}static isInstance(t){return kt.hasMarker(t,Lc)}};function Fc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Uc="AI_InvalidArgumentError",zc=`vercel.ai.error.${Uc}`,Lp=Symbol.for(zc),la,ca,Vc=class extends(ca=kt,la=Lp,ca){constructor({message:t,cause:r,argument:i}){super({name:Uc,message:t,cause:r}),this[la]=!0,this.argument=i}static isInstance(t){return kt.hasMarker(t,zc)}},Zc="AI_InvalidPromptError",$c=`vercel.ai.error.${Zc}`,Fp=Symbol.for($c),ua,da,Up=class extends(da=kt,ua=Fp,da){constructor({prompt:t,message:r,cause:i}){super({name:Zc,message:`Invalid prompt: ${r}`,cause:i}),this[ua]=!0,this.prompt=t}static isInstance(t){return kt.hasMarker(t,$c)}},jc="AI_InvalidResponseDataError",Hc=`vercel.ai.error.${jc}`,zp=Symbol.for(Hc),fa,ha,fi=class extends(ha=kt,fa=zp,ha){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:jc,message:r}),this[fa]=!0,this.data=t}static isInstance(t){return kt.hasMarker(t,Hc)}},Wc="AI_JSONParseError",Gc=`vercel.ai.error.${Wc}`,Vp=Symbol.for(Gc),pa,ma,Do=class extends(ma=kt,pa=Vp,ma){constructor({text:t,cause:r}){super({name:Wc,message:`JSON parsing failed: Text: ${t}.
40
+ Error message: ${Fc(r)}`,cause:r}),this[pa]=!0,this.text=t}static isInstance(t){return kt.hasMarker(t,Gc)}},qc="AI_LoadAPIKeyError",Xc=`vercel.ai.error.${qc}`,Zp=Symbol.for(Xc),ga,xa,Ao=class extends(xa=kt,ga=Zp,xa){constructor({message:t}){super({name:qc,message:t}),this[ga]=!0}static isInstance(t){return kt.hasMarker(t,Xc)}},Yc="AI_TooManyEmbeddingValuesForCallError",Kc=`vercel.ai.error.${Yc}`,$p=Symbol.for(Kc),ya,wa,jp=class extends(wa=kt,ya=$p,wa){constructor(t){super({name:Yc,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[ya]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return kt.hasMarker(t,Kc)}},Jc="AI_TypeValidationError",Qc=`vercel.ai.error.${Jc}`,Hp=Symbol.for(Qc),_a,va,no=class Si extends(va=kt,_a=Hp,va){constructor({value:r,cause:i,context:c}){let d="Type validation failed";if(c?.field&&(d+=` for ${c.field}`),c?.entityName||c?.entityId){d+=" (";const f=[];c.entityName&&f.push(c.entityName),c.entityId&&f.push(`id: "${c.entityId}"`),d+=f.join(", "),d+=")"}super({name:Jc,message:`${d}: Value: ${JSON.stringify(r)}.
41
+ Error message: ${Fc(i)}`,cause:i}),this[_a]=!0,this.value=r,this.context=c}static isInstance(r){return kt.hasMarker(r,Qc)}static wrap({value:r,cause:i,context:c}){var d,f,m;return Si.isInstance(i)&&i.value===r&&((d=i.context)==null?void 0:d.field)===c?.field&&((f=i.context)==null?void 0:f.entityName)===c?.entityName&&((m=i.context)==null?void 0:m.entityId)===c?.entityId?i:new Si({value:r,cause:i,context:c})}},eu="AI_UnsupportedFunctionalityError",tu=`vercel.ai.error.${eu}`,Wp=Symbol.for(tu),Ca,ba,Mn=class extends(ba=kt,Ca=Wp,ba){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:eu,message:r}),this[Ca]=!0,this.functionality=t}static isInstance(t){return kt.hasMarker(t,tu)}};function bn(...t){return t.reduce((r,i)=>({...r,...i??{}}),{})}function Gp({tools:t=[],providerToolNames:r,resolveProviderToolName:i}){var c;const d={},f={};for(const m of t)if(m.type==="provider"){const x=(c=i?.(m))!=null?c:m.id in r?r[m.id]:void 0;if(x==null)continue;d[m.name]=x,f[x]=m.name}return{toProviderToolName:m=>{var x;return(x=d[m])!=null?x:m},toCustomToolName:m=>{var x;return(x=f[m])!=null?x:m}}}var qp=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,r)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&r(this.status.error),this._resolve=t,this._reject=r}),this._promise)}resolve(t){var r;this.status={type:"resolved",value:t},this._promise&&((r=this._resolve)==null||r.call(this,t))}reject(t){var r;this.status={type:"rejected",error:t},this._promise&&((r=this._reject)==null||r.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function ao(t){return Object.fromEntries([...t.headers])}var{btoa:Xp,atob:Yp}=globalThis;function qi(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),i=Yp(r);return Uint8Array.from(i,c=>c.codePointAt(0))}function Kp(t){let r="";for(let i=0;i<t.length;i++)r+=String.fromCodePoint(t[i]);return Xp(r)}function kr(t){return t instanceof Uint8Array?Kp(t):t}function Jp(t,r={}){const{useArrayBrackets:i=!0}=r,c=new FormData;for(const[d,f]of Object.entries(t))if(f!=null){if(Array.isArray(f)){if(f.length===1){c.append(d,f[0]);continue}const m=i?`${d}[]`:d;for(const x of f)c.append(m,x);continue}c.append(d,f)}return c}async function Xi(t){var r;try{await((r=t.body)==null?void 0:r.cancel())}catch{}}var nu="AI_DownloadError",ru=`vercel.ai.error.${nu}`,Qp=Symbol.for(ru),Aa,Ea,cn=class extends(Ea=kt,Aa=Qp,Ea){constructor({url:t,statusCode:r,statusText:i,cause:c,message:d=c==null?`Failed to download ${t}: ${r} ${i}`:`Failed to download ${t}: ${c}`}){super({name:nu,message:d,cause:c}),this[Aa]=!0,this.url=t,this.statusCode=r,this.statusText=i}static isInstance(t){return kt.hasMarker(t,ru)}};function em(t=globalThis){return t.window!=null}function tm(t){let r;try{r=new URL(t)}catch{throw new cn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol==="data:")return;if(r.protocol!=="http:"&&r.protocol!=="https:")throw new cn({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});const i=r.hostname.toLowerCase().replace(/\.+$/,"");if(!i)throw new cn({url:t,message:"URL must have a hostname"});if(i==="localhost"||i.endsWith(".local")||i.endsWith(".localhost"))throw new cn({url:t,message:`URL with hostname ${i} is not allowed`});if(i.startsWith("[")&&i.endsWith("]")){const c=i.slice(1,-1);if(rm(c))throw new cn({url:t,message:`URL with IPv6 address ${i} is not allowed`});return}if(ou(i)){if(iu(i))throw new cn({url:t,message:`URL with IP address ${i} is not allowed`});return}}function ou(t){const r=t.split(".");return r.length!==4?!1:r.every(i=>{const c=Number(i);return Number.isInteger(c)&&c>=0&&c<=255&&String(c)===i})}function iu(t){const r=t.split(".").map(Number),[i,c,d]=r;return i===0||i===10||i===100&&c>=64&&c<=127||i===127||i===169&&c===254||i===172&&c>=16&&c<=31||i===192&&c===0&&d===0||i===192&&c===168||i===198&&(c===18||c===19)||i>=240}function nm(t){let r=t.toLowerCase();const i=r.indexOf("%");i!==-1&&(r=r.slice(0,i));const c=r.split("::");if(c.length>2)return null;const d=m=>{if(m==="")return[];const x=[],v=m.split(":");for(let g=0;g<v.length;g++){const E=v[g];if(E.includes(".")){if(g!==v.length-1||!ou(E))return null;const[A,D,T,S]=E.split(".").map(Number);x.push(A<<8|D,T<<8|S);continue}if(!/^[0-9a-f]{1,4}$/.test(E))return null;x.push(parseInt(E,16))}return x},f=d(c[0]);if(f===null)return null;if(c.length===2){const m=d(c[1]);if(m===null)return null;const x=8-f.length-m.length;return x<0?null:[...f,...new Array(x).fill(0),...m]}return f.length===8?f:null}function rm(t){const r=nm(t);if(r===null)return!0;const i=d=>r.slice(0,d).every(f=>f===0);if(i(7)&&(r[7]===0||r[7]===1)||(r[0]&65024)===64512||(r[0]&65472)===65152||(r[0]&65472)===65216||(r[0]&65280)===65280)return!0;if(i(6)||i(5)&&r[5]===65535||i(4)&&r[4]===65535&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===0&&r[3]===0&&r[4]===0&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===1){const d=r[6]>>8&255,f=r[6]&255,m=r[7]>>8&255,x=r[7]&255;return iu(`${d}.${f}.${m}.${x}`)}return!1}var om=10;async function im({url:t,headers:r,abortSignal:i,maxRedirects:c=om}){const d={signal:i};r!==void 0&&(d.headers=r);let f=t;for(let m=0;m<=c;m++){tm(f);const x=await fetch(f,{...d,redirect:"manual"});if(x.type==="opaqueredirect"){if(!em())throw new cn({url:t,message:`Redirect from ${f} could not be validated and was blocked`});return await fetch(f,{...d,redirect:"follow"})}const v=x.headers.get("location");if(x.status>=300&&x.status<400&&v){await Xi(x),f=new URL(v,f).toString();continue}return x}throw new cn({url:t,message:`Too many redirects (max ${c})`})}var su=2*1024*1024*1024;async function au({response:t,url:r,maxBytes:i=su}){const c=t.headers.get("content-length");if(c!=null){const E=parseInt(c,10);if(!isNaN(E)&&E>i)throw await Xi(t),new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes (Content-Length: ${E}).`})}const d=t.body;if(d==null)return new Uint8Array(0);const f=d.getReader(),m=[];let x=0;try{for(;;){const{done:E,value:A}=await f.read();if(E)break;if(x+=A.length,x>i)throw new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes.`});m.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const v=new Uint8Array(x);let g=0;for(const E of m)v.set(E,g),g+=E.length;return v}async function lu(t,r){var i,c;try{const d=await im({url:t,abortSignal:r?.abortSignal});if(!d.ok)throw await Xi(d),new cn({url:t,statusCode:d.status,statusText:d.statusText});const f=await au({response:d,url:t,maxBytes:(i=r?.maxBytes)!=null?i:su}),m=(c=d.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(d){throw cn.isInstance(d)?d:new cn({url:t,cause:d})}}var sm=({prefix:t,size:r=16,alphabet:i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const d=()=>{const f=i.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=i[Math.random()*f|0];return m.join("")};if(t==null)return d;if(i.includes(c))throw new Vc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${i}".`});return()=>`${t}${c}${d()}`},rn=sm();function Ti(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var am=["fetch failed","failed to fetch"],lm=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function cm(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&lm.includes(r))}function um({error:t,url:r,requestBodyValues:i}){if(Ti(t))return t;if(t instanceof TypeError&&am.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Kt({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return cm(t)?new Kt({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:i,isRetryable:!0}):t}function dm(t=globalThis){var r,i,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(i=t.process)==null?void 0:i.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fm(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((i,c)=>{r[c.toLowerCase()]=i});else{Array.isArray(t)||(t=Object.entries(t));for(const[i,c]of t)c!=null&&(r[i.toLowerCase()]=c)}return r}function cu(t,...r){const i=new Headers(fm(t)),c=i.get("user-agent")||"";return i.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(i.entries())}var hm="4.0.38";function Ia(t){return t!=null}function pm({apiKey:t,environmentVariableName:r,apiKeyParameterName:i="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new Ao({message:`${c} API key must be a string.`});if(typeof process>"u")throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter. Environment variables are not supported in this environment.`});if(t=process.env[r],t==null)throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new Ao({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function mm({settingValue:t,environmentVariableName:r}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[r],!(t==null||typeof t!="string")))return t}function gm(t){var r;const[i,c=""]=t.toLowerCase().split("/");return(r={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[c])!=null?r:c}var xm=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,ym=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Sa(t){const r=JSON.parse(t);return r===null||typeof r!="object"||xm.test(t)===!1&&ym.test(t)===!1?r:wm(r)}function wm(t){let r=[t];for(;r.length;){const i=r;r=[];for(const c of i){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&c.constructor!==null&&typeof c.constructor=="object"&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const d in c){const f=c[d];f&&typeof f=="object"&&r.push(f)}}}return t}function uu(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Sa(t)}try{return Sa(t)}finally{Error.stackTraceLimit=r}}function Yi(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:i}=t;if(i!=null)for(const c of Object.keys(i))i[c]=dr(i[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(dr):dr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(dr)),t.allOf!=null&&(t.allOf=t.allOf.map(dr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(dr));const{definitions:r}=t;if(r!=null)for(const i of Object.keys(r))r[i]=dr(r[i]);return t}function dr(t){return typeof t=="boolean"?t:Yi(t)}var _m=Symbol("Let zodToJsonSchema decide on which parser to use"),Ta={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},vm=t=>typeof t=="string"?{...Ta,name:t}:{...Ta,...t};function fn(){return{}}function Cm(t,r){var i,c,d;const f={type:"array"};return(i=t.type)!=null&&i._def&&((d=(c=t.type)==null?void 0:c._def)==null?void 0:d.typeName)!==je.ZodAny&&(f.items=ct(t.type._def,{...r,currentPath:[...r.currentPath,"items"]})),t.minLength&&(f.minItems=t.minLength.value),t.maxLength&&(f.maxItems=t.maxLength.value),t.exactLength&&(f.minItems=t.exactLength.value,f.maxItems=t.exactLength.value),f}function bm(t){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function Am(){return{type:"boolean"}}function du(t,r){return ct(t.type._def,r)}var Em=(t,r)=>ct(t.innerType._def,r);function fu(t,r,i){const c=i??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((d,f)=>fu(t,r,d))};switch(c){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Im(t)}}var Im=t=>{const r={type:"integer",format:"unix-time"};for(const i of t.checks)switch(i.kind){case"min":r.minimum=i.value;break;case"max":r.maximum=i.value;break}return r};function Sm(t,r){return{...ct(t.innerType._def,r),default:t.defaultValue()}}function Tm(t,r){return r.effectStrategy==="input"?ct(t.schema._def,r):fn()}function Nm(t){return{type:"string",enum:Array.from(t.values)}}var Om=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function km(t,r){const i=[ct(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),ct(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(d=>!!d),c=[];return i.forEach(d=>{if(Om(d))c.push(...d.allOf);else{let f=d;if("additionalProperties"in d&&d.additionalProperties===!1){const{additionalProperties:m,...x}=d;f=x}c.push(f)}}),c.length?{allOf:c}:void 0}function Rm(t){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:r==="bigint"?"integer":r,const:t.value}}var hi=void 0,wn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(hi===void 0&&(hi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hi),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function hu(t,r){const i={type:"string"};if(t.checks)for(const c of t.checks)switch(c.kind){case"min":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value;break;case"max":i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"email":switch(r.emailStrategy){case"format:email":_n(i,"email",c.message,r);break;case"format:idn-email":_n(i,"idn-email",c.message,r);break;case"pattern:zod":Yt(i,wn.email,c.message,r);break}break;case"url":_n(i,"uri",c.message,r);break;case"uuid":_n(i,"uuid",c.message,r);break;case"regex":Yt(i,c.regex,c.message,r);break;case"cuid":Yt(i,wn.cuid,c.message,r);break;case"cuid2":Yt(i,wn.cuid2,c.message,r);break;case"startsWith":Yt(i,RegExp(`^${pi(c.value,r)}`),c.message,r);break;case"endsWith":Yt(i,RegExp(`${pi(c.value,r)}$`),c.message,r);break;case"datetime":_n(i,"date-time",c.message,r);break;case"date":_n(i,"date",c.message,r);break;case"time":_n(i,"time",c.message,r);break;case"duration":_n(i,"duration",c.message,r);break;case"length":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value,i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"includes":{Yt(i,RegExp(pi(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&_n(i,"ipv4",c.message,r),c.version!=="v4"&&_n(i,"ipv6",c.message,r);break}case"base64url":Yt(i,wn.base64url,c.message,r);break;case"jwt":Yt(i,wn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Yt(i,wn.ipv4Cidr,c.message,r),c.version!=="v4"&&Yt(i,wn.ipv6Cidr,c.message,r);break}case"emoji":Yt(i,wn.emoji(),c.message,r);break;case"ulid":{Yt(i,wn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{_n(i,"binary",c.message,r);break}case"contentEncoding:base64":{i.contentEncoding="base64";break}case"pattern:zod":{Yt(i,wn.base64,c.message,r);break}}break}case"nanoid":Yt(i,wn.nanoid,c.message,r)}return i}function pi(t,r){return r.patternStrategy==="escape"?Dm(t):t}var Mm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Dm(t){let r="";for(let i=0;i<t.length;i++)Mm.has(t[i])||(r+="\\"),r+=t[i];return r}function _n(t,r,i,c){var d;t.format||(d=t.anyOf)!=null&&d.some(f=>f.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...i&&c.errorMessages&&{errorMessage:{format:i}}})):t.format=r}function Yt(t,r,i,c){var d;t.pattern||(d=t.allOf)!=null&&d.some(f=>f.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Na(r,c),...i&&c.errorMessages&&{errorMessage:{pattern:i}}})):t.pattern=Na(r,c)}function Na(t,r){var i;if(!r.applyRegexFlags||!t.flags)return t.source;const c={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},d=c.i?t.source.toLowerCase():t.source;let f="",m=!1,x=!1,v=!1;for(let g=0;g<d.length;g++){if(m){f+=d[g],m=!1;continue}if(c.i){if(x){if(d[g].match(/[a-z]/)){v?(f+=d[g],f+=`${d[g-2]}-${d[g]}`.toUpperCase(),v=!1):d[g+1]==="-"&&((i=d[g+2])!=null&&i.match(/[a-z]/))?(f+=d[g],v=!0):f+=`${d[g]}${d[g].toUpperCase()}`;continue}}else if(d[g].match(/[a-z]/)){f+=`[${d[g]}${d[g].toUpperCase()}]`;continue}}if(c.m){if(d[g]==="^"){f+=`(^|(?<=[\r
42
+ ]))`;continue}else if(d[g]==="$"){f+=`($|(?=[\r
43
+ ]))`;continue}}if(c.s&&d[g]==="."){f+=x?`${d[g]}\r
44
+ `:`[${d[g]}\r
45
+ ]`;continue}f+=d[g],d[g]==="\\"?m=!0:x&&d[g]==="]"?x=!1:!x&&d[g]==="["&&(x=!0)}try{new RegExp(f)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return f}function pu(t,r){var i,c,d,f,m,x;const v={type:"object",additionalProperties:(i=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?i:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===je.ZodString&&((d=t.keyType._def.checks)!=null&&d.length)){const{type:g,...E}=hu(t.keyType._def,r);return{...v,propertyNames:E}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===je.ZodEnum)return{...v,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===je.ZodBranded&&t.keyType._def.type._def.typeName===je.ZodString&&((x=t.keyType._def.type._def.checks)!=null&&x.length)){const{type:g,...E}=du(t.keyType._def,r);return{...v,propertyNames:E}}}return v}function Pm(t,r){if(r.mapStrategy==="record")return pu(t,r);const i=ct(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fn(),c=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fn();return{type:"array",maxItems:125,items:{type:"array",items:[i,c],minItems:2,maxItems:2}}}function Bm(t){const r=t.values,c=Object.keys(t.values).filter(f=>typeof r[r[f]]!="number").map(f=>r[f]),d=Array.from(new Set(c.map(f=>typeof f)));return{type:d.length===1?d[0]==="string"?"string":"number":["string","number"],enum:c}}function Lm(){return{not:fn()}}function Fm(){return{type:"null"}}var Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Um(t,r){const i=t.options instanceof Map?Array.from(t.options.values()):t.options;if(i.every(c=>c._def.typeName in Ni&&(!c._def.checks||!c._def.checks.length))){const c=i.reduce((d,f)=>{const m=Ni[f._def.typeName];return m&&!d.includes(m)?[...d,m]:d},[]);return{type:c.length>1?c:c[0]}}else if(i.every(c=>c._def.typeName==="ZodLiteral"&&!c.description)){const c=i.reduce((d,f)=>{const m=typeof f._def.value;switch(m){case"string":case"number":case"boolean":return[...d,m];case"bigint":return[...d,"integer"];case"object":if(f._def.value===null)return[...d,"null"];case"symbol":case"undefined":case"function":default:return d}},[]);if(c.length===i.length){const d=c.filter((f,m,x)=>x.indexOf(f)===m);return{type:d.length>1?d:d[0],enum:i.reduce((f,m)=>f.includes(m._def.value)?f:[...f,m._def.value],[])}}}else if(i.every(c=>c._def.typeName==="ZodEnum"))return{type:"string",enum:i.reduce((c,d)=>[...c,...d._def.values.filter(f=>!c.includes(f))],[])};return zm(t,r)}var zm=(t,r)=>{const i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,d)=>ct(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${d}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return i.length?{anyOf:i}:void 0};function Vm(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ni[t.innerType._def.typeName],"null"]};const i=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return i&&{anyOf:[i,{type:"null"}]}}function Zm(t){const r={type:"number"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"int":r.type="integer";break;case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function $m(t,r){const i={type:"object",properties:{}},c=[],d=t.shape();for(const m in d){let x=d[m];if(x===void 0||x._def===void 0)continue;const v=Hm(x),g=ct(x._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});g!==void 0&&(i.properties[m]=g,v||c.push(m))}c.length&&(i.required=c);const f=jm(t,r);return f!==void 0&&(i.additionalProperties=f),i}function jm(t,r){if(t.catchall._def.typeName!=="ZodNever")return ct(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return r.removeAdditionalStrategy==="strict"?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}function Hm(t){try{return t.isOptional()}catch{return!0}}var Wm=(t,r)=>{var i;if(r.currentPath.toString()===((i=r.propertyPath)==null?void 0:i.toString()))return ct(t.innerType._def,r);const c=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:fn()},c]}:fn()},Gm=(t,r)=>{if(r.pipeStrategy==="input")return ct(t.in._def,r);if(r.pipeStrategy==="output")return ct(t.out._def,r);const i=ct(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=ct(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",i?"1":"0"]});return{allOf:[i,c].filter(d=>d!==void 0)}};function qm(t,r){return ct(t.type._def,r)}function Xm(t,r){const c={type:"array",uniqueItems:!0,items:ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return t.minSize&&(c.minItems=t.minSize.value),t.maxSize&&(c.maxItems=t.maxSize.value),c}function Ym(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[]),additionalItems:ct(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[])}}function Km(){return{not:fn()}}function Jm(){return fn()}var Qm=(t,r)=>ct(t.innerType._def,r),eg=(t,r,i)=>{switch(r){case je.ZodString:return hu(t,i);case je.ZodNumber:return Zm(t);case je.ZodObject:return $m(t,i);case je.ZodBigInt:return bm(t);case je.ZodBoolean:return Am();case je.ZodDate:return fu(t,i);case je.ZodUndefined:return Km();case je.ZodNull:return Fm();case je.ZodArray:return Cm(t,i);case je.ZodUnion:case je.ZodDiscriminatedUnion:return Um(t,i);case je.ZodIntersection:return km(t,i);case je.ZodTuple:return Ym(t,i);case je.ZodRecord:return pu(t,i);case je.ZodLiteral:return Rm(t);case je.ZodEnum:return Nm(t);case je.ZodNativeEnum:return Bm(t);case je.ZodNullable:return Vm(t,i);case je.ZodOptional:return Wm(t,i);case je.ZodMap:return Pm(t,i);case je.ZodSet:return Xm(t,i);case je.ZodLazy:return()=>t.getter()._def;case je.ZodPromise:return qm(t,i);case je.ZodNaN:case je.ZodNever:return Lm();case je.ZodEffects:return Tm(t,i);case je.ZodAny:return fn();case je.ZodUnknown:return Jm();case je.ZodDefault:return Sm(t,i);case je.ZodBranded:return du(t,i);case je.ZodReadonly:return Qm(t,i);case je.ZodCatch:return Em(t,i);case je.ZodPipeline:return Gm(t,i);case je.ZodFunction:case je.ZodVoid:case je.ZodSymbol:return;default:return(c=>{})()}},tg=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function ct(t,r,i=!1){var c;const d=r.seen.get(t);if(r.override){const v=(c=r.override)==null?void 0:c.call(r,t,r,d,i);if(v!==_m)return v}if(d&&!i){const v=ng(d,r);if(v!==void 0)return v}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=eg(t,t.typeName,r),x=typeof m=="function"?ct(m(),r):m;if(x&&rg(t,r,x),r.postProcess){const v=r.postProcess(x,t,r);return f.jsonSchema=x,v}return f.jsonSchema=x,x}var ng=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:tg(r.currentPath,t.path)};case"none":case"seen":return t.path.length<r.currentPath.length&&t.path.every((i,c)=>r.currentPath[c]===i)?(console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),fn()):r.$refStrategy==="seen"?fn():void 0}},rg=(t,r,i)=>(t.description&&(i.description=t.description),i),og=t=>{const r=vm(t),i=r.name!==void 0?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,currentPath:i,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([c,d])=>[d._def,{def:d._def,path:[...r.basePath,r.definitionPath,c],jsonSchema:void 0}]))}},ig=(t,r)=>{var i;const c=og(r);let d=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((g,[E,A])=>{var D;return{...g,[E]:(D=ct(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,E]},!0))!=null?D:fn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(i=ct(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?i:fn(),x=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;x!==void 0&&(m.title=x);const v=f===void 0?d?{...m,[c.definitionPath]:d}:m:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...d,[f]:m}};return v.$schema="http://json-schema.org/draft-07/schema#",v},Oi=Symbol.for("vercel.ai.schema");function Fe(t){let r;return()=>(r==null&&(r=t()),r)}function Vo(t,{validate:r}={}){return{[Oi]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function sg(t){return typeof t=="object"&&t!==null&&Oi in t&&t[Oi]===!0&&"jsonSchema"in t&&"validate"in t}function ag(t){return t==null?Vo({type:"object",properties:{},additionalProperties:!1}):sg(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Le(t):lg(t):t()}function lg(t){return Vo(()=>Yi(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async r=>{const i=await t["~standard"].validate(r);return"value"in i?{success:!0,value:i.value}:{success:!1,error:new no({value:r,cause:i.issues})}}})}function cg(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>ig(t,{$refStrategy:c?"root":"none"}),{validate:async d=>{const f=await t.safeParseAsync(d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function ug(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>Yi(Uf(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async d=>{const f=await vc(t,d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function dg(t){return"_zod"in t}function Le(t,r){return dg(t)?ug(t):cg(t)}async function Dt({value:t,schema:r,context:i}){const c=await Ki({value:t,schema:r,context:i});if(!c.success)throw no.wrap({value:t,cause:c.error,context:i});return c.value}async function Ki({value:t,schema:r,context:i}){const c=ag(r);try{if(c.validate==null)return{success:!0,value:t,rawValue:t};const d=await c.validate(t);return d.success?{success:!0,value:d.value,rawValue:t}:{success:!1,error:no.wrap({value:t,cause:d.error,context:i}),rawValue:t}}catch(d){return{success:!1,error:no.wrap({value:t,cause:d,context:i}),rawValue:t}}}async function mu({text:t,schema:r}){try{const i=uu(t);return r==null?i:Dt({value:i,schema:r})}catch(i){throw Do.isInstance(i)||no.isInstance(i)?i:new Do({text:t,cause:i})}}async function gu({text:t,schema:r}){try{const i=uu(t);return r==null?{success:!0,value:i,rawValue:i}:await Ki({value:i,schema:r})}catch(i){return{success:!1,error:Do.isInstance(i)?i:new Do({text:t,cause:i}),rawValue:void 0}}}function fg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ec).pipeThrough(new TransformStream({async transform({data:i},c){i!=="[DONE]"&&c.enqueue(await gu({text:i,schema:r}))}}))}async function An({provider:t,providerOptions:r,schema:i}){if(r?.[t]==null)return;const c=await Ki({value:r[t],schema:i});if(!c.success)throw new Vc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var hg=()=>globalThis.fetch,Zn=async({url:t,headers:r,body:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(i),values:i},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),xu=async({url:t,headers:r,formData:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:r,body:{content:i,values:Object.fromEntries(i.entries())},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),yu=async({url:t,headers:r={},body:i,successfulResponseHandler:c,failedResponseHandler:d,abortSignal:f,fetch:m=hg()})=>{try{const x=await m(t,{method:"POST",headers:cu(r,`ai-sdk/provider-utils/${hm}`,dm()),body:i.content,signal:f}),v=ao(x);if(!x.ok){let g;try{g=await d({response:x,url:t,requestBodyValues:i.values})}catch(E){throw Ti(E)||Kt.isInstance(E)?E:new Kt({message:"Failed to process error response",cause:E,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:i.values})}catch(g){throw g instanceof Error&&(Ti(g)||Kt.isInstance(g))?g:new Kt({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}}catch(x){throw um({error:x,url:t,requestBodyValues:i.values})}};function pg({id:t,inputSchema:r}){return({execute:i,outputSchema:c,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v,...g})=>({type:"provider",id:t,args:g,inputSchema:r,outputSchema:c,execute:i,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v})}function Dn({id:t,inputSchema:r,outputSchema:i,supportsDeferredResults:c}){return({execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,...E})=>({type:"provider",id:t,args:E,inputSchema:r,outputSchema:i,execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,supportsDeferredResults:c})}var mg=new TextDecoder;async function wu({response:t,url:r}){return mg.decode(await au({response:t,url:r}))}var gg=({errorSchema:t,errorToMessage:r,isRetryable:i})=>async({response:c,url:d,requestBodyValues:f})=>{const m=await wu({response:c,url:d}),x=ao(c);if(m.trim()==="")return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})};try{const v=await mu({text:m,schema:t});return{responseHeaders:x,value:new Kt({message:r(v),url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:v,isRetryable:i?.(c,v)})}}catch{return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})}}},Ji=t=>async({response:r})=>{const i=ao(r);if(r.body==null)throw new Bp({});return{responseHeaders:i,value:fg({stream:r.body,schema:t})}},mr=t=>async({response:r,url:i,requestBodyValues:c})=>{const d=await wu({response:r,url:i}),f=await gu({text:d,schema:t}),m=ao(r);if(!f.success)throw new Kt({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:d,url:i,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}},xg=()=>async({response:t,url:r,requestBodyValues:i})=>{const c=ao(t);if(!t.body)throw new Kt({message:"Response body is empty",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0});try{const d=await t.arrayBuffer();return{responseHeaders:c,value:new Uint8Array(d)}}catch(d){throw new Kt({message:"Failed to read response as array buffer",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:d})}};function yg(t){return t?.replace(/\/$/,"")}var Qi=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),En=gg({errorSchema:Qi,errorToMessage:t=>t.error.message});function _u(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),i=t.startsWith("gpt-4")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")&&!t.startsWith("gpt-5.4-nano")||t.startsWith("o3")||t.startsWith("o4-mini"),c=t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),d=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2")||t.startsWith("gpt-5.3")||t.startsWith("gpt-5.4")||t.startsWith("gpt-5.5")||t.startsWith("gpt-5.6");return{supportsFlexProcessing:r,supportsPriorityProcessing:i,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:d}}async function es({stream:t,getError:r,isOutputChunk:i,url:c,requestBodyValues:d,responseHeaders:f}){const[m,x]=t.tee(),v=m.getReader();try{for(;;){const g=await v.read();if(g.done)return x;const E=g.value;if(!E.success)return x;const A=r(E.value);if(A!=null)throw x.cancel().catch(()=>{}),wg({frame:A,url:c,requestBodyValues:d,responseHeaders:f});if(i(E.value))return x}}finally{v.cancel().catch(()=>{}),v.releaseLock()}}function wg({frame:t,url:r,requestBodyValues:i,responseHeaders:c}){var d;const f=_g(t);return new Kt({message:(d=f?.message)!=null?d:"OpenAI stream failed before any output was generated",url:r,requestBodyValues:i,statusCode:f==null?500:vg(f),responseHeaders:c,responseBody:JSON.stringify(t),data:t})}function _g(t){var r;const i=jr(t);if(i==null)return;if(i.type==="response.failed"){const d=jr(i.response),f=jr(d?.error);return typeof f?.message=="string"?{message:f.message,code:Oa(f.code),type:"response.failed",frame:t}:void 0}const c=(r=jr(i.error))!=null?r:i;return typeof c.message=="string"&&(jr(i.error)!=null||typeof c.type=="string"||"code"in c||"param"in c)?{message:c.message,code:Oa(c.code),type:typeof c.type=="string"?c.type:void 0,frame:t}:void 0}function vg(t){if(typeof t.code=="number"&&ka(t.code))return t.code;if(typeof t.code=="string"&&/^\d{3}$/.test(t.code)){const i=Number(t.code);if(ka(i))return i}const r=[t.code,t.type].filter(i=>typeof i=="string"||typeof i=="number").join(" ").toLowerCase();return["insufficient_quota","rate_limit"].some(i=>r.includes(i))?429:r.includes("authentication")?401:r.includes("permission")?403:r.includes("not_found")?404:["invalid","bad_request","context_length"].some(i=>r.includes(i))?400:r.includes("overload")?503:r.includes("timeout")?504:500}function jr(t){return typeof t=="object"&&t!=null?t:void 0}function Oa(t){return typeof t=="string"||typeof t=="number"?t:void 0}function ka(t){return Number.isInteger(t)&&t>=400&&t<=599}function Ra(t){var r,i,c,d,f,m,x,v;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const g=(r=t.prompt_tokens)!=null?r:0,E=(i=t.completion_tokens)!=null?i:0,A=(d=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?d:0,D=(m=(f=t.prompt_tokens_details)==null?void 0:f.cache_write_tokens)!=null?m:void 0,T=(v=(x=t.completion_tokens_details)==null?void 0:x.reasoning_tokens)!=null?v:0;return{inputTokens:{total:g,noCache:g-A-(D??0),cacheRead:A,cacheWrite:D},outputTokens:{total:E,text:E-T,reasoning:T},raw:t}}function Cg(t){return JSON.stringify(t===void 0?{}:t)}function Un(t){var r;return(r=t?.openai)==null?void 0:r.promptCacheBreakpoint}function bg({prompt:t,systemMessageMode:r="system"}){var i,c;const d=[],f=[];for(const{role:m,content:x,providerOptions:v}of t)switch(m){case"system":{switch(r){case"system":{const g=Un(v);d.push({role:"system",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"developer":{const g=Un(v);d.push({role:"developer",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"remove":{f.push({type:"other",message:"system messages are removed for this model"});break}default:{const g=r;throw new Error(`Unsupported system message mode: ${g}`)}}break}case"user":{if(x.length===1&&x[0].type==="text"&&Un(x[0].providerOptions)==null){d.push({role:"user",content:x[0].text});break}d.push({role:"user",content:x.map((g,E)=>{var A,D,T;switch(g.type){case"text":{const S=Un(g.providerOptions);return{type:"text",text:g.text,...S!=null&&{prompt_cache_breakpoint:S}}}case"file":{const S=Un(g.providerOptions);if(g.mediaType.startsWith("image/")){const P=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${P};base64,${kr(g.data)}`,detail:(D=(A=g.providerOptions)==null?void 0:A.openai)==null?void 0:D.imageDetail},...S!=null&&{prompt_cache_breakpoint:S}}}else if(g.mediaType.startsWith("audio/")){if(g.data instanceof URL)throw new Mn({functionality:"audio file parts with URLs"});switch(g.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:kr(g.data),format:"wav"},...S!=null&&{prompt_cache_breakpoint:S}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:kr(g.data),format:"mp3"},...S!=null&&{prompt_cache_breakpoint:S}};default:throw new Mn({functionality:`audio content parts with media type ${g.mediaType}`})}}else if(g.mediaType==="application/pdf"){if(g.data instanceof URL)throw new Mn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof g.data=="string"&&g.data.startsWith("file-")?{file_id:g.data}:{filename:(T=g.filename)!=null?T:`part-${E}.pdf`,file_data:`data:application/pdf;base64,${kr(g.data)}`},...S!=null&&{prompt_cache_breakpoint:S}}}else throw new Mn({functionality:`file part media type ${g.mediaType}`})}}})});break}case"assistant":{let g="";const E=[];let A=!1;const D=[];for(const T of x)switch(T.type){case"text":{const S=Un(T.providerOptions);g+=T.text,E.push({type:"text",text:T.text,...S!=null&&{prompt_cache_breakpoint:S}}),A||(A=S!=null);break}case"tool-call":{D.push({id:T.toolCallId,type:"function",function:{name:T.toolName,arguments:Cg(T.input)}});break}}d.push({role:"assistant",content:A?E:D.length>0?g||null:g,tool_calls:D.length>0?D:void 0});break}case"tool":{for(const g of x){if(g.type==="tool-approval-response")continue;const E=g.output,A=(i=E.type==="content"?E.value.map(T=>Un(T.providerOptions)).find(T=>T!=null):Un(E.providerOptions))!=null?i:Un(g.providerOptions);let D;switch(E.type){case"text":case"error-text":D=E.value;break;case"execution-denied":D=(c=E.reason)!=null?c:"Tool call execution denied.";break;case"content":case"json":case"error-json":D=JSON.stringify(E.value);break}d.push({role:"tool",tool_call_id:g.toolCallId,content:A==null?D:[{type:"text",text:D,prompt_cache_breakpoint:A}]})}break}default:{const g=m;throw new Error(`Unsupported role: ${g}`)}}return{messages:d,warnings:f}}function mi({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i?new Date(i*1e3):void 0}}function Ma(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Ag=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({message:N({role:Y("assistant").nullish(),content:w().nullish(),tool_calls:ue(N({id:w().nullish(),type:Y("function"),function:N({name:w(),arguments:w()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}),index:j(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),Eg=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({delta:N({role:Ae(["assistant"]).nullish(),content:w().nullish(),tool_calls:ue(N({index:j(),id:w().nullish(),type:Y("function").nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:j()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Qi]))),Ig=Fe(()=>Le(N({logitBias:wt(qh(),j()).optional(),logprobs:st([Mt(),j()]).optional(),parallelToolCalls:Mt().optional(),user:w().optional(),reasoningEffort:Ae(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:j().optional(),store:Mt().optional(),metadata:wt(w().max(64),w().max(512)).optional(),prediction:wt(w(),xr()).optional(),serviceTier:Ae(["auto","flex","priority","default"]).optional(),strictJsonSchema:Mt().optional(),textVerbosity:Ae(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional()})));function Sg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const i=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};const c=[];for(const f of t)switch(f.type){case"function":c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema,...f.strict!=null?{strict:f.strict}:{}}});break;default:i.push({type:"unsupported",feature:`tool type: ${f.type}`});break}if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:i};const d=r.type;switch(d){case"auto":case"none":case"required":return{tools:c,toolChoice:d,toolWarnings:i};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:i};default:{const f=d;throw new Mn({functionality:`tool choice type: ${f}`})}}}var Tg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,seed:g,tools:E,toolChoice:A,providerOptions:D}){var T,S,P,M,ee;const $=[],F=(T=await An({provider:"openai",providerOptions:D,schema:Ig}))!=null?T:{},re=_u(this.modelId),Z=(S=F.forceReasoning)!=null?S:re.isReasoningModel;d!=null&&$.push({type:"unsupported",feature:"topK"});const{messages:B,warnings:L}=bg({prompt:t,systemMessageMode:(P=F.systemMessageMode)!=null?P:Z?"developer":re.systemMessageMode});$.push(...L);const W=(M=F.strictJsonSchema)!=null?M:!0,z={model:this.modelId,logit_bias:F.logitBias,logprobs:F.logprobs===!0||typeof F.logprobs=="number"?!0:void 0,top_logprobs:typeof F.logprobs=="number"?F.logprobs:typeof F.logprobs=="boolean"&&F.logprobs?0:void 0,user:F.user,parallel_tool_calls:F.parallelToolCalls,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:v?.type==="json"?v.schema!=null?{type:"json_schema",json_schema:{schema:v.schema,strict:W,name:(ee=v.name)!=null?ee:"response",description:v.description}}:{type:"json_object"}:void 0,stop:x,seed:g,verbosity:F.textVerbosity,max_completion_tokens:F.maxCompletionTokens,store:F.store,metadata:F.metadata,prediction:F.prediction,reasoning_effort:F.reasoningEffort,service_tier:F.serviceTier,prompt_cache_key:F.promptCacheKey,prompt_cache_options:F.promptCacheOptions,prompt_cache_retention:F.promptCacheRetention,safety_identifier:F.safetyIdentifier,messages:B};Z?((F.reasoningEffort!=="none"||!re.supportsNonReasoningParameters)&&(z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),z.logprobs!=null&&(z.logprobs=void 0,$.push({type:"other",message:"logprobs is not supported for reasoning models"}))),z.frequency_penalty!=null&&(z.frequency_penalty=void 0,$.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),z.presence_penalty!=null&&(z.presence_penalty=void 0,$.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),z.logit_bias!=null&&(z.logit_bias=void 0,$.push({type:"other",message:"logitBias is not supported for reasoning models"})),z.top_logprobs!=null&&(z.top_logprobs=void 0,$.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),z.max_tokens!=null&&(z.max_completion_tokens==null&&(z.max_completion_tokens=z.max_tokens),z.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),F.serviceTier==="flex"&&!re.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),z.service_tier=void 0),F.serviceTier==="priority"&&!re.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),z.service_tier=void 0);const{tools:we,toolChoice:G,toolWarnings:me}=Sg({tools:E,toolChoice:A});return{args:{...z,tools:we,tool_choice:G},warnings:[...$,...me]}}async doGenerate(t){var r,i,c,d,f,m,x;const{args:v,warnings:g}=await this.getArgs(t),{responseHeaders:E,value:A,rawValue:D}=await Zn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:v,failedResponseHandler:En,successfulResponseHandler:mr(Ag),abortSignal:t.abortSignal,fetch:this.config.fetch}),T=A.choices[0],S=[],P=T.message.content;P!=null&&P.length>0&&S.push({type:"text",text:P});for(const $ of(r=T.message.tool_calls)!=null?r:[])S.push({type:"tool-call",toolCallId:(i=$.id)!=null?i:rn(),toolName:$.function.name,input:$.function.arguments});for(const $ of(c=T.message.annotations)!=null?c:[])S.push({type:"source",sourceType:"url",id:rn(),url:$.url_citation.url,title:$.url_citation.title});const M=(d=A.usage)==null?void 0:d.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const ee={openai:{}};return M?.accepted_prediction_tokens!=null&&(ee.openai.acceptedPredictionTokens=M?.accepted_prediction_tokens),M?.rejected_prediction_tokens!=null&&(ee.openai.rejectedPredictionTokens=M?.rejected_prediction_tokens),((m=T.logprobs)==null?void 0:m.content)!=null&&(ee.openai.logprobs=T.logprobs.content),{content:S,finishReason:{unified:Ma(T.finish_reason),raw:(x=T.finish_reason)!=null?x:void 0},usage:Ra(A.usage),request:{body:v},response:{...mi(A),headers:E,body:D},warnings:g,providerMetadata:ee}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Eg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:P=>"error"in P?P.error:void 0,isOutputChunk:Ng,url:d,requestBodyValues:c,responseHeaders:f}),v=[];let g={unified:"other",raw:void 0},E,A=!1,D=!1;const T={openai:{}};return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:i})},transform(P,M){var ee,$,F,re,Z,B,L,W,z,we,G,me,fe;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:P.error});return}const te=P.value;if("error"in te){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:te.error});return}if(!A){const le=mi(te);Object.values(le).some(Boolean)&&(A=!0,M.enqueue({type:"response-metadata",...mi(te)}))}te.usage!=null&&(E=te.usage,((ee=te.usage.completion_tokens_details)==null?void 0:ee.accepted_prediction_tokens)!=null&&(T.openai.acceptedPredictionTokens=($=te.usage.completion_tokens_details)==null?void 0:$.accepted_prediction_tokens),((F=te.usage.completion_tokens_details)==null?void 0:F.rejected_prediction_tokens)!=null&&(T.openai.rejectedPredictionTokens=(re=te.usage.completion_tokens_details)==null?void 0:re.rejected_prediction_tokens));const q=te.choices[0];if(q?.finish_reason!=null&&(g={unified:Ma(q.finish_reason),raw:q.finish_reason}),((Z=q?.logprobs)==null?void 0:Z.content)!=null&&(T.openai.logprobs=q.logprobs.content),q?.delta==null)return;const ke=q.delta;if(ke.content!=null&&(D||(M.enqueue({type:"text-start",id:"0"}),D=!0),M.enqueue({type:"text-delta",id:"0",delta:ke.content})),ke.tool_calls!=null)for(const le of ke.tool_calls){const Te=le.index;if(v[Te]==null){if(le.type!=null&&le.type!=="function")throw new fi({data:le,message:"Expected 'function' type."});if(le.id==null)throw new fi({data:le,message:"Expected 'id' to be a string."});if(((B=le.function)==null?void 0:B.name)==null)throw new fi({data:le,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:le.id,toolName:le.function.name}),v[Te]={id:le.id,type:"function",function:{name:le.function.name,arguments:(L=le.function.arguments)!=null?L:""},hasFinished:!1};const xe=v[Te];((W=xe.function)==null?void 0:W.name)!=null&&((z=xe.function)==null?void 0:z.arguments)!=null&&xe.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:xe.id,delta:xe.function.arguments});continue}const Je=v[Te];Je.hasFinished||(((we=le.function)==null?void 0:we.arguments)!=null&&(Je.function.arguments+=(me=(G=le.function)==null?void 0:G.arguments)!=null?me:""),M.enqueue({type:"tool-input-delta",id:Je.id,delta:(fe=le.function.arguments)!=null?fe:""}))}if(ke.annotations!=null)for(const le of ke.annotations)M.enqueue({type:"source",sourceType:"url",id:rn(),url:le.url_citation.url,title:le.url_citation.title})},flush(P){var M;D&&P.enqueue({type:"text-end",id:"0"});for(const ee of v)ee.hasFinished||(P.enqueue({type:"tool-input-end",id:ee.id}),P.enqueue({type:"tool-call",toolCallId:(M=ee.id)!=null?M:rn(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0);P.enqueue({type:"finish",finishReason:g,usage:Ra(E),...T!=null?{providerMetadata:T}:{}})}})),request:{body:c},response:{headers:f}}}};function Ng(t){return"error"in t?!1:t.choices.some(r=>{const i=r.delta;return i?.content!=null&&i.content.length>0||i?.tool_calls!=null&&i.tool_calls.length>0||i?.annotations!=null&&i.annotations.length>0})}function Da(t){var r,i,c,d;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=(r=t.prompt_tokens)!=null?r:0,m=(i=t.completion_tokens)!=null?i:0;return{inputTokens:{total:(c=t.prompt_tokens)!=null?c:void 0,noCache:f,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(d=t.completion_tokens)!=null?d:void 0,text:m,reasoning:void 0},raw:t}}function Og({prompt:t,user:r="user",assistant:i="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
41
46
 
42
- `,t=t.slice(1));for(const{role:u,content:f}of t)switch(u){case"system":throw new Ap({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const m=f.map(g=>{switch(g.type){case"text":return g.text}}).filter(Boolean).join("");c+=`${r}:
47
+ `,t=t.slice(1));for(const{role:d,content:f}of t)switch(d){case"system":throw new Up({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const m=f.map(x=>{switch(x.type){case"text":return x.text}}).filter(Boolean).join("");c+=`${r}:
43
48
  ${m}
44
49
 
45
- `;break}case"assistant":{const m=f.map(g=>{switch(g.type){case"text":return g.text;case"tool-call":throw new zn({functionality:"tool-call messages"})}}).join("");c+=`${o}:
50
+ `;break}case"assistant":{const m=f.map(x=>{switch(x.type){case"text":return x.text;case"tool-call":throw new Mn({functionality:"tool-call messages"})}}).join("");c+=`${i}:
46
51
  ${m}
47
52
 
48
- `;break}case"tool":throw new zn({functionality:"tool messages"});default:{const m=u;throw new Error(`Unsupported role: ${m}`)}}return c+=`${o}:
53
+ `;break}case"tool":throw new Mn({functionality:"tool messages"});default:{const m=d;throw new Error(`Unsupported role: ${m}`)}}return c+=`${i}:
49
54
  `,{prompt:c,stopSequences:[`
50
- ${r}:`]}}function Ta({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o!=null?new Date(o*1e3):void 0}}function Na(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var ag=Be(()=>Pe(T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({text:w(),finish_reason:w(),logprobs:T({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(ht(w(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),lg=Be(()=>Pe(Qe([T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({text:w(),finish_reason:w().nullish(),index:j(),logprobs:T({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(ht(w(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),qo]))),Oa=Be(()=>Pe(T({echo:Rt().optional(),logitBias:ht(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:Qe([Rt(),j()]).optional()}))),cg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=r}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:m,stopSequences:g,responseFormat:C,tools:x,toolChoice:A,seed:v,providerOptions:P}){const O=[],M={...await Zn({provider:"openai",providerOptions:P,schema:Oa}),...await Zn({provider:this.providerOptionsName,providerOptions:P,schema:Oa})};u!=null&&O.push({type:"unsupported",feature:"topK"}),x?.length&&O.push({type:"unsupported",feature:"tools"}),A!=null&&O.push({type:"unsupported",feature:"toolChoice"}),C!=null&&C.type!=="text"&&O.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:D,stopSequences:B}=sg({prompt:t}),G=[...B??[],...g??[]];return{args:{model:this.modelId,echo:M.echo,logit_bias:M.logitBias,logprobs:M?.logprobs===!0?0:M?.logprobs===!1?void 0:M?.logprobs,suffix:M.suffix,user:M.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,seed:v,prompt:D,stop:G.length>0?G:void 0},warnings:O}}async doGenerate(t){var r;const{args:o,warnings:c}=await this.getArgs(t),{responseHeaders:u,value:f,rawValue:m}=await $n({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:o,failedResponseHandler:An,successfulResponseHandler:hr(ag),abortSignal:t.abortSignal,fetch:this.config.fetch}),g=f.choices[0],C={openai:{}};return g.logprobs!=null&&(C.openai.logprobs=g.logprobs),{content:[{type:"text",text:g.text}],usage:Sa(f.usage),finishReason:{unified:Na(g.finish_reason),raw:(r=g.finish_reason)!=null?r:void 0},request:{body:o},response:{...Ta(f),headers:u,body:m},providerMetadata:C,warnings:c}}async doStream(t){const{args:r,warnings:o}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:u,value:f}=await $n({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:c,failedResponseHandler:An,successfulResponseHandler:Xo(lg),abortSignal:t.abortSignal,fetch:this.config.fetch});let m={unified:"other",raw:void 0};const g={openai:{}};let C,x=!0;return{stream:f.pipeThrough(new TransformStream({start(A){A.enqueue({type:"stream-start",warnings:o})},transform(A,v){if(t.includeRawChunks&&v.enqueue({type:"raw",rawValue:A.rawValue}),!A.success){m={unified:"error",raw:void 0},v.enqueue({type:"error",error:A.error});return}const P=A.value;if("error"in P){m={unified:"error",raw:void 0},v.enqueue({type:"error",error:P.error});return}x&&(x=!1,v.enqueue({type:"response-metadata",...Ta(P)}),v.enqueue({type:"text-start",id:"0"})),P.usage!=null&&(C=P.usage);const O=P.choices[0];O?.finish_reason!=null&&(m={unified:Na(O.finish_reason),raw:O.finish_reason}),O?.logprobs!=null&&(g.openai.logprobs=O.logprobs),O?.text!=null&&O.text.length>0&&v.enqueue({type:"text-delta",id:"0",delta:O.text})},flush(A){x||A.enqueue({type:"text-end",id:"0"}),A.enqueue({type:"finish",finishReason:m,providerMetadata:g,usage:Sa(C)})}})),request:{body:c},response:{headers:u}}}},ug=Be(()=>Pe(T({dimensions:j().optional(),user:w().optional()}))),dg=Be(()=>Pe(T({data:ue(T({embedding:ue(j())})),usage:T({prompt_tokens:j()}).nullish()}))),fg=class{constructor(t,r){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=r}get provider(){return this.config.provider}async doEmbed({values:t,headers:r,abortSignal:o,providerOptions:c}){var u;if(t.length>this.maxEmbeddingsPerCall)throw new Op({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(u=await Zn({provider:"openai",providerOptions:c,schema:ug}))!=null?u:{},{responseHeaders:m,value:g,rawValue:C}=await $n({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:En(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:An,successfulResponseHandler:hr(dg),abortSignal:o,fetch:this.config.fetch});return{warnings:[],embeddings:g.data.map(x=>x.embedding),usage:g.usage?{tokens:g.usage.prompt_tokens}:void 0,response:{headers:m,body:C}}}},ka=Be(()=>Pe(T({created:j().nullish(),data:ue(T({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:T({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:T({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),hg={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},pg=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function mg(t){return pg.some(r=>t.startsWith(r))}var gg=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=hg[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:r,mask:o,n:c,size:u,aspectRatio:f,seed:m,providerOptions:g,headers:C,abortSignal:x}){var A,v,P,O,M,D,B,G,Z,z,ee;const K=[];f!=null&&K.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&K.push({type:"unsupported",feature:"seed"});const V=(P=(v=(A=this.config._internal)==null?void 0:A.currentDate)==null?void 0:v.call(A))!=null?P:new Date;if(r!=null){const{value:S,responseHeaders:Te}=await ou({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:En(this.config.headers(),C),formData:Fp({model:this.modelId,prompt:t,image:await Promise.all(r.map(ye=>ye.type==="file"?new Blob([ye.data instanceof Uint8Array?new Blob([ye.data],{type:ye.mediaType}):new Blob([Ho(ye.data)],{type:ye.mediaType})],{type:ye.mediaType}):Kc(ye.url))),mask:o!=null?await xg(o):void 0,n:c,size:u,...(O=g.openai)!=null?O:{}}),failedResponseHandler:An,successfulResponseHandler:hr(ka),abortSignal:x,fetch:this.config.fetch});return{images:S.data.map(ye=>ye.b64_json),warnings:K,usage:S.usage!=null?{inputTokens:(M=S.usage.input_tokens)!=null?M:void 0,outputTokens:(D=S.usage.output_tokens)!=null?D:void 0,totalTokens:(B=S.usage.total_tokens)!=null?B:void 0}:void 0,response:{timestamp:V,modelId:this.modelId,headers:Te},providerMetadata:{openai:{images:S.data.map((ye,re)=>{var xe,Me,$,ge,ne,Q;return{...ye.revised_prompt?{revisedPrompt:ye.revised_prompt}:{},created:(xe=S.created)!=null?xe:void 0,size:(Me=S.size)!=null?Me:void 0,quality:($=S.quality)!=null?$:void 0,background:(ge=S.background)!=null?ge:void 0,outputFormat:(ne=S.output_format)!=null?ne:void 0,...Ra((Q=S.usage)==null?void 0:Q.input_tokens_details,re,S.data.length)}})}}}}const{value:U,responseHeaders:J}=await $n({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:En(this.config.headers(),C),body:{model:this.modelId,prompt:t,n:c,size:u,...(G=g.openai)!=null?G:{},...mg(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:An,successfulResponseHandler:hr(ka),abortSignal:x,fetch:this.config.fetch});return{images:U.data.map(S=>S.b64_json),warnings:K,usage:U.usage!=null?{inputTokens:(Z=U.usage.input_tokens)!=null?Z:void 0,outputTokens:(z=U.usage.output_tokens)!=null?z:void 0,totalTokens:(ee=U.usage.total_tokens)!=null?ee:void 0}:void 0,response:{timestamp:V,modelId:this.modelId,headers:J},providerMetadata:{openai:{images:U.data.map((S,Te)=>{var ye,re,xe,Me,$,ge;return{...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},created:(ye=U.created)!=null?ye:void 0,size:(re=U.size)!=null?re:void 0,quality:(xe=U.quality)!=null?xe:void 0,background:(Me=U.background)!=null?Me:void 0,outputFormat:($=U.output_format)!=null?$:void 0,...Ra((ge=U.usage)==null?void 0:ge.input_tokens_details,Te,U.data.length)}})}}}}};function Ra(t,r,o){if(t==null)return{};const c={};if(t.image_tokens!=null){const u=Math.floor(t.image_tokens/o),f=t.image_tokens-u*(o-1);c.imageTokens=r===o-1?f:u}if(t.text_tokens!=null){const u=Math.floor(t.text_tokens/o),f=t.text_tokens-u*(o-1);c.textTokens=r===o-1?f:u}return c}async function xg(t){if(!t)return;if(t.type==="url")return Kc(t.url);const r=t.data instanceof Uint8Array?t.data:Ho(t.data);return new Blob([r],{type:t.mediaType})}var lu=Be(()=>Pe(T({callId:w(),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}))),cu=Be(()=>Pe(T({status:Se(["completed","failed"]),output:w().optional()}))),yg=Dn({id:"openai.apply_patch",inputSchema:lu,outputSchema:cu}),wg=yg,_g=Be(()=>Pe(T({code:w().nullish(),containerId:w()}))),vg=Be(()=>Pe(T({outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullish()}))),Cg=Be(()=>Pe(T({container:Qe([w(),T({fileIds:ue(w()).optional()})]).optional()}))),bg=Dn({id:"openai.code_interpreter",inputSchema:_g,outputSchema:vg}),Eg=(t={})=>bg(t),Ag=Be(()=>Pe(T({name:w(),description:w().optional(),format:Qe([T({type:X("grammar"),syntax:Se(["regex","lark"]),definition:w()}),T({type:X("text")})]).optional()}))),Ig=Be(()=>Pe(w())),Sg=Ym({id:"openai.custom",inputSchema:Ig}),Tg=t=>Sg(t),uu=T({key:w(),type:Se(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Qe([w(),j(),Rt(),ue(w())])}),du=T({type:Se(["and","or"]),filters:ue(Qe([uu,Zo(()=>du)]))}),Ng=Be(()=>Pe(T({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:T({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:Qe([uu,du]).optional()}))),Og=Be(()=>Pe(T({queries:ue(w()),results:ue(T({attributes:ht(w(),bn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),kg=Dn({id:"openai.file_search",inputSchema:T({}),outputSchema:Og}),Rg=Be(()=>Pe(T({background:Se(["auto","opaque","transparent"]).optional(),inputFidelity:Se(["low","high"]).optional(),inputImageMask:T({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Se(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Se(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Se(["auto","low","medium","high"]).optional(),size:Se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),Mg=Be(()=>Pe(T({}))),Dg=Be(()=>Pe(T({result:w()}))),Pg=Dn({id:"openai.image_generation",inputSchema:Mg,outputSchema:Dg}),Bg=(t={})=>Pg(t),fu=Be(()=>Pe(T({action:T({type:X("exec"),command:ue(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:ht(w(),w()).optional()})}))),hu=Be(()=>Pe(T({output:w()}))),Lg=Dn({id:"openai.local_shell",inputSchema:fu,outputSchema:hu}),pu=Be(()=>Pe(T({action:T({commands:ue(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),So=Be(()=>Pe(T({output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exitCode:j()})])}))}))),Fg=ue(ut("type",[T({type:X("skillReference"),skillId:w(),version:w().optional()}),T({type:X("inline"),name:w(),description:w(),source:T({type:X("base64"),mediaType:X("application/zip"),data:w()})})])).optional(),Ug=Be(()=>Pe(T({environment:Qe([T({type:X("containerAuto"),fileIds:ue(w()).optional(),memoryLimit:Se(["1g","4g","16g","64g"]).optional(),networkPolicy:ut("type",[T({type:X("disabled")}),T({type:X("allowlist"),allowedDomains:ue(w()),domainSecrets:ue(T({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:Fg}),T({type:X("containerReference"),containerId:w()}),T({type:X("local").optional(),skills:ue(T({name:w(),description:w(),path:w()})).optional()})]).optional()}))),zg=Dn({id:"openai.shell",inputSchema:pu,outputSchema:So}),Vg=Be(()=>Pe(T({execution:Se(["server","client"]).optional(),description:w().optional(),parameters:ht(w(),bn()).optional()}))),To=Be(()=>Pe(T({arguments:bn().optional(),call_id:w().nullish()}))),No=Be(()=>Pe(T({tools:ue(ht(w(),bn()))}))),Zg=Dn({id:"openai.tool_search",inputSchema:To,outputSchema:No}),$g=(t={})=>Zg(t),Hg=Be(()=>Pe(T({externalWebAccess:Rt().optional(),filters:T({allowedDomains:ue(w()).optional()}).optional(),searchContextSize:Se(["low","medium","high"]).optional(),userLocation:T({type:X("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),Wg=Be(()=>Pe(T({}))),jg=Be(()=>Pe(T({action:ut("type",[T({type:X("search"),query:w().optional()}),T({type:X("openPage"),url:w().nullish()}),T({type:X("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ue(ut("type",[T({type:X("url"),url:w()}),T({type:X("api"),name:w()})])).optional()}))),Gg=Dn({id:"openai.web_search",inputSchema:Wg,outputSchema:jg}),Xg=(t={})=>Gg(t),qg=Be(()=>Pe(T({searchContextSize:Se(["low","medium","high"]).optional(),userLocation:T({type:X("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),Yg=Be(()=>Pe(T({}))),Kg=Be(()=>Pe(T({action:ut("type",[T({type:X("search"),query:w().optional()}),T({type:X("openPage"),url:w().nullish()}),T({type:X("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),Jg=Dn({id:"openai.web_search_preview",inputSchema:Yg,outputSchema:Kg}),Oo=Zo(()=>Qe([w(),j(),Rt(),pc(),ue(Oo),ht(w(),Oo)])),Qg=Be(()=>Pe(T({serverLabel:w(),allowedTools:Qe([ue(w()),T({readOnly:Rt().optional(),toolNames:ue(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:ht(w(),w()).optional(),requireApproval:Qe([Se(["always","never"]),T({never:T({toolNames:ue(w()).optional()}).optional()})]).optional(),serverDescription:w().optional(),serverUrl:w().optional()}).refine(t=>t.serverUrl!=null||t.connectorId!=null,"One of serverUrl or connectorId must be provided."))),e2=Be(()=>Pe(T({}))),t2=Be(()=>Pe(T({type:X("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:Qe([w(),Oo]).optional()}))),n2=Dn({id:"openai.mcp",inputSchema:e2,outputSchema:t2}),r2=t=>n2(t),i2={applyPatch:wg,customTool:Tg,codeInterpreter:Eg,fileSearch:kg,imageGeneration:Bg,localShell:Lg,shell:zg,webSearchPreview:Jg,webSearch:Xg,mcp:r2,toolSearch:$g};function Ma(t){var r,o,c,u;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=t.input_tokens,m=t.output_tokens,g=(o=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,C=(u=(c=t.output_tokens_details)==null?void 0:c.reasoning_tokens)!=null?u:0;return{inputTokens:{total:f,noCache:f-g,cacheRead:g,cacheWrite:void 0},outputTokens:{total:m,text:m-C,reasoning:C},raw:t}}function Da(t,r){return r?r.some(o=>t.startsWith(o)):!1}async function o2({prompt:t,toolNameMapping:r,systemMessageMode:o,providerOptionsName:c,fileIdPrefixes:u,store:f,hasConversation:m=!1,hasLocalShellTool:g=!1,hasShellTool:C=!1,hasApplyPatchTool:x=!1,customProviderToolNames:A}){var v,P,O,M,D,B,G,Z,z,ee,K,V,U,J,S,Te,ye;let re=[];const xe=[],Me=new Set;for(const{role:$,content:ge}of t)switch($){case"system":{switch(o){case"system":{re.push({role:"system",content:ge});break}case"developer":{re.push({role:"developer",content:ge});break}case"remove":{xe.push({type:"other",message:"system messages are removed for this model"});break}default:{const ne=o;throw new Error(`Unsupported system message mode: ${ne}`)}}break}case"user":{re.push({role:"user",content:ge.map((ne,Q)=>{var me,fe,ie;switch(ne.type){case"text":return{type:"input_text",text:ne.text};case"file":if(ne.mediaType.startsWith("image/")){const pe=ne.mediaType==="image/*"?"image/jpeg":ne.mediaType;return{type:"input_image",...ne.data instanceof URL?{image_url:ne.data.toString()}:typeof ne.data=="string"&&Da(ne.data,u)?{file_id:ne.data}:{image_url:`data:${pe};base64,${Tr(ne.data)}`},detail:(fe=(me=ne.providerOptions)==null?void 0:me[c])==null?void 0:fe.imageDetail}}else{if(ne.mediaType==="application/pdf")return ne.data instanceof URL?{type:"input_file",file_url:ne.data.toString()}:{type:"input_file",...typeof ne.data=="string"&&Da(ne.data,u)?{file_id:ne.data}:{filename:(ie=ne.filename)!=null?ie:`part-${Q}.pdf`,file_data:`data:application/pdf;base64,${Tr(ne.data)}`}};throw new zn({functionality:`file part media type ${ne.mediaType}`})}}})});break}case"assistant":{const ne={};for(const Q of ge)switch(Q.type){case"text":{const me=(v=Q.providerOptions)==null?void 0:v[c],fe=me?.itemId,ie=me?.phase;if(m&&fe!=null)break;if(f&&fe!=null){re.push({type:"item_reference",id:fe});break}re.push({role:"assistant",content:[{type:"output_text",text:Q.text}],id:fe,...ie!=null&&{phase:ie}});break}case"tool-call":{const me=(B=(O=(P=Q.providerOptions)==null?void 0:P[c])==null?void 0:O.itemId)!=null?B:(D=(M=Q.providerMetadata)==null?void 0:M[c])==null?void 0:D.itemId;if(m&&me!=null)break;const fe=r.toProviderToolName(Q.toolName);if(fe==="tool_search"){if(f&&me!=null){re.push({type:"item_reference",id:me});break}const ie=typeof Q.input=="string"?await ru({text:Q.input,schema:To}):await kt({value:Q.input,schema:To}),pe=ie.call_id!=null?"client":"server";re.push({type:"tool_search_call",id:me??Q.toolCallId,execution:pe,call_id:(G=ie.call_id)!=null?G:null,status:"completed",arguments:ie.arguments});break}if(Q.providerExecuted){f&&me!=null&&re.push({type:"item_reference",id:me});break}if(f&&me!=null){re.push({type:"item_reference",id:me});break}if(g&&fe==="local_shell"){const ie=await kt({value:Q.input,schema:fu});re.push({type:"local_shell_call",call_id:Q.toolCallId,id:me,action:{type:"exec",command:ie.action.command,timeout_ms:ie.action.timeoutMs,user:ie.action.user,working_directory:ie.action.workingDirectory,env:ie.action.env}});break}if(C&&fe==="shell"){const ie=await kt({value:Q.input,schema:pu});re.push({type:"shell_call",call_id:Q.toolCallId,id:me,status:"completed",action:{commands:ie.action.commands,timeout_ms:ie.action.timeoutMs,max_output_length:ie.action.maxOutputLength}});break}if(x&&fe==="apply_patch"){const ie=await kt({value:Q.input,schema:lu});re.push({type:"apply_patch_call",call_id:ie.callId,id:me,status:"completed",operation:ie.operation});break}if(A?.has(fe)){re.push({type:"custom_tool_call",call_id:Q.toolCallId,name:fe,input:typeof Q.input=="string"?Q.input:JSON.stringify(Q.input),id:me});break}re.push({type:"function_call",call_id:Q.toolCallId,name:fe,arguments:JSON.stringify(Q.input),id:me});break}case"tool-result":{if(Q.output.type==="execution-denied"||Q.output.type==="json"&&typeof Q.output.value=="object"&&Q.output.value!=null&&"type"in Q.output.value&&Q.output.value.type==="execution-denied"||m)break;const me=r.toProviderToolName(Q.toolName);if(me==="tool_search"){const fe=(ee=(z=(Z=Q.providerOptions)==null?void 0:Z[c])==null?void 0:z.itemId)!=null?ee:Q.toolCallId;if(f)re.push({type:"item_reference",id:fe});else if(Q.output.type==="json"){const ie=await kt({value:Q.output.value,schema:No});re.push({type:"tool_search_output",id:fe,execution:"server",call_id:null,status:"completed",tools:ie.tools})}break}if(C&&me==="shell"){if(Q.output.type==="json"){const fe=await kt({value:Q.output.value,schema:So});re.push({type:"shell_call_output",call_id:Q.toolCallId,output:fe.output.map(ie=>({stdout:ie.stdout,stderr:ie.stderr,outcome:ie.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ie.outcome.exitCode}}))})}break}if(f){const fe=(U=(V=(K=Q.providerOptions)==null?void 0:K[c])==null?void 0:V.itemId)!=null?U:Q.toolCallId;re.push({type:"item_reference",id:fe})}else xe.push({type:"other",message:`Results for OpenAI tool ${Q.toolName} are not sent to the API when store is false`});break}case"reasoning":{const me=await Zn({provider:c,providerOptions:Q.providerOptions,schema:s2}),fe=me?.itemId;if(m&&fe!=null)break;if(fe!=null){const ie=ne[fe];if(f)ie===void 0&&(re.push({type:"item_reference",id:fe}),ne[fe]={type:"reasoning",id:fe,summary:[]});else{const pe=[];Q.text.length>0?pe.push({type:"summary_text",text:Q.text}):ie!==void 0&&xe.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(Q)}.`}),ie===void 0?(ne[fe]={type:"reasoning",id:fe,encrypted_content:me?.reasoningEncryptedContent,summary:pe},re.push(ne[fe])):(ie.summary.push(...pe),me?.reasoningEncryptedContent!=null&&(ie.encrypted_content=me.reasoningEncryptedContent))}}else{const ie=me?.reasoningEncryptedContent;if(ie!=null){const pe=[];Q.text.length>0&&pe.push({type:"summary_text",text:Q.text}),re.push({type:"reasoning",encrypted_content:ie,summary:pe})}else xe.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(Q)}.`})}break}}break}case"tool":{for(const ne of ge){if(ne.type==="tool-approval-response"){const ie=ne;if(Me.has(ie.approvalId))continue;Me.add(ie.approvalId),f&&re.push({type:"item_reference",id:ie.approvalId}),re.push({type:"mcp_approval_response",approval_request_id:ie.approvalId,approve:ie.approved});continue}const Q=ne.output;if(Q.type==="execution-denied"&&((S=(J=Q.providerOptions)==null?void 0:J.openai)==null?void 0:S.approvalId))continue;const me=r.toProviderToolName(ne.toolName);if(me==="tool_search"&&Q.type==="json"){const ie=await kt({value:Q.value,schema:No});re.push({type:"tool_search_output",execution:"client",call_id:ne.toolCallId,status:"completed",tools:ie.tools});continue}if(g&&me==="local_shell"&&Q.type==="json"){const ie=await kt({value:Q.value,schema:hu});re.push({type:"local_shell_call_output",call_id:ne.toolCallId,output:ie.output});continue}if(C&&me==="shell"&&Q.type==="json"){const ie=await kt({value:Q.value,schema:So});re.push({type:"shell_call_output",call_id:ne.toolCallId,output:ie.output.map(pe=>({stdout:pe.stdout,stderr:pe.stderr,outcome:pe.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:pe.outcome.exitCode}}))});continue}if(x&&ne.toolName==="apply_patch"&&Q.type==="json"){const ie=await kt({value:Q.value,schema:cu});re.push({type:"apply_patch_call_output",call_id:ne.toolCallId,status:ie.status,output:ie.output});continue}if(A?.has(me)){let ie;switch(Q.type){case"text":case"error-text":ie=Q.value;break;case"execution-denied":ie=(Te=Q.reason)!=null?Te:"Tool execution denied.";break;case"json":case"error-json":ie=JSON.stringify(Q.value);break;case"content":ie=Q.value.map(pe=>{var vt;switch(pe.type){case"text":return{type:"input_text",text:pe.text};case"image-data":return{type:"input_image",image_url:`data:${pe.mediaType};base64,${pe.data}`};case"image-url":return{type:"input_image",image_url:pe.url};case"file-data":return{type:"input_file",filename:(vt=pe.filename)!=null?vt:"data",file_data:`data:${pe.mediaType};base64,${pe.data}`};case"file-url":return{type:"input_file",file_url:pe.url};default:xe.push({type:"other",message:`unsupported custom tool content part type: ${pe.type}`});return}}).filter(_a);break;default:ie=""}re.push({type:"custom_tool_call_output",call_id:ne.toolCallId,output:ie});continue}let fe;switch(Q.type){case"text":case"error-text":fe=Q.value;break;case"execution-denied":fe=(ye=Q.reason)!=null?ye:"Tool execution denied.";break;case"json":case"error-json":fe=JSON.stringify(Q.value);break;case"content":fe=Q.value.map(ie=>{var pe;switch(ie.type){case"text":return{type:"input_text",text:ie.text};case"image-data":return{type:"input_image",image_url:`data:${ie.mediaType};base64,${ie.data}`};case"image-url":return{type:"input_image",image_url:ie.url};case"file-data":return{type:"input_file",filename:(pe=ie.filename)!=null?pe:"data",file_data:`data:${ie.mediaType};base64,${ie.data}`};case"file-url":return{type:"input_file",file_url:ie.url};default:{xe.push({type:"other",message:`unsupported tool content part type: ${ie.type}`});return}}}).filter(_a);break}re.push({type:"function_call_output",call_id:ne.toolCallId,output:fe})}break}default:{const ne=$;throw new Error(`Unsupported role: ${ne}`)}}return!f&&re.some($=>"type"in $&&$.type==="reasoning"&&$.encrypted_content==null)&&(xe.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),re=re.filter($=>!("type"in $)||$.type!=="reasoning"||$.encrypted_content!=null)),{input:re,warnings:xe}}var s2=T({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function uo({finishReason:t,hasFunctionCall:r}){switch(t){case void 0:case null:return r?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return r?"tool-calls":"other"}}var Qr=Zo(()=>Qe([w(),j(),Rt(),pc(),ue(Qr),ht(w(),Qr.optional())])),a2=Be(()=>Pe(Qe([T({type:X("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish()}),T({type:Se(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:w()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}),service_tier:w().nullish()})}),T({type:X("response.failed"),response:T({error:T({code:w().nullish(),message:w()}).nullish(),incomplete_details:T({reason:w()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}).nullish(),service_tier:w().nullish()})}),T({type:X("response.created"),response:T({id:w(),created_at:j(),model:w(),service_tier:w().nullish()})}),T({type:X("response.output_item.added"),output_index:j(),item:ut("type",[T({type:X("message"),id:w(),phase:Se(["commentary","final_answer"]).nullish()}),T({type:X("reasoning"),id:w(),encrypted_content:w().nullish()}),T({type:X("function_call"),id:w(),call_id:w(),name:w(),arguments:w()}),T({type:X("web_search_call"),id:w(),status:w()}),T({type:X("computer_call"),id:w(),status:w()}),T({type:X("file_search_call"),id:w()}),T({type:X("image_generation_call"),id:w()}),T({type:X("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullable(),status:w()}),T({type:X("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),T({type:X("mcp_list_tools"),id:w()}),T({type:X("mcp_approval_request"),id:w()}),T({type:X("apply_patch_call"),id:w(),call_id:w(),status:Se(["in_progress","completed"]),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}),T({type:X("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),T({type:X("shell_call"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:ue(w())})}),T({type:X("shell_call_output"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exit_code:j()})])}))}),T({type:X("tool_search_call"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),arguments:bn()}),T({type:X("tool_search_output"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),tools:ue(ht(w(),Qr.optional()))})])}),T({type:X("response.output_item.done"),output_index:j(),item:ut("type",[T({type:X("message"),id:w(),phase:Se(["commentary","final_answer"]).nullish()}),T({type:X("reasoning"),id:w(),encrypted_content:w().nullish()}),T({type:X("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:X("completed")}),T({type:X("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:X("completed")}),T({type:X("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullable()}),T({type:X("image_generation_call"),id:w(),result:w()}),T({type:X("web_search_call"),id:w(),status:w(),action:ut("type",[T({type:X("search"),query:w().nullish(),sources:ue(ut("type",[T({type:X("url"),url:w()}),T({type:X("api"),name:w()})])).nullish()}),T({type:X("open_page"),url:w().nullish()}),T({type:X("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),T({type:X("file_search_call"),id:w(),queries:ue(w()),results:ue(T({attributes:ht(w(),Qe([w(),j(),Rt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),T({type:X("local_shell_call"),id:w(),call_id:w(),action:T({type:X("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:ht(w(),w()).optional()})}),T({type:X("computer_call"),id:w(),status:X("completed")}),T({type:X("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),T({type:X("mcp_list_tools"),id:w(),server_label:w(),tools:ue(T({name:w(),description:w().optional(),input_schema:mr(),annotations:ht(w(),bn()).optional()})),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),T({type:X("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),T({type:X("apply_patch_call"),id:w(),call_id:w(),status:Se(["in_progress","completed"]),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}),T({type:X("shell_call"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:ue(w())})}),T({type:X("shell_call_output"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exit_code:j()})])}))}),T({type:X("tool_search_call"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),arguments:bn()}),T({type:X("tool_search_output"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),tools:ue(ht(w(),Qr.optional()))})])}),T({type:X("response.function_call_arguments.delta"),item_id:w(),output_index:j(),delta:w()}),T({type:X("response.custom_tool_call_input.delta"),item_id:w(),output_index:j(),delta:w()}),T({type:X("response.image_generation_call.partial_image"),item_id:w(),output_index:j(),partial_image_b64:w()}),T({type:X("response.code_interpreter_call_code.delta"),item_id:w(),output_index:j(),delta:w()}),T({type:X("response.code_interpreter_call_code.done"),item_id:w(),output_index:j(),code:w()}),T({type:X("response.output_text.annotation.added"),annotation:ut("type",[T({type:X("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),T({type:X("file_citation"),file_id:w(),filename:w(),index:j()}),T({type:X("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),T({type:X("file_path"),file_id:w(),index:j()})])}),T({type:X("response.reasoning_summary_part.added"),item_id:w(),summary_index:j()}),T({type:X("response.reasoning_summary_text.delta"),item_id:w(),summary_index:j(),delta:w()}),T({type:X("response.reasoning_summary_part.done"),item_id:w(),summary_index:j()}),T({type:X("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:j(),delta:w(),obfuscation:w().nullish()}),T({type:X("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:j(),diff:w()}),T({type:X("error"),sequence_number:j(),error:T({type:w(),code:w(),message:w(),param:w().nullish()})}),T({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),l2=Be(()=>Pe(T({id:w().optional(),created_at:j().optional(),error:T({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ue(ut("type",[T({type:X("message"),role:X("assistant"),id:w(),phase:Se(["commentary","final_answer"]).nullish(),content:ue(T({type:X("output_text"),text:w(),logprobs:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish(),annotations:ue(ut("type",[T({type:X("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),T({type:X("file_citation"),file_id:w(),filename:w(),index:j()}),T({type:X("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),T({type:X("file_path"),file_id:w(),index:j()})]))}))}),T({type:X("web_search_call"),id:w(),status:w(),action:ut("type",[T({type:X("search"),query:w().nullish(),sources:ue(ut("type",[T({type:X("url"),url:w()}),T({type:X("api"),name:w()})])).nullish()}),T({type:X("open_page"),url:w().nullish()}),T({type:X("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),T({type:X("file_search_call"),id:w(),queries:ue(w()),results:ue(T({attributes:ht(w(),Qe([w(),j(),Rt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),T({type:X("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullable()}),T({type:X("image_generation_call"),id:w(),result:w()}),T({type:X("local_shell_call"),id:w(),call_id:w(),action:T({type:X("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:ht(w(),w()).optional()})}),T({type:X("function_call"),call_id:w(),name:w(),arguments:w(),id:w()}),T({type:X("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),T({type:X("computer_call"),id:w(),status:w().optional()}),T({type:X("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ue(T({type:X("summary_text"),text:w()}))}),T({type:X("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),T({type:X("mcp_list_tools"),id:w(),server_label:w(),tools:ue(T({name:w(),description:w().optional(),input_schema:mr(),annotations:ht(w(),bn()).optional()})),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),T({type:X("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),T({type:X("apply_patch_call"),id:w(),call_id:w(),status:Se(["in_progress","completed"]),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}),T({type:X("shell_call"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:ue(w())})}),T({type:X("shell_call_output"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exit_code:j()})])}))}),T({type:X("tool_search_call"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),arguments:bn()}),T({type:X("tool_search_output"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),tools:ue(ht(w(),Qr.optional()))})])).optional(),service_tier:w().nullish(),incomplete_details:T({reason:w()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}).optional()}))),mu=20,Pa=Be(()=>Pe(T({conversation:w().nullish(),include:ue(Se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:Qe([Rt(),j().min(1).max(mu)]).optional(),maxToolCalls:j().nullish(),metadata:mr().nullish(),parallelToolCalls:Rt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheRetention:Se(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Se(["auto","flex","priority","default"]).nullish(),store:Rt().nullish(),strictJsonSchema:Rt().nullish(),textVerbosity:Se(["low","medium","high"]).nullish(),truncation:Se(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Se(["system","developer","remove"]).optional(),forceReasoning:Rt().optional()})));async function c2({tools:t,toolChoice:r,toolNameMapping:o,customProviderToolNames:c}){var u,f;t=t?.length?t:void 0;const m=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:m};const g=[],C=c??new Set;for(const A of t)switch(A.type){case"function":{const v=(u=A.providerOptions)==null?void 0:u.openai,P=v?.deferLoading;g.push({type:"function",name:A.name,description:A.description,parameters:A.inputSchema,...A.strict!=null?{strict:A.strict}:{},...P!=null?{defer_loading:P}:{}});break}case"provider":{switch(A.id){case"openai.file_search":{const v=await kt({value:A.args,schema:Ng});g.push({type:"file_search",vector_store_ids:v.vectorStoreIds,max_num_results:v.maxNumResults,ranking_options:v.ranking?{ranker:v.ranking.ranker,score_threshold:v.ranking.scoreThreshold}:void 0,filters:v.filters});break}case"openai.local_shell":{g.push({type:"local_shell"});break}case"openai.shell":{const v=await kt({value:A.args,schema:Ug});g.push({type:"shell",...v.environment&&{environment:u2(v.environment)}});break}case"openai.apply_patch":{g.push({type:"apply_patch"});break}case"openai.web_search_preview":{const v=await kt({value:A.args,schema:qg});g.push({type:"web_search_preview",search_context_size:v.searchContextSize,user_location:v.userLocation});break}case"openai.web_search":{const v=await kt({value:A.args,schema:Hg});g.push({type:"web_search",filters:v.filters!=null?{allowed_domains:v.filters.allowedDomains}:void 0,external_web_access:v.externalWebAccess,search_context_size:v.searchContextSize,user_location:v.userLocation});break}case"openai.code_interpreter":{const v=await kt({value:A.args,schema:Cg});g.push({type:"code_interpreter",container:v.container==null?{type:"auto",file_ids:void 0}:typeof v.container=="string"?v.container:{type:"auto",file_ids:v.container.fileIds}});break}case"openai.image_generation":{const v=await kt({value:A.args,schema:Rg});g.push({type:"image_generation",background:v.background,input_fidelity:v.inputFidelity,input_image_mask:v.inputImageMask?{file_id:v.inputImageMask.fileId,image_url:v.inputImageMask.imageUrl}:void 0,model:v.model,moderation:v.moderation,partial_images:v.partialImages,quality:v.quality,output_compression:v.outputCompression,output_format:v.outputFormat,size:v.size});break}case"openai.mcp":{const v=await kt({value:A.args,schema:Qg}),P=D=>({tool_names:D.toolNames}),O=v.requireApproval,M=O==null?void 0:typeof O=="string"?O:O.never!=null?{never:P(O.never)}:void 0;g.push({type:"mcp",server_label:v.serverLabel,allowed_tools:Array.isArray(v.allowedTools)?v.allowedTools:v.allowedTools?{read_only:v.allowedTools.readOnly,tool_names:v.allowedTools.toolNames}:void 0,authorization:v.authorization,connector_id:v.connectorId,headers:v.headers,require_approval:M??"never",server_description:v.serverDescription,server_url:v.serverUrl});break}case"openai.custom":{const v=await kt({value:A.args,schema:Ag});g.push({type:"custom",name:v.name,description:v.description,format:v.format}),C.add(v.name);break}case"openai.tool_search":{const v=await kt({value:A.args,schema:Vg});g.push({type:"tool_search",...v.execution!=null?{execution:v.execution}:{},...v.description!=null?{description:v.description}:{},...v.parameters!=null?{parameters:v.parameters}:{}});break}}break}default:m.push({type:"unsupported",feature:`function tool ${A}`});break}if(r==null)return{tools:g,toolChoice:void 0,toolWarnings:m};const x=r.type;switch(x){case"auto":case"none":case"required":return{tools:g,toolChoice:x,toolWarnings:m};case"tool":{const A=(f=o?.toProviderToolName(r.toolName))!=null?f:r.toolName;return{tools:g,toolChoice:A==="code_interpreter"||A==="file_search"||A==="image_generation"||A==="web_search_preview"||A==="web_search"||A==="mcp"||A==="apply_patch"?{type:A}:C.has(A)?{type:"custom",name:A}:{type:"function",name:A},toolWarnings:m}}default:{const A=x;throw new zn({functionality:`tool choice type: ${A}`})}}}function u2(t){if(t.type==="containerReference")return{type:"container_reference",container_id:t.containerId};if(t.type==="containerAuto"){const o=t;return{type:"container_auto",file_ids:o.fileIds,memory_limit:o.memoryLimit,network_policy:o.networkPolicy==null?void 0:o.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:o.networkPolicy.allowedDomains,domain_secrets:o.networkPolicy.domainSecrets},skills:d2(o.skills)}}return{type:"local",skills:t.skills}}function d2(t){return t?.map(r=>r.type==="skillReference"?{type:"skill_reference",skill_id:r.skillId,version:r.version}:{type:"inline",name:r.name,description:r.description,source:{type:"base64",media_type:r.source.mediaType,data:r.source.data}})}function Ba(t){var r,o;const c={};for(const u of t)if(u.role==="assistant")for(const f of u.content){if(f.type!=="tool-call")continue;const m=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.approvalRequestId;m!=null&&(c[m]=f.toolCallId)}return c}var f2=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:r,stopSequences:o,topP:c,topK:u,presencePenalty:f,frequencyPenalty:m,seed:g,prompt:C,providerOptions:x,tools:A,toolChoice:v,responseFormat:P}){var O,M,D,B,G,Z,z,ee,K;const V=[],U=au(this.modelId);u!=null&&V.push({type:"unsupported",feature:"topK"}),g!=null&&V.push({type:"unsupported",feature:"seed"}),f!=null&&V.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&V.push({type:"unsupported",feature:"frequencyPenalty"}),o!=null&&V.push({type:"unsupported",feature:"stopSequences"});const J=this.config.provider.includes("azure")?"azure":"openai";let S=await Zn({provider:J,providerOptions:x,schema:Pa});S==null&&J!=="openai"&&(S=await Zn({provider:"openai",providerOptions:x,schema:Pa}));const Te=(O=S?.forceReasoning)!=null?O:U.isReasoningModel;S?.conversation&&S?.previousResponseId&&V.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const ye=Mp({tools:A,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:Ue=>Ue.id==="openai.custom"?Ue.args.name:void 0}),re=new Set,{tools:xe,toolChoice:Me,toolWarnings:$}=await c2({tools:A,toolChoice:v,toolNameMapping:ye,customProviderToolNames:re}),{input:ge,warnings:ne}=await o2({prompt:C,toolNameMapping:ye,systemMessageMode:(M=S?.systemMessageMode)!=null?M:Te?"developer":U.systemMessageMode,providerOptionsName:J,fileIdPrefixes:this.config.fileIdPrefixes,store:(D=S?.store)!=null?D:!0,hasConversation:S?.conversation!=null,hasLocalShellTool:ie("openai.local_shell"),hasShellTool:ie("openai.shell"),hasApplyPatchTool:ie("openai.apply_patch"),customProviderToolNames:re.size>0?re:void 0});V.push(...ne);const Q=(B=S?.strictJsonSchema)!=null?B:!0;let me=S?.include;function fe(Ue){me==null?me=[Ue]:me.includes(Ue)||(me=[...me,Ue])}function ie(Ue){return A?.find(Ht=>Ht.type==="provider"&&Ht.id===Ue)!=null}const pe=typeof S?.logprobs=="number"?S?.logprobs:S?.logprobs===!0?mu:void 0;pe&&fe("message.output_text.logprobs");const vt=(G=A?.find(Ue=>Ue.type==="provider"&&(Ue.id==="openai.web_search"||Ue.id==="openai.web_search_preview")))==null?void 0:G.name;vt&&fe("web_search_call.action.sources"),ie("openai.code_interpreter")&&fe("code_interpreter_call.outputs");const Ee=S?.store;Ee===!1&&Te&&fe("reasoning.encrypted_content");const Tt={model:this.modelId,input:ge,temperature:r,top_p:c,max_output_tokens:t,...(P?.type==="json"||S?.textVerbosity)&&{text:{...P?.type==="json"&&{format:P.schema!=null?{type:"json_schema",strict:Q,name:(Z=P.name)!=null?Z:"response",description:P.description,schema:P.schema}:{type:"json_object"}},...S?.textVerbosity&&{verbosity:S.textVerbosity}}},conversation:S?.conversation,max_tool_calls:S?.maxToolCalls,metadata:S?.metadata,parallel_tool_calls:S?.parallelToolCalls,previous_response_id:S?.previousResponseId,store:Ee,user:S?.user,instructions:S?.instructions,service_tier:S?.serviceTier,include:me,prompt_cache_key:S?.promptCacheKey,prompt_cache_retention:S?.promptCacheRetention,safety_identifier:S?.safetyIdentifier,top_logprobs:pe,truncation:S?.truncation,...Te&&(S?.reasoningEffort!=null||S?.reasoningSummary!=null)&&{reasoning:{...S?.reasoningEffort!=null&&{effort:S.reasoningEffort},...S?.reasoningSummary!=null&&{summary:S.reasoningSummary}}}};Te?S?.reasoningEffort==="none"&&U.supportsNonReasoningParameters||(Tt.temperature!=null&&(Tt.temperature=void 0,V.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),Tt.top_p!=null&&(Tt.top_p=void 0,V.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(S?.reasoningEffort!=null&&V.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),S?.reasoningSummary!=null&&V.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),S?.serviceTier==="flex"&&!U.supportsFlexProcessing&&(V.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Tt.service_tier),S?.serviceTier==="priority"&&!U.supportsPriorityProcessing&&(V.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete Tt.service_tier);const Ce=(K=(ee=(z=A?.find(Ue=>Ue.type==="provider"&&Ue.id==="openai.shell"))==null?void 0:z.args)==null?void 0:ee.environment)==null?void 0:K.type,sn=Ce==="containerAuto"||Ce==="containerReference";return{webSearchToolName:vt,args:{...Tt,tools:xe,tool_choice:Me},warnings:[...V,...$],store:Ee,toolNameMapping:ye,providerOptionsName:J,isShellProviderExecuted:sn}}async doGenerate(t){var r,o,c,u,f,m,g,C,x,A,v,P,O,M,D,B,G,Z,z,ee,K,V,U,J,S,Te,ye,re;const{args:xe,warnings:Me,webSearchToolName:$,toolNameMapping:ge,providerOptionsName:ne,isShellProviderExecuted:Q}=await this.getArgs(t),me=this.config.url({path:"/responses",modelId:this.modelId}),fe=Ba(t.prompt),{responseHeaders:ie,value:pe,rawValue:vt}=await $n({url:me,headers:En(this.config.headers(),t.headers),body:xe,failedResponseHandler:An,successfulResponseHandler:hr(l2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(pe.error)throw new cn({message:pe.error.message,url:me,requestBodyValues:xe,statusCode:400,responseHeaders:ie,responseBody:vt,isRetryable:!1});const Ee=[],Tt=[];let Ce=!1;const sn=[];for(const de of pe.output)switch(de.type){case"reasoning":{de.summary.length===0&&de.summary.push({type:"summary_text",text:""});for(const Oe of de.summary)Ee.push({type:"reasoning",text:Oe.text,providerMetadata:{[ne]:{itemId:de.id,reasoningEncryptedContent:(r=de.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("image_generation"),result:{result:de.result}});break}case"tool_search_call":{const Oe=(o=de.call_id)!=null?o:de.id,yt=de.execution==="server";yt&&sn.push(Oe),Ee.push({type:"tool-call",toolCallId:Oe,toolName:ge.toCustomToolName("tool_search"),input:JSON.stringify({arguments:de.arguments,call_id:de.call_id}),...yt?{providerExecuted:!0}:{},providerMetadata:{[ne]:{itemId:de.id}}});break}case"tool_search_output":{const Oe=(u=(c=de.call_id)!=null?c:sn.shift())!=null?u:de.id;Ee.push({type:"tool-result",toolCallId:Oe,toolName:ge.toCustomToolName("tool_search"),result:{tools:de.tools},providerMetadata:{[ne]:{itemId:de.id}}});break}case"local_shell_call":{Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:ge.toCustomToolName("local_shell"),input:JSON.stringify({action:de.action}),providerMetadata:{[ne]:{itemId:de.id}}});break}case"shell_call":{Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:ge.toCustomToolName("shell"),input:JSON.stringify({action:{commands:de.action.commands}}),...Q&&{providerExecuted:!0},providerMetadata:{[ne]:{itemId:de.id}}});break}case"shell_call_output":{Ee.push({type:"tool-result",toolCallId:de.call_id,toolName:ge.toCustomToolName("shell"),result:{output:de.output.map(Oe=>({stdout:Oe.stdout,stderr:Oe.stderr,outcome:Oe.outcome.type==="exit"?{type:"exit",exitCode:Oe.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const Oe of de.content){(m=(f=t.providerOptions)==null?void 0:f[ne])!=null&&m.logprobs&&Oe.logprobs&&Tt.push(Oe.logprobs);const yt={itemId:de.id,...de.phase!=null&&{phase:de.phase},...Oe.annotations.length>0&&{annotations:Oe.annotations}};Ee.push({type:"text",text:Oe.text,providerMetadata:{[ne]:yt}});for(const be of Oe.annotations)be.type==="url_citation"?Ee.push({type:"source",sourceType:"url",id:(x=(C=(g=this.config).generateId)==null?void 0:C.call(g))!=null?x:Kt(),url:be.url,title:be.title}):be.type==="file_citation"?Ee.push({type:"source",sourceType:"document",id:(P=(v=(A=this.config).generateId)==null?void 0:v.call(A))!=null?P:Kt(),mediaType:"text/plain",title:be.filename,filename:be.filename,providerMetadata:{[ne]:{type:be.type,fileId:be.file_id,index:be.index}}}):be.type==="container_file_citation"?Ee.push({type:"source",sourceType:"document",id:(D=(M=(O=this.config).generateId)==null?void 0:M.call(O))!=null?D:Kt(),mediaType:"text/plain",title:be.filename,filename:be.filename,providerMetadata:{[ne]:{type:be.type,fileId:be.file_id,containerId:be.container_id}}}):be.type==="file_path"&&Ee.push({type:"source",sourceType:"document",id:(Z=(G=(B=this.config).generateId)==null?void 0:G.call(B))!=null?Z:Kt(),mediaType:"application/octet-stream",title:be.file_id,filename:be.file_id,providerMetadata:{[ne]:{type:be.type,fileId:be.file_id,index:be.index}}})}break}case"function_call":{Ce=!0,Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:de.name,input:de.arguments,providerMetadata:{[ne]:{itemId:de.id}}});break}case"custom_tool_call":{Ce=!0;const Oe=ge.toCustomToolName(de.name);Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:Oe,input:JSON.stringify(de.input),providerMetadata:{[ne]:{itemId:de.id}}});break}case"web_search_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName($??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName($??"web_search"),result:Fa(de.action)});break}case"mcp_call":{const Oe=de.approval_request_id!=null&&(z=fe[de.approval_request_id])!=null?z:de.id,yt=`mcp.${de.name}`;Ee.push({type:"tool-call",toolCallId:Oe,toolName:yt,input:de.arguments,providerExecuted:!0,dynamic:!0}),Ee.push({type:"tool-result",toolCallId:Oe,toolName:yt,result:{type:"call",serverLabel:de.server_label,name:de.name,arguments:de.arguments,...de.output!=null?{output:de.output}:{},...de.error!=null?{error:de.error}:{}},providerMetadata:{[ne]:{itemId:de.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const Oe=(ee=de.approval_request_id)!=null?ee:de.id,yt=(U=(V=(K=this.config).generateId)==null?void 0:V.call(K))!=null?U:Kt(),be=`mcp.${de.name}`;Ee.push({type:"tool-call",toolCallId:yt,toolName:be,input:de.arguments,providerExecuted:!0,dynamic:!0}),Ee.push({type:"tool-approval-request",approvalId:Oe,toolCallId:yt});break}case"computer_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:de.status||"completed"}});break}case"file_search_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("file_search"),result:{queries:de.queries,results:(S=(J=de.results)==null?void 0:J.map(Oe=>({attributes:Oe.attributes,fileId:Oe.file_id,filename:Oe.filename,score:Oe.score,text:Oe.text})))!=null?S:null}});break}case"code_interpreter_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("code_interpreter"),input:JSON.stringify({code:de.code,containerId:de.container_id}),providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("code_interpreter"),result:{outputs:de.outputs}});break}case"apply_patch_call":{Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:ge.toCustomToolName("apply_patch"),input:JSON.stringify({callId:de.call_id,operation:de.operation}),providerMetadata:{[ne]:{itemId:de.id}}});break}}const Ue={[ne]:{responseId:pe.id,...Tt.length>0?{logprobs:Tt}:{},...typeof pe.service_tier=="string"?{serviceTier:pe.service_tier}:{}}},Ht=pe.usage;return{content:Ee,finishReason:{unified:uo({finishReason:(Te=pe.incomplete_details)==null?void 0:Te.reason,hasFunctionCall:Ce}),raw:(re=(ye=pe.incomplete_details)==null?void 0:ye.reason)!=null?re:void 0},usage:Ma(Ht),request:{body:xe},response:{id:pe.id,timestamp:new Date(pe.created_at*1e3),modelId:pe.model,headers:ie,body:vt},providerMetadata:Ue,warnings:Me}}async doStream(t){const{args:r,warnings:o,webSearchToolName:c,toolNameMapping:u,store:f,providerOptionsName:m,isShellProviderExecuted:g}=await this.getArgs(t),{responseHeaders:C,value:x}=await $n({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:An,successfulResponseHandler:Xo(a2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=this,v=Ba(t.prompt),P=new Map;let O={unified:"other",raw:void 0},M;const D=[];let B=null;const G={},Z=[];let z,ee=!1;const K={};let V;const U=[];return{stream:x.pipeThrough(new TransformStream({start(J){J.enqueue({type:"stream-start",warnings:o})},transform(J,S){var Te,ye,re,xe,Me,$,ge,ne,Q,me,fe,ie,pe,vt,Ee,Tt,Ce,sn,Ue,Ht,de,Oe,yt,be,Xt,Wt,In,Ct,Xe,Ze,Sn,ve,Bn,Hn,Jt,Wn,Bt,rr;if(t.includeRawChunks&&S.enqueue({type:"raw",rawValue:J.rawValue}),!J.success){O={unified:"error",raw:void 0},S.enqueue({type:"error",error:J.error});return}const R=J.value;if(La(R)){if(R.item.type==="function_call")G[R.output_index]={toolName:R.item.name,toolCallId:R.item.call_id},S.enqueue({type:"tool-input-start",id:R.item.call_id,toolName:R.item.name});else if(R.item.type==="custom_tool_call"){const oe=u.toCustomToolName(R.item.name);G[R.output_index]={toolName:oe,toolCallId:R.item.call_id},S.enqueue({type:"tool-input-start",id:R.item.call_id,toolName:oe})}else if(R.item.type==="web_search_call")G[R.output_index]={toolName:u.toCustomToolName(c??"web_search"),toolCallId:R.item.id},S.enqueue({type:"tool-input-start",id:R.item.id,toolName:u.toCustomToolName(c??"web_search"),providerExecuted:!0}),S.enqueue({type:"tool-input-end",id:R.item.id}),S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(R.item.type==="computer_call")G[R.output_index]={toolName:u.toCustomToolName("computer_use"),toolCallId:R.item.id},S.enqueue({type:"tool-input-start",id:R.item.id,toolName:u.toCustomToolName("computer_use"),providerExecuted:!0});else if(R.item.type==="code_interpreter_call")G[R.output_index]={toolName:u.toCustomToolName("code_interpreter"),toolCallId:R.item.id,codeInterpreter:{containerId:R.item.container_id}},S.enqueue({type:"tool-input-start",id:R.item.id,toolName:u.toCustomToolName("code_interpreter"),providerExecuted:!0}),S.enqueue({type:"tool-input-delta",id:R.item.id,delta:`{"containerId":"${R.item.container_id}","code":"`});else if(R.item.type==="file_search_call")S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(R.item.type==="image_generation_call")S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(R.item.type==="tool_search_call"){const oe=R.item.id,qe=u.toCustomToolName("tool_search"),lt=R.item.execution==="server";G[R.output_index]={toolName:qe,toolCallId:oe,toolSearchExecution:(Te=R.item.execution)!=null?Te:"server"},lt&&S.enqueue({type:"tool-input-start",id:oe,toolName:qe,providerExecuted:!0})}else if(R.item.type!=="tool_search_output"){if(!(R.item.type==="mcp_call"||R.item.type==="mcp_list_tools"||R.item.type==="mcp_approval_request"))if(R.item.type==="apply_patch_call"){const{call_id:oe,operation:qe}=R.item;if(G[R.output_index]={toolName:u.toCustomToolName("apply_patch"),toolCallId:oe,applyPatch:{hasDiff:qe.type==="delete_file",endEmitted:qe.type==="delete_file"}},S.enqueue({type:"tool-input-start",id:oe,toolName:u.toCustomToolName("apply_patch")}),qe.type==="delete_file"){const lt=JSON.stringify({callId:oe,operation:qe});S.enqueue({type:"tool-input-delta",id:oe,delta:lt}),S.enqueue({type:"tool-input-end",id:oe})}else S.enqueue({type:"tool-input-delta",id:oe,delta:`{"callId":"${ur(oe)}","operation":{"type":"${ur(qe.type)}","path":"${ur(qe.path)}","diff":"`})}else R.item.type==="shell_call"?G[R.output_index]={toolName:u.toCustomToolName("shell"),toolCallId:R.item.call_id}:R.item.type==="shell_call_output"||(R.item.type==="message"?(Z.splice(0,Z.length),z=(ye=R.item.phase)!=null?ye:void 0,S.enqueue({type:"text-start",id:R.item.id,providerMetadata:{[m]:{itemId:R.item.id,...R.item.phase!=null&&{phase:R.item.phase}}}})):La(R)&&R.item.type==="reasoning"&&(K[R.item.id]={encryptedContent:R.item.encrypted_content,summaryParts:{0:"active"}},S.enqueue({type:"reasoning-start",id:`${R.item.id}:0`,providerMetadata:{[m]:{itemId:R.item.id,reasoningEncryptedContent:(re=R.item.encrypted_content)!=null?re:null}}})))}}else if(p2(R)){if(R.item.type==="message"){const oe=(xe=R.item.phase)!=null?xe:z;z=void 0,S.enqueue({type:"text-end",id:R.item.id,providerMetadata:{[m]:{itemId:R.item.id,...oe!=null&&{phase:oe},...Z.length>0&&{annotations:Z}}}})}else if(R.item.type==="function_call")G[R.output_index]=void 0,ee=!0,S.enqueue({type:"tool-input-end",id:R.item.call_id}),S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:R.item.name,input:R.item.arguments,providerMetadata:{[m]:{itemId:R.item.id}}});else if(R.item.type==="custom_tool_call"){G[R.output_index]=void 0,ee=!0;const oe=u.toCustomToolName(R.item.name);S.enqueue({type:"tool-input-end",id:R.item.call_id}),S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:oe,input:JSON.stringify(R.item.input),providerMetadata:{[m]:{itemId:R.item.id}}})}else if(R.item.type==="web_search_call")G[R.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName(c??"web_search"),result:Fa(R.item.action)});else if(R.item.type==="computer_call")G[R.output_index]=void 0,S.enqueue({type:"tool-input-end",id:R.item.id}),S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:R.item.status||"completed"}});else if(R.item.type==="file_search_call")G[R.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("file_search"),result:{queries:R.item.queries,results:($=(Me=R.item.results)==null?void 0:Me.map(oe=>({attributes:oe.attributes,fileId:oe.file_id,filename:oe.filename,score:oe.score,text:oe.text})))!=null?$:null}});else if(R.item.type==="code_interpreter_call")G[R.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("code_interpreter"),result:{outputs:R.item.outputs}});else if(R.item.type==="image_generation_call")S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("image_generation"),result:{result:R.item.result}});else if(R.item.type==="tool_search_call"){const oe=G[R.output_index],qe=R.item.execution==="server";if(oe!=null){const lt=qe?oe.toolCallId:(ge=R.item.call_id)!=null?ge:R.item.id;qe?U.push(lt):S.enqueue({type:"tool-input-start",id:lt,toolName:oe.toolName}),S.enqueue({type:"tool-input-end",id:lt}),S.enqueue({type:"tool-call",toolCallId:lt,toolName:oe.toolName,input:JSON.stringify({arguments:R.item.arguments,call_id:qe?null:lt}),...qe?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:R.item.id}}})}G[R.output_index]=void 0}else if(R.item.type==="tool_search_output"){const oe=(Q=(ne=R.item.call_id)!=null?ne:U.shift())!=null?Q:R.item.id;S.enqueue({type:"tool-result",toolCallId:oe,toolName:u.toCustomToolName("tool_search"),result:{tools:R.item.tools},providerMetadata:{[m]:{itemId:R.item.id}}})}else if(R.item.type==="mcp_call"){G[R.output_index]=void 0;const oe=(me=R.item.approval_request_id)!=null?me:void 0,qe=oe!=null&&(ie=(fe=P.get(oe))!=null?fe:v[oe])!=null?ie:R.item.id,lt=`mcp.${R.item.name}`;S.enqueue({type:"tool-call",toolCallId:qe,toolName:lt,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-result",toolCallId:qe,toolName:lt,result:{type:"call",serverLabel:R.item.server_label,name:R.item.name,arguments:R.item.arguments,...R.item.output!=null?{output:R.item.output}:{},...R.item.error!=null?{error:R.item.error}:{}},providerMetadata:{[m]:{itemId:R.item.id}}})}else if(R.item.type==="mcp_list_tools")G[R.output_index]=void 0;else if(R.item.type==="apply_patch_call"){const oe=G[R.output_index];oe?.applyPatch&&!oe.applyPatch.endEmitted&&R.item.operation.type!=="delete_file"&&(oe.applyPatch.hasDiff||S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.item.operation.diff)}),S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:'"}}'}),S.enqueue({type:"tool-input-end",id:oe.toolCallId}),oe.applyPatch.endEmitted=!0),oe&&R.item.status==="completed"&&S.enqueue({type:"tool-call",toolCallId:oe.toolCallId,toolName:u.toCustomToolName("apply_patch"),input:JSON.stringify({callId:R.item.call_id,operation:R.item.operation}),providerMetadata:{[m]:{itemId:R.item.id}}}),G[R.output_index]=void 0}else if(R.item.type==="mcp_approval_request"){G[R.output_index]=void 0;const oe=(Ee=(vt=(pe=A.config).generateId)==null?void 0:vt.call(pe))!=null?Ee:Kt(),qe=(Tt=R.item.approval_request_id)!=null?Tt:R.item.id;P.set(qe,oe);const lt=`mcp.${R.item.name}`;S.enqueue({type:"tool-call",toolCallId:oe,toolName:lt,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-approval-request",approvalId:qe,toolCallId:oe})}else if(R.item.type==="local_shell_call")G[R.output_index]=void 0,S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:u.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:R.item.action.command,timeoutMs:R.item.action.timeout_ms,user:R.item.action.user,workingDirectory:R.item.action.working_directory,env:R.item.action.env}}),providerMetadata:{[m]:{itemId:R.item.id}}});else if(R.item.type==="shell_call")G[R.output_index]=void 0,S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:u.toCustomToolName("shell"),input:JSON.stringify({action:{commands:R.item.action.commands}}),...g&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:R.item.id}}});else if(R.item.type==="shell_call_output")S.enqueue({type:"tool-result",toolCallId:R.item.call_id,toolName:u.toCustomToolName("shell"),result:{output:R.item.output.map(oe=>({stdout:oe.stdout,stderr:oe.stderr,outcome:oe.outcome.type==="exit"?{type:"exit",exitCode:oe.outcome.exit_code}:{type:"timeout"}}))}});else if(R.item.type==="reasoning"){const oe=K[R.item.id],qe=Object.entries(oe.summaryParts).filter(([lt,xr])=>xr==="active"||xr==="can-conclude").map(([lt])=>lt);for(const lt of qe)S.enqueue({type:"reasoning-end",id:`${R.item.id}:${lt}`,providerMetadata:{[m]:{itemId:R.item.id,reasoningEncryptedContent:(Ce=R.item.encrypted_content)!=null?Ce:null}}});delete K[R.item.id]}}else if(y2(R)){const oe=G[R.output_index];oe!=null&&S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:R.delta})}else if(w2(R)){const oe=G[R.output_index];oe!=null&&S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:R.delta})}else if(b2(R)){const oe=G[R.output_index];oe?.applyPatch&&(S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.delta)}),oe.applyPatch.hasDiff=!0)}else if(E2(R)){const oe=G[R.output_index];oe?.applyPatch&&!oe.applyPatch.endEmitted&&(oe.applyPatch.hasDiff||(S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.diff)}),oe.applyPatch.hasDiff=!0),S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:'"}}'}),S.enqueue({type:"tool-input-end",id:oe.toolCallId}),oe.applyPatch.endEmitted=!0)}else if(_2(R))S.enqueue({type:"tool-result",toolCallId:R.item_id,toolName:u.toCustomToolName("image_generation"),result:{result:R.partial_image_b64},preliminary:!0});else if(v2(R)){const oe=G[R.output_index];oe!=null&&S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.delta)})}else if(C2(R)){const oe=G[R.output_index];oe!=null&&(S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:'"}'}),S.enqueue({type:"tool-input-end",id:oe.toolCallId}),S.enqueue({type:"tool-call",toolCallId:oe.toolCallId,toolName:u.toCustomToolName("code_interpreter"),input:JSON.stringify({code:R.code,containerId:oe.codeInterpreter.containerId}),providerExecuted:!0}))}else if(x2(R))B=R.response.id,S.enqueue({type:"response-metadata",id:R.response.id,timestamp:new Date(R.response.created_at*1e3),modelId:R.response.model});else if(h2(R))S.enqueue({type:"text-delta",id:R.item_id,delta:R.delta}),(Ue=(sn=t.providerOptions)==null?void 0:sn[m])!=null&&Ue.logprobs&&R.logprobs&&D.push(R.logprobs);else if(R.type==="response.reasoning_summary_part.added"){if(R.summary_index>0){const oe=K[R.item_id];oe.summaryParts[R.summary_index]="active";for(const qe of Object.keys(oe.summaryParts))oe.summaryParts[qe]==="can-conclude"&&(S.enqueue({type:"reasoning-end",id:`${R.item_id}:${qe}`,providerMetadata:{[m]:{itemId:R.item_id}}}),oe.summaryParts[qe]="concluded");S.enqueue({type:"reasoning-start",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[m]:{itemId:R.item_id,reasoningEncryptedContent:(de=(Ht=K[R.item_id])==null?void 0:Ht.encryptedContent)!=null?de:null}}})}}else if(R.type==="response.reasoning_summary_text.delta")S.enqueue({type:"reasoning-delta",id:`${R.item_id}:${R.summary_index}`,delta:R.delta,providerMetadata:{[m]:{itemId:R.item_id}}});else if(R.type==="response.reasoning_summary_part.done")f?(S.enqueue({type:"reasoning-end",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[m]:{itemId:R.item_id}}}),K[R.item_id].summaryParts[R.summary_index]="concluded"):K[R.item_id].summaryParts[R.summary_index]="can-conclude";else if(m2(R))O={unified:uo({finishReason:(Oe=R.response.incomplete_details)==null?void 0:Oe.reason,hasFunctionCall:ee}),raw:(be=(yt=R.response.incomplete_details)==null?void 0:yt.reason)!=null?be:void 0},M=R.response.usage,typeof R.response.service_tier=="string"&&(V=R.response.service_tier);else if(g2(R)){const oe=(Xt=R.response.incomplete_details)==null?void 0:Xt.reason;O={unified:oe?uo({finishReason:oe,hasFunctionCall:ee}):"error",raw:oe??"error"},M=(Wt=R.response.usage)!=null?Wt:void 0}else A2(R)?(Z.push(R.annotation),R.annotation.type==="url_citation"?S.enqueue({type:"source",sourceType:"url",id:(Xe=(Ct=(In=A.config).generateId)==null?void 0:Ct.call(In))!=null?Xe:Kt(),url:R.annotation.url,title:R.annotation.title}):R.annotation.type==="file_citation"?S.enqueue({type:"source",sourceType:"document",id:(ve=(Sn=(Ze=A.config).generateId)==null?void 0:Sn.call(Ze))!=null?ve:Kt(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[m]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}}):R.annotation.type==="container_file_citation"?S.enqueue({type:"source",sourceType:"document",id:(Jt=(Hn=(Bn=A.config).generateId)==null?void 0:Hn.call(Bn))!=null?Jt:Kt(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[m]:{type:R.annotation.type,fileId:R.annotation.file_id,containerId:R.annotation.container_id}}}):R.annotation.type==="file_path"&&S.enqueue({type:"source",sourceType:"document",id:(rr=(Bt=(Wn=A.config).generateId)==null?void 0:Bt.call(Wn))!=null?rr:Kt(),mediaType:"application/octet-stream",title:R.annotation.file_id,filename:R.annotation.file_id,providerMetadata:{[m]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}})):I2(R)&&S.enqueue({type:"error",error:R})},flush(J){const S={[m]:{responseId:B,...D.length>0?{logprobs:D}:{},...V!==void 0?{serviceTier:V}:{}}};J.enqueue({type:"finish",finishReason:O,usage:Ma(M),providerMetadata:S})}})),request:{body:r},response:{headers:C}}}};function h2(t){return t.type==="response.output_text.delta"}function p2(t){return t.type==="response.output_item.done"}function m2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function g2(t){return t.type==="response.failed"}function x2(t){return t.type==="response.created"}function y2(t){return t.type==="response.function_call_arguments.delta"}function w2(t){return t.type==="response.custom_tool_call_input.delta"}function _2(t){return t.type==="response.image_generation_call.partial_image"}function v2(t){return t.type==="response.code_interpreter_call_code.delta"}function C2(t){return t.type==="response.code_interpreter_call_code.done"}function b2(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function E2(t){return t.type==="response.apply_patch_call_operation_diff.done"}function La(t){return t.type==="response.output_item.added"}function A2(t){return t.type==="response.output_text.annotation.added"}function I2(t){return t.type==="error"}function Fa(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function ur(t){return JSON.stringify(t).slice(1,-1)}var S2=Be(()=>Pe(T({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),T2=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:r="alloy",outputFormat:o="mp3",speed:c,instructions:u,language:f,providerOptions:m}){const g=[],C=await Zn({provider:"openai",providerOptions:m,schema:S2}),x={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:u};if(o&&(["mp3","opus","aac","flac","wav","pcm"].includes(o)?x.response_format=o:g.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${o}. Using mp3 instead.`})),C){const A={};for(const v in A){const P=A[v];P!==void 0&&(x[v]=P)}}return f&&g.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:x,warnings:g}}async doGenerate(t){var r,o,c;const u=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{requestBody:f,warnings:m}=await this.getArgs(t),{value:g,responseHeaders:C,rawValue:x}=await $n({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:f,failedResponseHandler:An,successfulResponseHandler:Jm(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:g,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:u,modelId:this.modelId,headers:C,body:x}}}},N2=Be(()=>Pe(T({text:w(),language:w().nullish(),duration:j().nullish(),words:ue(T({word:w(),start:j(),end:j()})).nullish(),segments:ue(T({id:j(),seek:j(),start:j(),end:j(),text:w(),tokens:ue(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),O2=Be(()=>Pe(T({include:ue(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:ue(Se(["word","segment"])).default(["segment"]).optional()}))),Ua={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},k2=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:r,providerOptions:o}){const c=[],u=await Zn({provider:"openai",providerOptions:o,schema:O2}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([Ho(t)]);f.append("model",this.modelId);const g=Jp(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${g}`),u){const C={include:u.include,language:u.language,prompt:u.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:u.temperature,timestamp_granularities:u.timestampGranularities};for(const[x,A]of Object.entries(C))if(A!=null)if(Array.isArray(A))for(const v of A)f.append(`${x}[]`,String(v));else f.append(x,String(A))}return{formData:f,warnings:c}}async doGenerate(t){var r,o,c,u,f,m,g,C;const x=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{formData:A,warnings:v}=await this.getArgs(t),{value:P,responseHeaders:O,rawValue:M}=await ou({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),formData:A,failedResponseHandler:An,successfulResponseHandler:hr(N2),abortSignal:t.abortSignal,fetch:this.config.fetch}),D=P.language!=null&&P.language in Ua?Ua[P.language]:void 0;return{text:P.text,segments:(g=(m=(u=P.segments)==null?void 0:u.map(B=>({text:B.text,startSecond:B.start,endSecond:B.end})))!=null?m:(f=P.words)==null?void 0:f.map(B=>({text:B.word,startSecond:B.start,endSecond:B.end})))!=null?g:[],language:D,durationInSeconds:(C=P.duration)!=null?C:void 0,warnings:v,response:{timestamp:x,modelId:this.modelId,headers:O,body:M}}}},R2="3.0.52";function gu(t={}){var r,o;const c=(r=Qm(Kp({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",u=(o=t.name)!=null?o:"openai",f=()=>Jc({Authorization:`Bearer ${Yp({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${R2}`),m=D=>new og(D,{provider:`${u}.chat`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),g=D=>new cg(D,{provider:`${u}.completion`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),C=D=>new fg(D,{provider:`${u}.embedding`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),x=D=>new gg(D,{provider:`${u}.image`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),A=D=>new k2(D,{provider:`${u}.transcription`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),v=D=>new T2(D,{provider:`${u}.speech`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),P=D=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return O(D)},O=D=>new f2(D,{provider:`${u}.responses`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),M=function(D){return P(D)};return M.specificationVersion="v3",M.languageModel=P,M.chat=m,M.completion=g,M.responses=O,M.embedding=C,M.embeddingModel=C,M.textEmbedding=C,M.textEmbeddingModel=C,M.image=x,M.imageModel=x,M.transcription=A,M.transcriptionModel=A,M.speech=v,M.speechModel=v,M.tools=i2,M}gu();const M2={deepseek:{prompt:{strategy:"append",id:"5ed1b9071c15d1ed59b5827ea5dcabd4",params:{customComponents:[{name:"选择用户组件",description:"选择用户组件,用于选择用户,支持模糊搜索",component:"TinyUser",schema:{properties:[{property:"modelValue",label:"用户绑定工号",required:!0,description:"用户的工号,双向绑定值",type:"string"},{property:"valueField",label:"值字段",required:!0,description:"用户工号值的绑定字段",type:"string"}]}}],customExamples:[{name:"选择用户示例",schema:{componentName:"Page",state:{reviewer:""},children:[{componentName:"h3",props:{},children:"输入用户名搜索工号并选择用户"},{componentName:"TinyUser",props:{modelValue:{type:"JSExpression",model:!0,value:"this.state.reviewer"},valueField:"uid"}},{componentName:"TinyButton",props:{text:"提交"}}]}}],customActions:[{name:"continueChat",description:"继续对话, 用于表单的提交按钮等",parameters:{type:"object",properties:{message:{type:"string",description:"对话消息,可以是按钮文本等,也可以是其他内容"}}}}]}}}};class D2{constructor(r={}){this.option=r}async traverse(r){const o=_.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",o),(async()=>{let u,f,m,g,C;for await(const x of r.fullStream)switch(this.option.debug&&console.log("【stream-debug】 "+(new Date().getTime()/1e3).toString().slice(-6)+x.type,x),x.type){case"start":u=_.reactive({running:!0,steps:[]}),o.value=u,this.option.onStart?.(u);break;case"start-step":f=_.reactive({running:!0,contents:[],request:x.request}),u.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":m=_.reactive({type:"reasoning",id:x.id,running:!0,text:""}),f.contents.push(m),this.option.onReasoning?.(m);break;case"reasoning-delta":m.text+=x.text;break;case"reasoning-end":m.running=!1;break;case"text-start":g=_.reactive({type:"text",id:x.id,running:!0,text:""}),f.contents.push(g),this.option.onText?.(g);break;case"text-delta":g.text+=x.text;break;case"text-end":g.running=!1;break;case"tool-input-start":C=_.reactive({type:"tool",running:!0,id:x.id,toolCallId:x.id,title:"",toolName:x.toolName,dynamic:x.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(C),this.option.onTool?.(C);break;case"tool-input-delta":C.inputStr+=x.delta;break;case"tool-input-end":break;case"tool-call":C.input=x.input;break;case"tool-result":C.output=x.output,C.running=!1;break;case"tool-error":C.error=x.error,C.running=!1;break;case"finish-step":f.running=!1,f.finishReason=x.finishReason,f.usage=x.usage;break;case"finish":u.running=!1,u.finishReason=x.finishReason,u.totalUsage=x.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":u&&(u.running=!1,u.error=x.error,u.finishReason="error"),this.option.onFinish?.();break;case"abort":u&&(u.running=!1,u.error={message:x.reason},u.finishReason="other"),this.option.onFinish?.();break}})(),o}}function P2(t){const r=[];let o=0;for(;o<t.length;){const c="```schemaJson",u=t.indexOf(c,o),f=c.length;if(u===-1){const x=t.slice(o).trim();x&&r.push({type:"markdown",content:x});break}const m=t.slice(o,u).trim();m&&r.push({type:"markdown",content:m});const g=t.indexOf("```",u+f);let C;g===-1?(C=t.slice(u+f).trim(),o=t.length):(C=t.slice(u+f,g).trim(),o=g+3),r.push({type:"schema-card",content:C})}return r}class B2{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
55
+ ${r}:`]}}function Pa({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i!=null?new Date(i*1e3):void 0}}function Ba(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var kg=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),Rg=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w().nullish(),index:j(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Qi]))),La=Fe(()=>Le(N({echo:Mt().optional(),logitBias:wt(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:st([Mt(),j()]).optional()}))),Mg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=r}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,tools:g,toolChoice:E,seed:A,providerOptions:D}){const T=[],S={...await An({provider:"openai",providerOptions:D,schema:La}),...await An({provider:this.providerOptionsName,providerOptions:D,schema:La})};d!=null&&T.push({type:"unsupported",feature:"topK"}),g?.length&&T.push({type:"unsupported",feature:"tools"}),E!=null&&T.push({type:"unsupported",feature:"toolChoice"}),v!=null&&v.type!=="text"&&T.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:P,stopSequences:M}=Og({prompt:t}),ee=[...M??[],...x??[]];return{args:{model:this.modelId,echo:S.echo,logit_bias:S.logitBias,logprobs:S?.logprobs===!0?0:S?.logprobs===!1?void 0:S?.logprobs,suffix:S.suffix,user:S.user,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,seed:A,prompt:P,stop:ee.length>0?ee:void 0},warnings:T}}async doGenerate(t){var r;const{args:i,warnings:c}=await this.getArgs(t),{responseHeaders:d,value:f,rawValue:m}=await Zn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:i,failedResponseHandler:En,successfulResponseHandler:mr(kg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=f.choices[0],v={openai:{}};return x.logprobs!=null&&(v.openai.logprobs=x.logprobs),{content:[{type:"text",text:x.text}],usage:Da(f.usage),finishReason:{unified:Ba(x.finish_reason),raw:(r=x.finish_reason)!=null?r:void 0},request:{body:i},response:{...Pa(f),headers:d,body:m},providerMetadata:v,warnings:c}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Rg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:T=>"error"in T?T.error:void 0,isOutputChunk:Dg,url:d,requestBodyValues:c,responseHeaders:f});let v={unified:"other",raw:void 0};const g={openai:{}};let E,A=!0;return{stream:x.pipeThrough(new TransformStream({start(T){T.enqueue({type:"stream-start",warnings:i})},transform(T,S){if(t.includeRawChunks&&S.enqueue({type:"raw",rawValue:T.rawValue}),!T.success){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:T.error});return}const P=T.value;if("error"in P){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:P.error});return}A&&(A=!1,S.enqueue({type:"response-metadata",...Pa(P)}),S.enqueue({type:"text-start",id:"0"})),P.usage!=null&&(E=P.usage);const M=P.choices[0];M?.finish_reason!=null&&(v={unified:Ba(M.finish_reason),raw:M.finish_reason}),M?.logprobs!=null&&(g.openai.logprobs=M.logprobs),M?.text!=null&&M.text.length>0&&S.enqueue({type:"text-delta",id:"0",delta:M.text})},flush(T){A||T.enqueue({type:"text-end",id:"0"}),T.enqueue({type:"finish",finishReason:v,providerMetadata:g,usage:Da(E)})}})),request:{body:c},response:{headers:f}}}};function Dg(t){return!("error"in t)&&t.choices.some(r=>r.text.length>0)}var Pg=Fe(()=>Le(N({dimensions:j().optional(),user:w().optional()}))),Bg=Fe(()=>Le(N({data:ue(N({embedding:ue(j())})),usage:N({prompt_tokens:j()}).nullish()}))),Lg=class{constructor(t,r){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=r}get provider(){return this.config.provider}async doEmbed({values:t,headers:r,abortSignal:i,providerOptions:c}){var d;if(t.length>this.maxEmbeddingsPerCall)throw new jp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(d=await An({provider:"openai",providerOptions:c,schema:Pg}))!=null?d:{},{responseHeaders:m,value:x,rawValue:v}=await Zn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:bn(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:En,successfulResponseHandler:mr(Bg),abortSignal:i,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map(g=>g.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:m,body:v}}}},Fa=Fe(()=>Le(N({created:j().nullish(),data:ue(N({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:N({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:N({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),Fg={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},Ug=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function zg(t){return Ug.some(r=>t.startsWith(r))}var vu=N({quality:Ae(["standard","hd","low","medium","high","auto"]).optional(),background:Ae(["transparent","opaque","auto"]).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),outputCompression:j().int().min(0).max(100).optional(),user:w().optional()}),Vg=Fe(()=>Le(vu.extend({style:Ae(["vivid","natural"]).optional(),moderation:Ae(["auto","low"]).optional()}))),Zg=Fe(()=>Le(vu.extend({inputFidelity:Ae(["high","low"]).optional()}))),$g=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=Fg[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:r,mask:i,n:c,size:d,aspectRatio:f,seed:m,providerOptions:x,headers:v,abortSignal:g}){var E,A,D,T,S,P,M,ee,$,F,re;const Z=[];f!=null&&Z.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&Z.push({type:"unsupported",feature:"seed"});const B=(D=(A=(E=this.config._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E))!=null?D:new Date;if(r!=null){const we=(T=await An({provider:"openai",providerOptions:x,schema:Zg}))!=null?T:{},{value:G,responseHeaders:me}=await xu({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:bn(this.config.headers(),v),formData:Jp({model:this.modelId,prompt:t,image:await Promise.all(r.map(fe=>fe.type==="file"?new Blob([fe.data instanceof Uint8Array?new Blob([fe.data],{type:fe.mediaType}):new Blob([qi(fe.data)],{type:fe.mediaType})],{type:fe.mediaType}):lu(fe.url))),mask:i!=null?await jg(i):void 0,n:c,size:d,quality:we.quality,background:we.background,output_format:we.outputFormat,output_compression:we.outputCompression,input_fidelity:we.inputFidelity,user:we.user}),failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:G.data.map(fe=>fe.b64_json),warnings:Z,usage:G.usage!=null?{inputTokens:(S=G.usage.input_tokens)!=null?S:void 0,outputTokens:(P=G.usage.output_tokens)!=null?P:void 0,totalTokens:(M=G.usage.total_tokens)!=null?M:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:me},providerMetadata:{openai:{images:G.data.map((fe,te)=>{var q,ke,le,Te,Je,xe;return{...fe.revised_prompt?{revisedPrompt:fe.revised_prompt}:{},created:(q=G.created)!=null?q:void 0,size:(ke=G.size)!=null?ke:void 0,quality:(le=G.quality)!=null?le:void 0,background:(Te=G.background)!=null?Te:void 0,outputFormat:(Je=G.output_format)!=null?Je:void 0,...Ua((xe=G.usage)==null?void 0:xe.input_tokens_details,te,G.data.length)}})}}}}const L=(ee=await An({provider:"openai",providerOptions:x,schema:Vg}))!=null?ee:{},{value:W,responseHeaders:z}=await Zn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:bn(this.config.headers(),v),body:{model:this.modelId,prompt:t,n:c,size:d,quality:L.quality,style:L.style,background:L.background,moderation:L.moderation,output_format:L.outputFormat,output_compression:L.outputCompression,user:L.user,...zg(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:W.data.map(we=>we.b64_json),warnings:Z,usage:W.usage!=null?{inputTokens:($=W.usage.input_tokens)!=null?$:void 0,outputTokens:(F=W.usage.output_tokens)!=null?F:void 0,totalTokens:(re=W.usage.total_tokens)!=null?re:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:z},providerMetadata:{openai:{images:W.data.map((we,G)=>{var me,fe,te,q,ke,le;return{...we.revised_prompt?{revisedPrompt:we.revised_prompt}:{},created:(me=W.created)!=null?me:void 0,size:(fe=W.size)!=null?fe:void 0,quality:(te=W.quality)!=null?te:void 0,background:(q=W.background)!=null?q:void 0,outputFormat:(ke=W.output_format)!=null?ke:void 0,...Ua((le=W.usage)==null?void 0:le.input_tokens_details,G,W.data.length)}})}}}}};function Ua(t,r,i){if(t==null)return{};const c={};if(t.image_tokens!=null){const d=Math.floor(t.image_tokens/i),f=t.image_tokens-d*(i-1);c.imageTokens=r===i-1?f:d}if(t.text_tokens!=null){const d=Math.floor(t.text_tokens/i),f=t.text_tokens-d*(i-1);c.textTokens=r===i-1?f:d}return c}async function jg(t){if(!t)return;if(t.type==="url")return lu(t.url);const r=t.data instanceof Uint8Array?t.data:qi(t.data);return new Blob([r],{type:t.mediaType})}var Cu=Fe(()=>Le(N({callId:w(),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}))),bu=Fe(()=>Le(N({status:Ae(["completed","failed"]),output:w().optional()}))),Hg=Dn({id:"openai.apply_patch",inputSchema:Cu,outputSchema:bu}),Wg=Hg,Gg=Fe(()=>Le(N({code:w().nullish(),containerId:w()}))),qg=Fe(()=>Le(N({outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullish()}))),Xg=Fe(()=>Le(N({container:st([w(),N({fileIds:ue(w()).optional()})]).optional()}))),Yg=Dn({id:"openai.code_interpreter",inputSchema:Gg,outputSchema:qg}),Kg=(t={})=>Yg(t),Jg=Fe(()=>Le(N({name:w(),description:w().optional(),format:st([N({type:Y("grammar"),syntax:Ae(["regex","lark"]),definition:w()}),N({type:Y("text")})]).optional()}))),Qg=Fe(()=>Le(w())),e2=pg({id:"openai.custom",inputSchema:Qg}),t2=t=>e2(t),Au=N({key:w(),type:Ae(["eq","ne","gt","gte","lt","lte","in","nin"]),value:st([w(),j(),Mt(),ue(w())])}),Eu=N({type:Ae(["and","or"]),filters:ue(st([Au,Wi(()=>Eu)]))}),n2=Fe(()=>Le(N({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:N({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:st([Au,Eu]).optional()}))),r2=Fe(()=>Le(N({queries:ue(w()),results:ue(N({attributes:wt(w(),Cn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),o2=Dn({id:"openai.file_search",inputSchema:N({}),outputSchema:r2}),i2=Fe(()=>Le(N({background:Ae(["auto","opaque","transparent"]).optional(),inputFidelity:Ae(["low","high"]).optional(),inputImageMask:N({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Ae(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Ae(["auto","low","medium","high"]).optional(),size:Ae(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),s2=Fe(()=>Le(N({}))),a2=Fe(()=>Le(N({result:w()}))),l2=Dn({id:"openai.image_generation",inputSchema:s2,outputSchema:a2}),c2=(t={})=>l2(t),Iu=Fe(()=>Le(N({action:N({type:Y("exec"),command:ue(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:wt(w(),w()).optional()})}))),Su=Fe(()=>Le(N({output:w()}))),u2=Dn({id:"openai.local_shell",inputSchema:Iu,outputSchema:Su}),Tu=Fe(()=>Le(N({action:N({commands:ue(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),ki=Fe(()=>Le(N({output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exitCode:j()})])}))}))),d2=ue(mt("type",[N({type:Y("skillReference"),skillId:w(),version:w().optional()}),N({type:Y("inline"),name:w(),description:w(),source:N({type:Y("base64"),mediaType:Y("application/zip"),data:w()})})])).optional(),f2=Fe(()=>Le(N({environment:st([N({type:Y("containerAuto"),fileIds:ue(w()).optional(),memoryLimit:Ae(["1g","4g","16g","64g"]).optional(),networkPolicy:mt("type",[N({type:Y("disabled")}),N({type:Y("allowlist"),allowedDomains:ue(w()),domainSecrets:ue(N({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:d2}),N({type:Y("containerReference"),containerId:w()}),N({type:Y("local").optional(),skills:ue(N({name:w(),description:w(),path:w()})).optional()})]).optional()}))),h2=Dn({id:"openai.shell",inputSchema:Tu,outputSchema:ki}),p2=Fe(()=>Le(N({execution:Ae(["server","client"]).optional(),description:w().optional(),parameters:wt(w(),Cn()).optional()}))),Ri=Fe(()=>Le(N({arguments:Cn().optional(),call_id:w().nullish()}))),Mi=Fe(()=>Le(N({tools:ue(wt(w(),Cn()))}))),m2=Dn({id:"openai.tool_search",inputSchema:Ri,outputSchema:Mi}),g2=(t={})=>m2(t),x2=Fe(()=>Le(N({externalWebAccess:Mt().optional(),filters:N({allowedDomains:ue(w()).optional()}).optional(),searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),y2=Fe(()=>Le(N({}))),w2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional(),queries:ue(w()).optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).optional()}))),_2=Dn({id:"openai.web_search",inputSchema:y2,outputSchema:w2}),v2=(t={})=>_2(t),C2=Fe(()=>Le(N({searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),b2=Fe(()=>Le(N({}))),A2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),E2=Dn({id:"openai.web_search_preview",inputSchema:b2,outputSchema:A2}),Di=Wi(()=>st([w(),j(),Mt(),bc(),ue(Di),wt(w(),Di)])),I2=Fe(()=>Le(N({serverLabel:w(),allowedTools:st([ue(w()),N({readOnly:Mt().optional(),toolNames:ue(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:wt(w(),w()).optional(),requireApproval:st([Ae(["always","never"]),N({never:N({toolNames:ue(w()).optional()}).optional()})]).optional(),serverDescription:w().optional(),serverUrl:w().optional()}).refine(t=>t.serverUrl!=null||t.connectorId!=null,"One of serverUrl or connectorId must be provided."))),S2=Fe(()=>Le(N({}))),T2=Fe(()=>Le(N({type:Y("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:st([w(),Di]).optional()}))),N2=Dn({id:"openai.mcp",inputSchema:S2,outputSchema:T2}),O2=t=>N2(t),k2={applyPatch:Wg,customTool:t2,codeInterpreter:Kg,fileSearch:o2,imageGeneration:c2,localShell:u2,shell:h2,webSearchPreview:E2,webSearch:v2,mcp:O2,toolSearch:g2};function za(t){var r,i,c,d,f,m;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const x=t.input_tokens,v=t.output_tokens,g=(i=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?i:0,E=(d=(c=t.input_tokens_details)==null?void 0:c.cache_write_tokens)!=null?d:void 0,A=(m=(f=t.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:0;return{inputTokens:{total:x,noCache:x-g-(E??0),cacheRead:g,cacheWrite:E},outputTokens:{total:v,text:v-A,reasoning:A},raw:t}}function R2(t){return JSON.stringify(t===void 0?{}:t)}function Nr(t,r){var i;return(i=t?.[r])==null?void 0:i.promptCacheBreakpoint}function Va(t,r){return r?r.some(i=>t.startsWith(i)):!1}async function M2({prompt:t,toolNameMapping:r,systemMessageMode:i,providerOptionsName:c,fileIdPrefixes:d,passThroughUnsupportedFiles:f=!1,store:m,hasConversation:x=!1,hasPreviousResponseId:v=!1,hasLocalShellTool:g=!1,hasShellTool:E=!1,hasApplyPatchTool:A=!1,customProviderToolNames:D}){var T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe,te,q,ke,le,Te,Je;let xe=[];const $e=[],Ue=new Set;for(const{role:Ze,content:qe,providerOptions:ze}of t)switch(Ze){case"system":{switch(i){case"system":{const ie=Nr(ze,c);xe.push({role:"system",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"developer":{const ie=Nr(ze,c);xe.push({role:"developer",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"remove":{$e.push({type:"other",message:"system messages are removed for this model"});break}default:{const ie=i;throw new Error(`Unsupported system message mode: ${ie}`)}}break}case"user":{xe.push({role:"user",content:qe.map((ie,de)=>{var _e,Pe,ae;switch(ie.type){case"text":{const J=Nr(ie.providerOptions,c);return{type:"input_text",text:ie.text,...J!=null&&{prompt_cache_breakpoint:J}}}case"file":{const J=Nr(ie.providerOptions,c),ye=ie.mediaType==="image/*"?"image/jpeg":ie.mediaType;if(ye.startsWith("image/"))return{type:"input_image",...ie.data instanceof URL?{image_url:ie.data.toString()}:typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{image_url:`data:${ye};base64,${kr(ie.data)}`},detail:(Pe=(_e=ie.providerOptions)==null?void 0:_e[c])==null?void 0:Pe.imageDetail,...J!=null&&{prompt_cache_breakpoint:J}};if(ie.data instanceof URL)return{type:"input_file",file_url:ie.data.toString(),...J!=null&&{prompt_cache_breakpoint:J}};if(ye!=="application/pdf"&&!f)throw new Mn({functionality:`file part media type ${ye}`});return{type:"input_file",...typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{filename:(ae=ie.filename)!=null?ae:ye==="application/pdf"?`part-${de}.pdf`:`part-${de}`,file_data:`data:${ye};base64,${kr(ie.data)}`},...J!=null&&{prompt_cache_breakpoint:J}}}}})});break}case"assistant":{const ie={};for(const de of qe)switch(de.type){case"text":{const _e=(T=de.providerOptions)==null?void 0:T[c],Pe=_e?.itemId,ae=_e?.phase;if(x&&Pe!=null)break;if(m&&Pe!=null){xe.push({type:"item_reference",id:Pe});break}xe.push({role:"assistant",content:[{type:"output_text",text:de.text}],id:Pe,...ae!=null&&{phase:ae}});break}case"tool-call":{const _e=($=(P=(S=de.providerOptions)==null?void 0:S[c])==null?void 0:P.itemId)!=null?$:(ee=(M=de.providerMetadata)==null?void 0:M[c])==null?void 0:ee.itemId,Pe=(L=(re=(F=de.providerOptions)==null?void 0:F[c])==null?void 0:re.namespace)!=null?L:(B=(Z=de.providerMetadata)==null?void 0:Z[c])==null?void 0:B.namespace;if(x&&_e!=null)break;const ae=r.toProviderToolName(de.toolName);if(ae==="tool_search"){if(m&&_e!=null){xe.push({type:"item_reference",id:_e});break}const ye=typeof de.input=="string"?await mu({text:de.input,schema:Ri}):await Dt({value:de.input,schema:Ri}),Se=ye.call_id!=null?"client":"server";xe.push({type:"tool_search_call",id:_e??de.toolCallId,execution:Se,call_id:(W=ye.call_id)!=null?W:null,status:"completed",arguments:ye.arguments});break}if(de.providerExecuted){m&&_e!=null&&xe.push({type:"item_reference",id:_e});break}if(v&&m&&_e!=null)break;const J=g&&ae==="local_shell"||E&&ae==="shell"||A&&ae==="apply_patch"||((z=D?.has(ae))!=null?z:!1);if(m&&_e!=null&&J){xe.push({type:"item_reference",id:_e});break}if(g&&ae==="local_shell"){const ye=await Dt({value:de.input,schema:Iu});xe.push({type:"local_shell_call",call_id:de.toolCallId,id:_e,action:{type:"exec",command:ye.action.command,timeout_ms:ye.action.timeoutMs,user:ye.action.user,working_directory:ye.action.workingDirectory,env:ye.action.env}});break}if(E&&ae==="shell"){const ye=await Dt({value:de.input,schema:Tu});xe.push({type:"shell_call",call_id:de.toolCallId,id:_e,status:"completed",action:{commands:ye.action.commands,timeout_ms:ye.action.timeoutMs,max_output_length:ye.action.maxOutputLength}});break}if(A&&ae==="apply_patch"){const ye=await Dt({value:de.input,schema:Cu});xe.push({type:"apply_patch_call",call_id:ye.callId,id:_e,status:"completed",operation:ye.operation});break}if(D?.has(ae)){xe.push({type:"custom_tool_call",call_id:de.toolCallId,name:ae,input:typeof de.input=="string"?de.input:JSON.stringify(de.input),id:_e});break}xe.push({type:"function_call",call_id:de.toolCallId,name:ae,arguments:R2(de.input),...Pe!=null&&{namespace:Pe}});break}case"tool-result":{if(de.output.type==="execution-denied"||de.output.type==="json"&&typeof de.output.value=="object"&&de.output.value!=null&&"type"in de.output.value&&de.output.value.type==="execution-denied"||x)break;const _e=r.toProviderToolName(de.toolName);if(_e==="tool_search"){const Pe=(me=(G=(we=de.providerOptions)==null?void 0:we[c])==null?void 0:G.itemId)!=null?me:de.toolCallId;if(m)xe.push({type:"item_reference",id:Pe});else if(de.output.type==="json"){const ae=await Dt({value:de.output.value,schema:Mi});xe.push({type:"tool_search_output",id:Pe,execution:"server",call_id:null,status:"completed",tools:ae.tools})}break}if(E&&_e==="shell"){if(de.output.type==="json"){const Pe=await Dt({value:de.output.value,schema:ki});xe.push({type:"shell_call_output",call_id:de.toolCallId,output:Pe.output.map(ae=>({stdout:ae.stdout,stderr:ae.stderr,outcome:ae.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ae.outcome.exitCode}}))})}break}if(m){const Pe=(q=(te=(fe=de.providerOptions)==null?void 0:fe[c])==null?void 0:te.itemId)!=null?q:de.toolCallId;xe.push({type:"item_reference",id:Pe})}else $e.push({type:"other",message:`Results for OpenAI tool ${de.toolName} are not sent to the API when store is false`});break}case"reasoning":{const _e=await An({provider:c,providerOptions:de.providerOptions,schema:D2}),Pe=_e?.itemId;if((x||v)&&Pe!=null)break;if(Pe!=null){const ae=ie[Pe];if(m)ae===void 0&&(xe.push({type:"item_reference",id:Pe}),ie[Pe]={type:"reasoning",id:Pe,summary:[]});else{const J=[];de.text.length>0?J.push({type:"summary_text",text:de.text}):ae!==void 0&&$e.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(de)}.`}),ae===void 0?(ie[Pe]={type:"reasoning",id:Pe,encrypted_content:_e?.reasoningEncryptedContent,summary:J},xe.push(ie[Pe])):(ae.summary.push(...J),_e?.reasoningEncryptedContent!=null&&(ae.encrypted_content=_e.reasoningEncryptedContent))}}else{const ae=_e?.reasoningEncryptedContent;if(ae!=null){const J=[];de.text.length>0&&J.push({type:"summary_text",text:de.text}),xe.push({type:"reasoning",encrypted_content:ae,summary:J})}else $e.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(de)}.`})}break}}break}case"tool":{for(const ie of qe){if(ie.type==="tool-approval-response"){const ae=ie;if(Ue.has(ae.approvalId))continue;Ue.add(ae.approvalId),m&&xe.push({type:"item_reference",id:ae.approvalId}),xe.push({type:"mcp_approval_response",approval_request_id:ae.approvalId,approve:ae.approved});continue}const de=ie.output;if(de.type==="execution-denied"&&((le=(ke=de.providerOptions)==null?void 0:ke.openai)==null?void 0:le.approvalId))continue;const _e=r.toProviderToolName(ie.toolName);if(_e==="tool_search"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Mi});xe.push({type:"tool_search_output",execution:"client",call_id:ie.toolCallId,status:"completed",tools:ae.tools});continue}if(g&&_e==="local_shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Su});xe.push({type:"local_shell_call_output",call_id:ie.toolCallId,output:ae.output});continue}if(E&&_e==="shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:ki});xe.push({type:"shell_call_output",call_id:ie.toolCallId,output:ae.output.map(J=>({stdout:J.stdout,stderr:J.stderr,outcome:J.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:J.outcome.exitCode}}))});continue}if(A&&ie.toolName==="apply_patch"&&de.type==="json"){const ae=await Dt({value:de.value,schema:bu});xe.push({type:"apply_patch_call_output",call_id:ie.toolCallId,status:ae.status,output:ae.output});continue}if(D?.has(_e)){let ae;switch(de.type){case"text":case"error-text":ae=de.value;break;case"execution-denied":ae=(Te=de.reason)!=null?Te:"Tool call execution denied.";break;case"json":case"error-json":ae=JSON.stringify(de.value);break;case"content":ae=de.value.map(J=>{var ye,Se,Ve,St,vt;const et=Nr(J.providerOptions,c);switch(J.type){case"text":return{type:"input_text",text:J.text,...et!=null&&{prompt_cache_breakpoint:et}};case"image-data":return{type:"input_image",image_url:`data:${J.mediaType};base64,${J.data}`,detail:(Se=(ye=J.providerOptions)==null?void 0:ye[c])==null?void 0:Se.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"image-url":return{type:"input_image",image_url:J.url,detail:(St=(Ve=J.providerOptions)==null?void 0:Ve[c])==null?void 0:St.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"file-data":return{type:"input_file",filename:(vt=J.filename)!=null?vt:"data",file_data:`data:${J.mediaType};base64,${J.data}`,...et!=null&&{prompt_cache_breakpoint:et}};case"file-url":return{type:"input_file",file_url:J.url,...et!=null&&{prompt_cache_breakpoint:et}};default:$e.push({type:"other",message:`unsupported custom tool content part type: ${J.type}`});return}}).filter(Ia);break;default:ae=""}xe.push({type:"custom_tool_call_output",call_id:ie.toolCallId,output:ae});continue}let Pe;switch(de.type){case"text":case"error-text":Pe=de.value;break;case"execution-denied":Pe=(Je=de.reason)!=null?Je:"Tool call execution denied.";break;case"json":case"error-json":Pe=JSON.stringify(de.value);break;case"content":Pe=de.value.map(ae=>{var J,ye,Se,Ve,St;const vt=Nr(ae.providerOptions,c);switch(ae.type){case"text":return{type:"input_text",text:ae.text,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-data":return{type:"input_image",image_url:`data:${ae.mediaType};base64,${ae.data}`,detail:(ye=(J=ae.providerOptions)==null?void 0:J[c])==null?void 0:ye.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-url":return{type:"input_image",image_url:ae.url,detail:(Ve=(Se=ae.providerOptions)==null?void 0:Se[c])==null?void 0:Ve.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-data":return{type:"input_file",filename:(St=ae.filename)!=null?St:"data",file_data:`data:${ae.mediaType};base64,${ae.data}`,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-url":return{type:"input_file",file_url:ae.url,...vt!=null&&{prompt_cache_breakpoint:vt}};default:{$e.push({type:"other",message:`unsupported tool content part type: ${ae.type}`});return}}}).filter(Ia);break}xe.push({type:"function_call_output",call_id:ie.toolCallId,output:Pe})}break}default:{const ie=Ze;throw new Error(`Unsupported role: ${ie}`)}}return!m&&xe.some(Ze=>"type"in Ze&&Ze.type==="reasoning"&&Ze.encrypted_content==null)&&($e.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),xe=xe.filter(Ze=>!("type"in Ze)||Ze.type!=="reasoning"||Ze.encrypted_content!=null)),{input:xe,warnings:$e}}var D2=N({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function gi({finishReason:t,hasFunctionCall:r}){switch(t){case void 0:case null:return r?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return r?"tool-calls":"other"}}var ro=Wi(()=>st([w(),j(),Mt(),bc(),ue(ro),wt(w(),ro.optional())])),P2=N({type:Y("error"),sequence_number:j(),error:N({type:w(),code:w(),message:w(),param:w().nullish()})}),B2=N({type:Y("error"),sequence_number:j(),code:w().nullish(),message:w(),param:w().nullish()}),L2=Fe(()=>Le(st([N({type:Y("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}),N({type:Ae(["response.completed","response.incomplete"]),response:N({incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.failed"),sequence_number:j(),response:N({error:N({code:w().nullish(),message:w()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).nullish(),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.created"),response:N({id:w(),created_at:j(),model:w(),service_tier:w().nullish()})}),N({type:Y("response.output_item.added"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),namespace:w().nullish()}),N({type:Y("web_search_call"),id:w(),status:w()}),N({type:Y("computer_call"),id:w(),status:w()}),N({type:Y("file_search_call"),id:w()}),N({type:Y("image_generation_call"),id:w()}),N({type:Y("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable(),status:w()}),N({type:Y("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w()}),N({type:Y("mcp_approval_request"),id:w()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.output_item.done"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:Y("completed"),namespace:w().nullish()}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:Y("completed")}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("computer_call"),id:w(),status:Y("completed")}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.function_call_arguments.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.custom_tool_call_input.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.image_generation_call.partial_image"),item_id:w(),output_index:j(),partial_image_b64:w()}),N({type:Y("response.code_interpreter_call_code.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.code_interpreter_call_code.done"),item_id:w(),output_index:j(),code:w()}),N({type:Y("response.output_text.annotation.added"),annotation:mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})])}),N({type:Y("response.reasoning_summary_part.added"),item_id:w(),summary_index:j()}),N({type:Y("response.reasoning_summary_text.delta"),item_id:w(),summary_index:j(),delta:w()}),N({type:Y("response.reasoning_summary_part.done"),item_id:w(),summary_index:j()}),N({type:Y("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:j(),delta:w(),obfuscation:w().nullish()}),N({type:Y("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:j(),diff:w()}),P2,B2,N({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),F2=Fe(()=>Le(N({id:w().optional(),created_at:j().optional(),error:N({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ue(mt("type",[N({type:Y("message"),role:Y("assistant"),id:w(),phase:Ae(["commentary","final_answer"]).nullish(),content:ue(N({type:Y("output_text"),text:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish(),annotations:ue(mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})]))}))}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("function_call"),call_id:w(),name:w(),arguments:w(),id:w(),namespace:w().nullish()}),N({type:Y("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),N({type:Y("computer_call"),id:w(),status:w().optional()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ue(N({type:Y("summary_text"),text:w()}))}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])).optional(),service_tier:w().nullish(),reasoning:N({context:w().nullish()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).optional()}))),Nu=20,Za=Fe(()=>Le(N({conversation:w().nullish(),include:ue(Ae(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:st([Mt(),j().min(1).max(Nu)]).optional(),maxToolCalls:j().nullish(),metadata:xr().nullish(),parallelToolCalls:Mt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningMode:Ae(["standard","pro"]).optional(),reasoningContext:Ae(["auto","current_turn","all_turns"]).optional(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Ae(["auto","flex","priority","default"]).nullish(),store:Mt().nullish(),passThroughUnsupportedFiles:Mt().optional(),strictJsonSchema:Mt().nullish(),textVerbosity:Ae(["low","medium","high"]).nullish(),truncation:Ae(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional(),allowedTools:N({toolNames:ue(w()).min(1),mode:Ae(["auto","required"]).optional()}).optional()})));async function U2({tools:t,toolChoice:r,allowedTools:i,toolNameMapping:c,customProviderToolNames:d}){var f,m,x;t=t?.length?t:void 0;const v=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:v};const g=[],E=new Map,A=d??new Set;for(const T of t)switch(T.type){case"function":{const S=(f=T.providerOptions)==null?void 0:f.openai,P=z2({tool:T,options:S}),M=S?.namespace;if(M==null)g.push(P);else{let ee=E.get(M.name);if(ee==null)ee={type:"namespace",name:M.name,description:M.description,tools:[]},E.set(M.name,ee),g.push(ee);else if(ee.description!==M.description)throw new Mn({functionality:`conflicting descriptions for OpenAI tool namespace "${M.name}"`});ee.tools.push(P)}break}case"provider":{switch(T.id){case"openai.file_search":{const S=await Dt({value:T.args,schema:n2});g.push({type:"file_search",vector_store_ids:S.vectorStoreIds,max_num_results:S.maxNumResults,ranking_options:S.ranking?{ranker:S.ranking.ranker,score_threshold:S.ranking.scoreThreshold}:void 0,filters:S.filters});break}case"openai.local_shell":{g.push({type:"local_shell"});break}case"openai.shell":{const S=await Dt({value:T.args,schema:f2});g.push({type:"shell",...S.environment&&{environment:V2(S.environment)}});break}case"openai.apply_patch":{g.push({type:"apply_patch"});break}case"openai.web_search_preview":{const S=await Dt({value:T.args,schema:C2});g.push({type:"web_search_preview",search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.web_search":{const S=await Dt({value:T.args,schema:x2});g.push({type:"web_search",filters:S.filters!=null?{allowed_domains:S.filters.allowedDomains}:void 0,external_web_access:S.externalWebAccess,search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.code_interpreter":{const S=await Dt({value:T.args,schema:Xg});g.push({type:"code_interpreter",container:S.container==null?{type:"auto",file_ids:void 0}:typeof S.container=="string"?S.container:{type:"auto",file_ids:S.container.fileIds}});break}case"openai.image_generation":{const S=await Dt({value:T.args,schema:i2});g.push({type:"image_generation",background:S.background,input_fidelity:S.inputFidelity,input_image_mask:S.inputImageMask?{file_id:S.inputImageMask.fileId,image_url:S.inputImageMask.imageUrl}:void 0,model:S.model,moderation:S.moderation,partial_images:S.partialImages,quality:S.quality,output_compression:S.outputCompression,output_format:S.outputFormat,size:S.size});break}case"openai.mcp":{const S=await Dt({value:T.args,schema:I2}),P=$=>({tool_names:$.toolNames}),M=S.requireApproval,ee=M==null?void 0:typeof M=="string"?M:M.never!=null?{never:P(M.never)}:void 0;g.push({type:"mcp",server_label:S.serverLabel,allowed_tools:Array.isArray(S.allowedTools)?S.allowedTools:S.allowedTools?{read_only:S.allowedTools.readOnly,tool_names:S.allowedTools.toolNames}:void 0,authorization:S.authorization,connector_id:S.connectorId,headers:S.headers,require_approval:ee??"never",server_description:S.serverDescription,server_url:S.serverUrl});break}case"openai.custom":{const S=await Dt({value:T.args,schema:Jg});g.push({type:"custom",name:S.name,description:S.description,format:S.format}),A.add(S.name);break}case"openai.tool_search":{const S=await Dt({value:T.args,schema:p2});g.push({type:"tool_search",...S.execution!=null?{execution:S.execution}:{},...S.description!=null?{description:S.description}:{},...S.parameters!=null?{parameters:S.parameters}:{}});break}}break}default:v.push({type:"unsupported",feature:`function tool ${T}`});break}if(i!=null)return{tools:g,toolChoice:{type:"allowed_tools",mode:(m=i.mode)!=null?m:"auto",tools:i.toolNames.map(T=>{var S;return{type:"function",name:(S=c?.toProviderToolName(T))!=null?S:T}})},toolWarnings:v};if(r==null)return{tools:g,toolChoice:void 0,toolWarnings:v};const D=r.type;switch(D){case"auto":case"none":case"required":return{tools:g,toolChoice:D,toolWarnings:v};case"tool":{const T=(x=c?.toProviderToolName(r.toolName))!=null?x:r.toolName;return{tools:g,toolChoice:T==="code_interpreter"||T==="file_search"||T==="image_generation"||T==="web_search_preview"||T==="web_search"||T==="mcp"||T==="apply_patch"?{type:T}:A.has(T)?{type:"custom",name:T}:{type:"function",name:T},toolWarnings:v}}default:{const T=D;throw new Mn({functionality:`tool choice type: ${T}`})}}}function z2({tool:t,options:r}){const i=r?.deferLoading;return{type:"function",name:t.name,description:t.description,parameters:t.inputSchema,...t.strict!=null?{strict:t.strict}:{},...i!=null?{defer_loading:i}:{}}}function V2(t){if(t.type==="containerReference")return{type:"container_reference",container_id:t.containerId};if(t.type==="containerAuto"){const i=t;return{type:"container_auto",file_ids:i.fileIds,memory_limit:i.memoryLimit,network_policy:i.networkPolicy==null?void 0:i.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:i.networkPolicy.allowedDomains,domain_secrets:i.networkPolicy.domainSecrets},skills:Z2(i.skills)}}return{type:"local",skills:t.skills}}function Z2(t){return t?.map(r=>r.type==="skillReference"?{type:"skill_reference",skill_id:r.skillId,version:r.version}:{type:"inline",name:r.name,description:r.description,source:{type:"base64",media_type:r.source.mediaType,data:r.source.data}})}function $a(t){var r,i;const c={};for(const d of t)if(d.role==="assistant")for(const f of d.content){if(f.type!=="tool-call")continue;const m=(i=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:i.approvalRequestId;m!=null&&(c[m]=f.toolCallId)}return c}var $2=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:r,stopSequences:i,topP:c,topK:d,presencePenalty:f,frequencyPenalty:m,seed:x,prompt:v,providerOptions:g,tools:E,toolChoice:A,responseFormat:D}){var T,S,P,M,ee,$,F,re,Z,B,L;const W=[],z=_u(this.modelId);d!=null&&W.push({type:"unsupported",feature:"topK"}),x!=null&&W.push({type:"unsupported",feature:"seed"}),f!=null&&W.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&W.push({type:"unsupported",feature:"frequencyPenalty"}),i!=null&&W.push({type:"unsupported",feature:"stopSequences"});const we=this.config.provider.includes("azure")?"azure":"openai";let G=await An({provider:we,providerOptions:g,schema:Za});G==null&&we!=="openai"&&(G=await An({provider:"openai",providerOptions:g,schema:Za}));const me=(T=G?.forceReasoning)!=null?T:z.isReasoningModel;G?.conversation&&G?.previousResponseId&&W.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const fe=Gp({tools:E,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:ae=>ae.id==="openai.custom"?ae.args.name:void 0}),te=new Set,{tools:q,toolChoice:ke,toolWarnings:le}=await U2({tools:E,toolChoice:A,allowedTools:(S=G?.allowedTools)!=null?S:void 0,toolNameMapping:fe,customProviderToolNames:te}),{input:Te,warnings:Je}=await M2({prompt:v,toolNameMapping:fe,systemMessageMode:(P=G?.systemMessageMode)!=null?P:me?"developer":z.systemMessageMode,providerOptionsName:we,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(M=G?.passThroughUnsupportedFiles)!=null?M:!1,store:(ee=G?.store)!=null?ee:!0,hasConversation:G?.conversation!=null,hasPreviousResponseId:G?.previousResponseId!=null,hasLocalShellTool:Ze("openai.local_shell"),hasShellTool:Ze("openai.shell"),hasApplyPatchTool:Ze("openai.apply_patch"),customProviderToolNames:te.size>0?te:void 0});W.push(...Je);const xe=($=G?.strictJsonSchema)!=null?$:!0;let $e=G?.include;function Ue(ae){$e==null?$e=[ae]:$e.includes(ae)||($e=[...$e,ae])}function Ze(ae){return E?.find(J=>J.type==="provider"&&J.id===ae)!=null}const qe=typeof G?.logprobs=="number"?G?.logprobs:G?.logprobs===!0?Nu:void 0;qe&&Ue("message.output_text.logprobs");const ze=(F=E?.find(ae=>ae.type==="provider"&&(ae.id==="openai.web_search"||ae.id==="openai.web_search_preview")))==null?void 0:F.name;ze&&Ue("web_search_call.action.sources"),Ze("openai.code_interpreter")&&Ue("code_interpreter_call.outputs");const ie=G?.store;ie===!1&&me&&Ue("reasoning.encrypted_content");const de={model:this.modelId,input:Te,temperature:r,top_p:c,max_output_tokens:t,...(D?.type==="json"||G?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:xe,name:(re=D.name)!=null?re:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...G?.textVerbosity&&{verbosity:G.textVerbosity}}},conversation:G?.conversation,max_tool_calls:G?.maxToolCalls,metadata:G?.metadata,parallel_tool_calls:G?.parallelToolCalls,previous_response_id:G?.previousResponseId,store:ie,user:G?.user,instructions:G?.instructions,service_tier:G?.serviceTier,include:$e,prompt_cache_key:G?.promptCacheKey,prompt_cache_options:G?.promptCacheOptions,prompt_cache_retention:G?.promptCacheRetention,safety_identifier:G?.safetyIdentifier,top_logprobs:qe,truncation:G?.truncation,...me&&(G?.reasoningEffort!=null||G?.reasoningSummary!=null||G?.reasoningMode!=null||G?.reasoningContext!=null)&&{reasoning:{...G?.reasoningEffort!=null&&{effort:G.reasoningEffort},...G?.reasoningSummary!=null&&{summary:G.reasoningSummary},...G?.reasoningMode!=null&&{mode:G.reasoningMode},...G?.reasoningContext!=null&&{context:G.reasoningContext}}}};me?G?.reasoningEffort==="none"&&z.supportsNonReasoningParameters||(de.temperature!=null&&(de.temperature=void 0,W.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),de.top_p!=null&&(de.top_p=void 0,W.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(G?.reasoningEffort!=null&&W.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),G?.reasoningSummary!=null&&W.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"}),G?.reasoningMode!=null&&W.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"}),G?.reasoningContext!=null&&W.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})),G?.serviceTier==="flex"&&!z.supportsFlexProcessing&&(W.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete de.service_tier),G?.serviceTier==="priority"&&!z.supportsPriorityProcessing&&(W.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete de.service_tier);const _e=(L=(B=(Z=E?.find(ae=>ae.type==="provider"&&ae.id==="openai.shell"))==null?void 0:Z.args)==null?void 0:B.environment)==null?void 0:L.type,Pe=_e==="containerAuto"||_e==="containerReference";return{webSearchToolName:ze,args:{...de,tools:q,tool_choice:ke},warnings:[...W,...le],store:ie,toolNameMapping:fe,providerOptionsName:we,isShellProviderExecuted:Pe}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,D,T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe;const{args:te,warnings:q,webSearchToolName:ke,toolNameMapping:le,providerOptionsName:Te,isShellProviderExecuted:Je}=await this.getArgs(t),xe=this.config.url({path:"/responses",modelId:this.modelId}),$e=$a(t.prompt),{responseHeaders:Ue,value:Ze,rawValue:qe}=await Zn({url:xe,headers:bn(this.config.headers(),t.headers),body:te,failedResponseHandler:En,successfulResponseHandler:mr(F2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Ze.error)throw new Kt({message:Ze.error.message,url:xe,requestBodyValues:te,statusCode:400,responseHeaders:Ue,responseBody:qe,isRetryable:!1});const ze=[],ie=[];let de=!1;const _e=[];for(const J of Ze.output)switch(J.type){case"reasoning":{J.summary.length===0&&J.summary.push({type:"summary_text",text:""});for(const ye of J.summary)ze.push({type:"reasoning",text:ye.text,providerMetadata:{[Te]:{itemId:J.id,reasoningEncryptedContent:(r=J.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),result:{result:J.result}});break}case"tool_search_call":{const ye=(i=J.call_id)!=null?i:J.id,Se=J.execution==="server";Se&&_e.push(ye),ze.push({type:"tool-call",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),input:JSON.stringify({arguments:J.arguments,call_id:J.call_id}),...Se?{providerExecuted:!0}:{},providerMetadata:{[Te]:{itemId:J.id}}});break}case"tool_search_output":{const ye=(d=(c=J.call_id)!=null?c:_e.shift())!=null?d:J.id;ze.push({type:"tool-result",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),result:{tools:J.tools},providerMetadata:{[Te]:{itemId:J.id}}});break}case"local_shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("local_shell"),input:JSON.stringify({action:J.action}),providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),input:JSON.stringify({action:{commands:J.action.commands}}),...Je&&{providerExecuted:!0},providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call_output":{ze.push({type:"tool-result",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),result:{output:J.output.map(ye=>({stdout:ye.stdout,stderr:ye.stderr,outcome:ye.outcome.type==="exit"?{type:"exit",exitCode:ye.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const ye of J.content){(m=(f=t.providerOptions)==null?void 0:f[Te])!=null&&m.logprobs&&ye.logprobs&&ie.push(ye.logprobs);const Se={itemId:J.id,...J.phase!=null&&{phase:J.phase},...ye.annotations.length>0&&{annotations:ye.annotations}};ze.push({type:"text",text:ye.text,providerMetadata:{[Te]:Se}});for(const Ve of ye.annotations)Ve.type==="url_citation"?ze.push({type:"source",sourceType:"url",id:(g=(v=(x=this.config).generateId)==null?void 0:v.call(x))!=null?g:rn(),url:Ve.url,title:Ve.title}):Ve.type==="file_citation"?ze.push({type:"source",sourceType:"document",id:(D=(A=(E=this.config).generateId)==null?void 0:A.call(E))!=null?D:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}}):Ve.type==="container_file_citation"?ze.push({type:"source",sourceType:"document",id:(P=(S=(T=this.config).generateId)==null?void 0:S.call(T))!=null?P:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,containerId:Ve.container_id}}}):Ve.type==="file_path"&&ze.push({type:"source",sourceType:"document",id:($=(ee=(M=this.config).generateId)==null?void 0:ee.call(M))!=null?$:rn(),mediaType:"application/octet-stream",title:Ve.file_id,filename:Ve.file_id,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}})}break}case"function_call":{de=!0,ze.push({type:"tool-call",toolCallId:J.call_id,toolName:J.name,input:J.arguments,providerMetadata:{[Te]:{itemId:J.id,...J.namespace!=null&&{namespace:J.namespace}}}});break}case"custom_tool_call":{de=!0;const ye=le.toCustomToolName(J.name);ze.push({type:"tool-call",toolCallId:J.call_id,toolName:ye,input:JSON.stringify(J.input),providerMetadata:{[Te]:{itemId:J.id}}});break}case"web_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),result:Ga(J.action)});break}case"mcp_call":{const ye=J.approval_request_id!=null&&(F=$e[J.approval_request_id])!=null?F:J.id,Se=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:ye,toolName:Se,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-result",toolCallId:ye,toolName:Se,result:{type:"call",serverLabel:J.server_label,name:J.name,arguments:J.arguments,...J.output!=null?{output:J.output}:{},...J.error!=null?{error:J.error}:{}},providerMetadata:{[Te]:{itemId:J.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const ye=(re=J.approval_request_id)!=null?re:J.id,Se=(L=(B=(Z=this.config).generateId)==null?void 0:B.call(Z))!=null?L:rn(),Ve=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:Se,toolName:Ve,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-approval-request",approvalId:ye,toolCallId:Se});break}case"computer_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:J.status||"completed"}});break}case"file_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),result:{queries:J.queries,results:(z=(W=J.results)==null?void 0:W.map(ye=>({attributes:ye.attributes,fileId:ye.file_id,filename:ye.filename,score:ye.score,text:ye.text})))!=null?z:null}});break}case"code_interpreter_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),input:JSON.stringify({code:J.code,containerId:J.container_id}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),result:{outputs:J.outputs}});break}case"apply_patch_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("apply_patch"),input:JSON.stringify({callId:J.call_id,operation:J.operation}),providerMetadata:{[Te]:{itemId:J.id}}});break}}const Pe={[Te]:{responseId:Ze.id,...ie.length>0?{logprobs:ie}:{},...typeof Ze.service_tier=="string"?{serviceTier:Ze.service_tier}:{},...((we=Ze.reasoning)==null?void 0:we.context)!=null?{reasoningContext:Ze.reasoning.context}:{}}},ae=Ze.usage;return{content:ze,finishReason:{unified:gi({finishReason:(G=Ze.incomplete_details)==null?void 0:G.reason,hasFunctionCall:de}),raw:(fe=(me=Ze.incomplete_details)==null?void 0:me.reason)!=null?fe:void 0},usage:za(ae),request:{body:te},response:{id:Ze.id,timestamp:new Date(Ze.created_at*1e3),modelId:Ze.model,headers:Ue,body:qe},providerMetadata:Pe,warnings:q}}async doStream(t){const{args:r,warnings:i,webSearchToolName:c,toolNameMapping:d,store:f,providerOptionsName:m,isShellProviderExecuted:x}=await this.getArgs(t),v=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:g,value:E}=await Zn({url:v,headers:bn(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:En,successfulResponseHandler:Ji(L2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=await es({stream:E,getError:fe=>Wa(fe)||ja(fe)&&fe.response.error!=null?fe:void 0,isOutputChunk:ix,url:v,requestBodyValues:r,responseHeaders:g}),D=this,T=$a(t.prompt),S=new Map;let P={unified:"other",raw:void 0},M;const ee=[];let $=null;const F={},re=[];let Z,B=!1;const L={};let W,z;const we=[];let G=!1;return{stream:A.pipeThrough(new TransformStream({start(fe){fe.enqueue({type:"stream-start",warnings:i})},transform(fe,te){var q,ke,le,Te,Je,xe,$e,Ue,Ze,qe,ze,ie,de,_e,Pe,ae,J,ye,Se,Ve,St,vt,et,nt,Xe,In,be,Bn,$n,qt,jn,Ft,rr,sn,At,or,Ln,wr,gt,ge;if(t.includeRawChunks&&te.enqueue({type:"raw",rawValue:fe.rawValue}),!fe.success){const ne=H2(fe.rawValue)?W2({value:fe.rawValue,cause:fe.error,url:v,requestBodyValues:r,responseHeaders:g}):fe.error;P={unified:"error",raw:void 0},te.enqueue({type:"error",error:ne});return}const O=fe.value;if(Ha(O)){if(O.item.type==="function_call")F[O.output_index]={toolName:O.item.name,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:O.item.name});else if(O.item.type==="custom_tool_call"){const ne=d.toCustomToolName(O.item.name);F[O.output_index]={toolName:ne,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:ne})}else if(O.item.type==="web_search_call")F[O.output_index]={toolName:d.toCustomToolName(c??"web_search"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName(c??"web_search"),providerExecuted:!0}),te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(O.item.type==="computer_call")F[O.output_index]={toolName:d.toCustomToolName("computer_use"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("computer_use"),providerExecuted:!0});else if(O.item.type==="code_interpreter_call")F[O.output_index]={toolName:d.toCustomToolName("code_interpreter"),toolCallId:O.item.id,codeInterpreter:{containerId:O.item.container_id}},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("code_interpreter"),providerExecuted:!0}),te.enqueue({type:"tool-input-delta",id:O.item.id,delta:`{"containerId":"${O.item.container_id}","code":"`});else if(O.item.type==="file_search_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(O.item.type==="tool_search_call"){const ne=O.item.id,Me=d.toCustomToolName("tool_search"),Ee=O.item.execution==="server";F[O.output_index]={toolName:Me,toolCallId:ne,toolSearchExecution:(q=O.item.execution)!=null?q:"server"},Ee&&te.enqueue({type:"tool-input-start",id:ne,toolName:Me,providerExecuted:!0})}else if(O.item.type!=="tool_search_output"){if(!(O.item.type==="mcp_call"||O.item.type==="mcp_list_tools"||O.item.type==="mcp_approval_request"))if(O.item.type==="apply_patch_call"){const{call_id:ne,operation:Me}=O.item;if(F[O.output_index]={toolName:d.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:Me.type==="delete_file",endEmitted:Me.type==="delete_file"}},te.enqueue({type:"tool-input-start",id:ne,toolName:d.toCustomToolName("apply_patch")}),Me.type==="delete_file"){const Ee=JSON.stringify({callId:ne,operation:Me});te.enqueue({type:"tool-input-delta",id:ne,delta:Ee}),te.enqueue({type:"tool-input-end",id:ne})}else te.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${fr(ne)}","operation":{"type":"${fr(Me.type)}","path":"${fr(Me.path)}","diff":"`})}else O.item.type==="shell_call"?F[O.output_index]={toolName:d.toCustomToolName("shell"),toolCallId:O.item.call_id}:O.item.type==="shell_call_output"||(O.item.type==="message"?(re.splice(0,re.length),Z=(ke=O.item.phase)!=null?ke:void 0,te.enqueue({type:"text-start",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...O.item.phase!=null&&{phase:O.item.phase}}}})):Ha(O)&&O.item.type==="reasoning"&&(L[O.item.id]={encryptedContent:O.item.encrypted_content,summaryParts:{0:"active"}},te.enqueue({type:"reasoning-start",id:`${O.item.id}:0`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(le=O.item.encrypted_content)!=null?le:null}}})))}}else if(q2(O)){if(O.item.type==="message"){const ne=(Te=O.item.phase)!=null?Te:Z;Z=void 0,te.enqueue({type:"text-end",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...ne!=null&&{phase:ne},...re.length>0&&{annotations:re}}}})}else if(O.item.type==="function_call")F[O.output_index]=void 0,B=!0,te.enqueue({type:"tool-input-end",id:O.item.call_id,...O.item.namespace!=null&&{providerMetadata:{[m]:{namespace:O.item.namespace}}}}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:O.item.name,input:O.item.arguments,providerMetadata:{[m]:{itemId:O.item.id,...O.item.namespace!=null&&{namespace:O.item.namespace}}}});else if(O.item.type==="custom_tool_call"){F[O.output_index]=void 0,B=!0;const ne=d.toCustomToolName(O.item.name);te.enqueue({type:"tool-input-end",id:O.item.call_id}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:ne,input:JSON.stringify(O.item.input),providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="web_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),result:Ga(O.item.action)});else if(O.item.type==="computer_call")F[O.output_index]=void 0,te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:O.item.status||"completed"}});else if(O.item.type==="file_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),result:{queries:O.item.queries,results:(xe=(Je=O.item.results)==null?void 0:Je.map(ne=>({attributes:ne.attributes,fileId:ne.file_id,filename:ne.filename,score:ne.score,text:ne.text})))!=null?xe:null}});else if(O.item.type==="code_interpreter_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("code_interpreter"),result:{outputs:O.item.outputs}});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),result:{result:O.item.result}});else if(O.item.type==="tool_search_call"){const ne=F[O.output_index],Me=O.item.execution==="server";if(ne!=null){const Ee=Me?ne.toolCallId:($e=O.item.call_id)!=null?$e:O.item.id;Me?we.push(Ee):te.enqueue({type:"tool-input-start",id:Ee,toolName:ne.toolName}),te.enqueue({type:"tool-input-end",id:Ee}),te.enqueue({type:"tool-call",toolCallId:Ee,toolName:ne.toolName,input:JSON.stringify({arguments:O.item.arguments,call_id:Me?null:Ee}),...Me?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:O.item.id}}})}F[O.output_index]=void 0}else if(O.item.type==="tool_search_output"){const ne=(Ze=(Ue=O.item.call_id)!=null?Ue:we.shift())!=null?Ze:O.item.id;te.enqueue({type:"tool-result",toolCallId:ne,toolName:d.toCustomToolName("tool_search"),result:{tools:O.item.tools},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_call"){F[O.output_index]=void 0;const ne=(qe=O.item.approval_request_id)!=null?qe:void 0,Me=ne!=null&&(ie=(ze=S.get(ne))!=null?ze:T[ne])!=null?ie:O.item.id,Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:Me,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-result",toolCallId:Me,toolName:Ee,result:{type:"call",serverLabel:O.item.server_label,name:O.item.name,arguments:O.item.arguments,...O.item.output!=null?{output:O.item.output}:{},...O.item.error!=null?{error:O.item.error}:{}},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_list_tools")F[O.output_index]=void 0;else if(O.item.type==="apply_patch_call"){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&O.item.operation.type!=="delete_file"&&(ne.applyPatch.hasDiff||te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.item.operation.diff)}),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0),ne&&O.item.status==="completed"&&te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("apply_patch"),input:JSON.stringify({callId:O.item.call_id,operation:O.item.operation}),providerMetadata:{[m]:{itemId:O.item.id}}}),F[O.output_index]=void 0}else if(O.item.type==="mcp_approval_request"){F[O.output_index]=void 0;const ne=(Pe=(_e=(de=D.config).generateId)==null?void 0:_e.call(de))!=null?Pe:rn(),Me=(ae=O.item.approval_request_id)!=null?ae:O.item.id;S.set(Me,ne);const Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:ne,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-approval-request",approvalId:Me,toolCallId:ne})}else if(O.item.type==="local_shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:O.item.action.command,timeoutMs:O.item.action.timeout_ms,user:O.item.action.user,workingDirectory:O.item.action.working_directory,env:O.item.action.env}}),providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),input:JSON.stringify({action:{commands:O.item.action.commands}}),...x&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call_output")te.enqueue({type:"tool-result",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),result:{output:O.item.output.map(ne=>({stdout:ne.stdout,stderr:ne.stderr,outcome:ne.outcome.type==="exit"?{type:"exit",exitCode:ne.outcome.exit_code}:{type:"timeout"}}))}});else if(O.item.type==="reasoning"){const ne=L[O.item.id],Me=Object.entries(ne.summaryParts).filter(([Ee,Oe])=>Oe==="active"||Oe==="can-conclude").map(([Ee])=>Ee);for(const Ee of Me)te.enqueue({type:"reasoning-end",id:`${O.item.id}:${Ee}`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(J=O.item.encrypted_content)!=null?J:null}}});delete L[O.item.id]}}else if(K2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(J2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(nx(O)){const ne=F[O.output_index];ne?.applyPatch&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)}),ne.applyPatch.hasDiff=!0)}else if(rx(O)){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&(ne.applyPatch.hasDiff||(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.diff)}),ne.applyPatch.hasDiff=!0),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0)}else if(Q2(O))te.enqueue({type:"tool-result",toolCallId:O.item_id,toolName:d.toCustomToolName("image_generation"),result:{result:O.partial_image_b64},preliminary:!0});else if(ex(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)})}else if(tx(O)){const ne=F[O.output_index];ne!=null&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("code_interpreter"),input:JSON.stringify({code:O.code,containerId:ne.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Y2(O))$=O.response.id,te.enqueue({type:"response-metadata",id:O.response.id,timestamp:new Date(O.response.created_at*1e3),modelId:O.response.model});else if(j2(O))te.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),(Se=(ye=t.providerOptions)==null?void 0:ye[m])!=null&&Se.logprobs&&O.logprobs&&ee.push(O.logprobs);else if(O.type==="response.reasoning_summary_part.added"){if(O.summary_index>0){const ne=L[O.item_id];ne.summaryParts[O.summary_index]="active";for(const Me of Object.keys(ne.summaryParts))ne.summaryParts[Me]==="can-conclude"&&(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${Me}`,providerMetadata:{[m]:{itemId:O.item_id}}}),ne.summaryParts[Me]="concluded");te.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id,reasoningEncryptedContent:(St=(Ve=L[O.item_id])==null?void 0:Ve.encryptedContent)!=null?St:null}}})}}else if(O.type==="response.reasoning_summary_text.delta")te.enqueue({type:"reasoning-delta",id:`${O.item_id}:${O.summary_index}`,delta:O.delta,providerMetadata:{[m]:{itemId:O.item_id}}});else if(O.type==="response.reasoning_summary_part.done")f?(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id}}}),L[O.item_id].summaryParts[O.summary_index]="concluded"):L[O.item_id].summaryParts[O.summary_index]="can-conclude";else if(X2(O))P={unified:gi({finishReason:(vt=O.response.incomplete_details)==null?void 0:vt.reason,hasFunctionCall:B}),raw:(nt=(et=O.response.incomplete_details)==null?void 0:et.reason)!=null?nt:void 0},M=O.response.usage,typeof O.response.service_tier=="string"&&(W=O.response.service_tier),((Xe=O.response.reasoning)==null?void 0:Xe.context)!=null&&(z=O.response.reasoning.context);else if(ja(O)){const ne=(In=O.response.incomplete_details)==null?void 0:In.reason;P={unified:ne?gi({finishReason:ne,hasFunctionCall:B}):"error",raw:ne??"error"},M=(be=O.response.usage)!=null?be:void 0,((Bn=O.response.reasoning)==null?void 0:Bn.context)!=null&&(z=O.response.reasoning.context),!G&&O.response.error!=null&&(G=!0,te.enqueue({type:"error",error:{type:"response.failed",sequence_number:O.sequence_number,response:{error:O.response.error,incomplete_details:O.response.incomplete_details,service_tier:O.response.service_tier}}}))}else ox(O)?(re.push(O.annotation),O.annotation.type==="url_citation"?te.enqueue({type:"source",sourceType:"url",id:(jn=(qt=($n=D.config).generateId)==null?void 0:qt.call($n))!=null?jn:rn(),url:O.annotation.url,title:O.annotation.title}):O.annotation.type==="file_citation"?te.enqueue({type:"source",sourceType:"document",id:(sn=(rr=(Ft=D.config).generateId)==null?void 0:rr.call(Ft))!=null?sn:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}}):O.annotation.type==="container_file_citation"?te.enqueue({type:"source",sourceType:"document",id:(Ln=(or=(At=D.config).generateId)==null?void 0:or.call(At))!=null?Ln:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,containerId:O.annotation.container_id}}}):O.annotation.type==="file_path"&&te.enqueue({type:"source",sourceType:"document",id:(ge=(gt=(wr=D.config).generateId)==null?void 0:gt.call(wr))!=null?ge:rn(),mediaType:"application/octet-stream",title:O.annotation.file_id,filename:O.annotation.file_id,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}})):Wa(O)&&(G=!0,P={unified:"error",raw:"error"},te.enqueue({type:"error",error:O}))},flush(fe){const te={[m]:{responseId:$,...ee.length>0?{logprobs:ee}:{},...W!==void 0?{serviceTier:W}:{},...z!==void 0?{reasoningContext:z}:{}}};fe.enqueue({type:"finish",finishReason:P,usage:za(M),providerMetadata:te})}})),request:{body:r},response:{headers:g}}}};function j2(t){return t.type==="response.output_text.delta"}function H2(t){const r=G2(t);return r!=null&&Array.isArray(r.choices)&&typeof r.type!="string"}function W2({value:t,cause:r,url:i,requestBodyValues:c,responseHeaders:d}){return new Kt({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:i,requestBodyValues:c,responseHeaders:d,responseBody:JSON.stringify(t),cause:r,data:t,isRetryable:!1})}function G2(t){return typeof t=="object"&&t!=null?t:void 0}function q2(t){return t.type==="response.output_item.done"}function X2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ja(t){return t.type==="response.failed"}function Y2(t){return t.type==="response.created"}function K2(t){return t.type==="response.function_call_arguments.delta"}function J2(t){return t.type==="response.custom_tool_call_input.delta"}function Q2(t){return t.type==="response.image_generation_call.partial_image"}function ex(t){return t.type==="response.code_interpreter_call_code.delta"}function tx(t){return t.type==="response.code_interpreter_call_code.done"}function nx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function rx(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function ox(t){return t.type==="response.output_text.annotation.added"}function Wa(t){return t.type==="error"}function ix(t){return!(t.type==="response.created"||t.type==="response.failed"||t.type==="error"||t.type==="unknown_chunk")}function Ga(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0,...t.queries!=null&&{queries:t.queries}},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function fr(t){return JSON.stringify(t).slice(1,-1)}var sx=Fe(()=>Le(N({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),ax=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:r="alloy",outputFormat:i="mp3",speed:c,instructions:d,language:f,providerOptions:m}){const x=[],v=await An({provider:"openai",providerOptions:m,schema:sx}),g={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:d};if(i&&(["mp3","opus","aac","flac","wav","pcm"].includes(i)?g.response_format=i:x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${i}. Using mp3 instead.`})),v){const E={};for(const A in E){const D=E[A];D!==void 0&&(g[A]=D)}}return f&&x.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:g,warnings:x}}async doGenerate(t){var r,i,c;const d=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{requestBody:f,warnings:m}=await this.getArgs(t),{value:x,responseHeaders:v,rawValue:g}=await Zn({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:f,failedResponseHandler:En,successfulResponseHandler:xg(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:x,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:d,modelId:this.modelId,headers:v,body:g}}}},lx=Fe(()=>Le(N({text:w(),language:w().nullish(),duration:j().nullish(),words:ue(N({word:w(),start:j(),end:j()})).nullish(),segments:ue(N({id:j(),seek:j(),start:j(),end:j(),text:w(),tokens:ue(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),cx=Fe(()=>Le(N({include:ue(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:ue(Ae(["word","segment"])).default(["segment"]).optional()}))),qa={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},ux=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:r,providerOptions:i}){const c=[],d=await An({provider:"openai",providerOptions:i,schema:cx}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([qi(t)]);f.append("model",this.modelId);const x=gm(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${x}`),d){const v={include:d.include,language:d.language,prompt:d.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:d.temperature,timestamp_granularities:d.timestampGranularities};for(const[g,E]of Object.entries(v))if(E!=null)if(Array.isArray(E))for(const A of E)f.append(`${g}[]`,String(A));else f.append(g,String(E))}return{formData:f,warnings:c}}async doGenerate(t){var r,i,c,d,f,m,x,v;const g=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{formData:E,warnings:A}=await this.getArgs(t),{value:D,responseHeaders:T,rawValue:S}=await xu({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),formData:E,failedResponseHandler:En,successfulResponseHandler:mr(lx),abortSignal:t.abortSignal,fetch:this.config.fetch}),P=D.language!=null&&D.language in qa?qa[D.language]:void 0;return{text:D.text,segments:(x=(m=(d=D.segments)==null?void 0:d.map(M=>({text:M.text,startSecond:M.start,endSecond:M.end})))!=null?m:(f=D.words)==null?void 0:f.map(M=>({text:M.word,startSecond:M.start,endSecond:M.end})))!=null?x:[],language:P,durationInSeconds:(v=D.duration)!=null?v:void 0,warnings:A,response:{timestamp:g,modelId:this.modelId,headers:T,body:S}}}},dx="3.0.84";function Ou(t={}){var r,i;const c=(r=yg(mm({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",d=(i=t.name)!=null?i:"openai",f=()=>cu({Authorization:`Bearer ${pm({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${dx}`),m=P=>new Tg(P,{provider:`${d}.chat`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),x=P=>new Mg(P,{provider:`${d}.completion`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),v=P=>new Lg(P,{provider:`${d}.embedding`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),g=P=>new $g(P,{provider:`${d}.image`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),E=P=>new ux(P,{provider:`${d}.transcription`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),A=P=>new ax(P,{provider:`${d}.speech`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),D=P=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return T(P)},T=P=>new $2(P,{provider:`${d}.responses`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),S=function(P){return D(P)};return S.specificationVersion="v3",S.languageModel=D,S.chat=m,S.completion=x,S.responses=T,S.embedding=v,S.embeddingModel=v,S.textEmbedding=v,S.textEmbeddingModel=v,S.image=g,S.imageModel=g,S.transcription=E,S.transcriptionModel=E,S.speech=A,S.speechModel=A,S.tools=k2,S}Ou();const fx={deepseek:{prompt:{strategy:"append",id:"5ed1b9071c15d1ed59b5827ea5dcabd4",params:{customComponents:[{name:"选择用户组件",description:"选择用户组件,用于选择用户,支持模糊搜索",component:"TinyUser",schema:{properties:[{property:"modelValue",label:"用户绑定工号",required:!0,description:"用户的工号,双向绑定值",type:"string"},{property:"valueField",label:"值字段",required:!0,description:"用户工号值的绑定字段",type:"string"}]}}],customExamples:[{name:"选择用户示例",schema:{componentName:"Page",state:{reviewer:""},children:[{componentName:"h3",props:{},children:"输入用户名搜索工号并选择用户"},{componentName:"TinyUser",props:{modelValue:{type:"JSExpression",model:!0,value:"this.state.reviewer"},valueField:"uid"}},{componentName:"TinyButton",props:{text:"提交"}}]}}],customActions:[{name:"continueChat",description:"继续对话, 用于表单的提交按钮等",parameters:{type:"object",properties:{message:{type:"string",description:"对话消息,可以是按钮文本等,也可以是其他内容"}}}}]}}}};class hx{constructor(r={}){this.option=r}async traverse(r){const i=_.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",i),(async()=>{let d,f,m,x,v;for await(const g of r.fullStream)switch(this.option.debug&&console.log("【stream-debug】 "+(new Date().getTime()/1e3).toString().slice(-6)+g.type,g),g.type){case"start":d=_.reactive({running:!0,steps:[]}),i.value=d,this.option.onStart?.(d);break;case"start-step":f=_.reactive({running:!0,contents:[],request:g.request}),d.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":m=_.reactive({type:"reasoning",id:g.id,running:!0,text:""}),f.contents.push(m),this.option.onReasoning?.(m);break;case"reasoning-delta":m.text+=g.text;break;case"reasoning-end":m.running=!1;break;case"text-start":x=_.reactive({type:"text",id:g.id,running:!0,text:""}),f.contents.push(x),this.option.onText?.(x);break;case"text-delta":x.text+=g.text;break;case"text-end":x.running=!1;break;case"tool-input-start":v=_.reactive({type:"tool",running:!0,id:g.id,toolCallId:g.id,title:"",toolName:g.toolName,dynamic:g.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(v),this.option.onTool?.(v);break;case"tool-input-delta":v.inputStr+=g.delta;break;case"tool-input-end":break;case"tool-call":v.input=g.input;break;case"tool-result":v.output=g.output,v.running=!1;break;case"tool-error":v.error=g.error,v.running=!1;break;case"finish-step":f.running=!1,f.finishReason=g.finishReason,f.usage=g.usage;break;case"finish":d.running=!1,d.finishReason=g.finishReason,d.totalUsage=g.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":d&&(d.running=!1,d.error=g.error,d.finishReason="error"),this.option.onFinish?.();break;case"abort":d&&(d.running=!1,d.error={message:g.reason},d.finishReason="other"),this.option.onFinish?.();break}})(),i}}function px(t){const r=[];let i=0;for(;i<t.length;){const c="```schemaJson",d=t.indexOf(c,i),f=c.length;if(d===-1){const g=t.slice(i).trim();g&&r.push({type:"markdown",content:g});break}const m=t.slice(i,d).trim();m&&r.push({type:"markdown",content:m});const x=t.indexOf("```",d+f);let v;x===-1?(v=t.slice(d+f).trim(),i=t.length):(v=t.slice(d+f,x).trim(),i=x+3),r.push({type:"schema-card",content:v})}return r}class mx{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
51
56
  当前时间:${new Date().toLocaleDateString()}。
52
57
  ${this.staticPrompt}
53
58
  ${this.skillMetaPrompt}
54
59
  ${this.tempPrompt}
55
- `}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const fo={model:"deepseek-ai/DeepSeek-V3",maxSteps:15,extraTools:{}},za={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function L2(t,r){if(!r&&!t)return;if(!t)return r;if(!r)return t;const o={...r};for(const[c,u]of Object.entries(t))u&&typeof u=="object"&&!Array.isArray(u)?o[c]={...o[c]||{},...u}:o[c]=u;return o}class F2 extends Jn.BaseModelProvider{transport;agent;promptManager;llmConfig={...fo,...za};isGenuiEnabled;debugStream=!1;emit;constructor(r,o,c,u){super(r);let f;c&&"llm"in c?f={...fo,...c}:f={...fo,...za,...c||{}},this.llmConfig=f;const g={llmConfig:f.llm?{llm:f.llm}:{...f}};this.agent=new Vn.AgentModelProvider(g),this.promptManager=new B2,this.promptManager.setStatic(o),this.emit=u}updateLLMConfig({model:r,baseURL:o,genuiUrl:c,apiKey:u,providerType:f,useReActMode:m,llm:g,providerOptions:C,headers:x}){if(g)this.agent.llm=g,this.llmConfig.model=r,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;else if(f&&o&&u){const A=this.isGenuiEnabled?.value&&c||o;this.llmConfig.model=r,this.llmConfig.apiKey=u,this.llmConfig.baseURL=o,this.llmConfig.providerType=f,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;let v;if(f==="deepseek")v=Cc;else if(f==="openai")v=gu;else if(typeof f=="function")v=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=v({apiKey:u,baseURL:A,...x?{headers:x}:{}})}this.llmConfig.providerOptions=C,this.llmConfig.headers=x}cleanGetSkillContentToolResult(r){const o=r[r.length-1];if(o.role==="tool"&&o.content.length>0){const c=o.content[o.content.length-1];c.type==="tool-result"&&c.toolName==="get_skill_content"&&(c.output.value.content="查询到技能内容已添加到系统提示词中。")}}cleanupOldSnapshotsInMessages(r){if(!r||r.length===0)return r;const c=this.agent.useReActMode===!0?"user":"tool",u=r[r.length-1];if(!u||u.role!==c||!this.isSnapshotContent(u.content))return r;const f=[...r];for(let m=f.length-2;m>=0;m--){const g=f[m];g.role===c&&this.isSnapshotContent(g.content)&&this.replaceSnapshotWithPlaceholder(g)}return f}removeSnapshotData(r){if(!r)return r;const o=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of o){const m=r.indexOf(f);if(m!==-1){c=m;break}}if(c!==-1){const f=r.substring(0,c).trim();return f?`${f} 📸 [历史快照已清理]`:"📸 历史快照已清理"}const u=["已成功获取页面无障碍树快照","takeSnapshot","snapshotId_counter"];for(const f of u)if(r.startsWith(f))return"📸 历史快照已清理";return r}replaceSnapshotWithPlaceholder(r){if(Array.isArray(r.content)){const o=r.content[0];if(o?.output?.value?.content){const c=o.output.value.content;Array.isArray(c)&&(o.output.value.content=c.map(u=>u.type==="image"||u.type==="image_url"?null:u.type==="text"&&u.text&&this.isSnapshotContent(u.text)?{type:"text",text:this.removeSnapshotData(u.text)}:u).filter(u=>u!==null)),o.output.value.screenshot&&delete o.output.value.screenshot}else r.content=r.content.filter(c=>c.type!=="image"&&c.type!=="image_url")}else typeof r.content=="string"&&this.isSnapshotContent(r.content)&&(r.content=this.removeSnapshotData(r.content))}isSnapshotContent(r){if(!r)return!1;const o=["无障碍树快照","takeSnapshot","snapshotId_counter","UID 格式","快照 ID","操作后的页面快照","已成功获取页面无障碍树快照","快照内容:"];if(typeof r=="string")return o.some(c=>r.includes(c));if(Array.isArray(r))for(const c of r){const u=c?.output?.value?.content?.[0]?.text;if(u&&o.some(f=>u.includes(f))||c.type==="text"&&c.text&&o.some(f=>c.text.includes(f))||c.type==="image"||c.type==="image_url")return!0}return!1}async chatStream(r,o){let c=r.messages[r.messages.length-1];if(!c)return;const u={model:this.llmConfig.model,system:this.promptManager.getSystemPrompt(),abortSignal:r.options?.signal,toolChoice:"auto",tools:this.llmConfig.extraTools||{},maxSteps:this.llmConfig.maxSteps,providerOptions:L2(this.llmConfig.providerOptions,M2),prepareStep:({messages:O})=>{this.cleanGetSkillContentToolResult(O);const M=this.cleanupOldSnapshotsInMessages(O),D=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(G=>{D.push(...Object.keys(G||{}))});const B=Array.from(new Set(D)).filter(G=>!this.agent.ignoreToolnames.includes(G));return{system:this.promptManager.getSystemPrompt(),messages:M,activeTools:B}},onStepFinish:O=>{if(O.finishReason==="tool-calls"&&O.content.length>0){const M=O.content[O.content.length-1];if(M.toolName==="get_skill_content"&&M.type==="tool-result"){const D=M.output.content;this.promptManager.appendTemp(D)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp(""),this.emit?.("chat-stream-finish")}},f={role:"user",content:c.content},g=[...(O=>O.map(M=>({role:M.role,content:M.content})))(this.agent.responseMessages),f];u.messages=g;const C=await this.agent.chatStream(u),x=new Dp,v=await new D2({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{x.resolve(),o.onDone()})}}).traverse(C),P={role:"assistant",content:"",uiContent:[]};return _.watch(v,O=>{if(!O)o.onData(P);else{const D=O.steps.map(B=>B.contents).flat().map(B=>{if(B.type==="text")return P2(B.text);if(B.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:B.text,thinkId:B.id};if(B.type==="tool")return{type:"tool",id:B.id,name:B.toolName,content:JSON.stringify({input:B.inputStr,output:B.output}),status:B.error?"failed":B.running?"running":"success"}});if(O?.error){const B={type:"markdown",content:`**错误**:${O.error.responseBody||O.error.message||"未知错误"}`};D.push(B)}(O.steps.length>=1||O?.error)&&o.onData({...P,uiContent:D.flat(),usage:O.totalUsage||null})}},{deep:!0}),x.promise}chat(r){throw new Error("Method not implemented.")}}const U2=({systemPrompt:t,llmConfig:r,emit:o})=>{const c=new F2({provider:"custom"},t,r,o),u=new Jn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:m,getCurrentConversation:g,switchConversation:C,deleteConversation:x,updateTitle:A,state:v}=Jn.useConversation({client:u,autoSave:!0,events:{onLoaded(){},onReceiveData(K,V,U){U(),V.value[V.value.length-1].role==="assistant"&&V.value.pop(),o("before-ai-render",K),V.value.push(K)}}}),{messageState:P,inputMessage:O,sendMessage:M,abortRequest:D,messages:B,addMessage:G,send:Z}=f,z=_.ref(),ee=async(K,V,U)=>{if(U){const{shouldBlock:S}=await U(K);if(S)return!1}O.value=K;const J=g();if(J&&J.title==="新会话"&&A(J.id,O.value.slice(0,15)),V&&V.length>0){const S=[{type:"text",text:O.value},...V],Te=[];O.value&&Te.push({type:"text",content:O.value});for(const re of V)re.type==="image"&&re.image&&Te.push({type:"image",content:re.image});const ye={role:"user",content:S,uiContent:Te};B.value.push(ye),O.value="",Z()}else{const S={role:"user",content:O.value,uiContent:[{type:"text",content:O.value}]};B.value.push(S),O.value="",Z()}return!0};return _.onMounted(()=>{z.value?.focus()}),_.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:u,messageManager:f,addMessage:G,send:Z,conversationState:v,messages:B,messageState:P,inputMessage:O,sendMessage:M,abortRequest:D,senderRef:z,handleSendMessage:ee,createConversation:m,switchConversation:C,deleteConversation:x,getCurrentConversation:g}};function z2(){}const Pn=Object.assign,Yo=typeof window<"u",Li=t=>t!==null&&typeof t=="object",tr=t=>t!=null,ko=t=>typeof t=="function",V2=t=>Li(t)&&ko(t.then)&&ko(t.catch),xu=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),Z2=()=>Yo?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Va(t,r){const o=r.split(".");let c=t;return o.forEach(u=>{var f;c=Li(c)&&(f=c[u])!=null?f:""}),c}function $2(t,r,o){return r.reduce((c,u)=>(c[u]=t[u],c),{})}const Oi=null,un=[Number,String],fr={type:Boolean,default:!0},H2=t=>({type:Number,default:t}),dn=t=>({type:String,default:t});var Ko=typeof window<"u";function yu(t){let r;_.onMounted(()=>{t(),_.nextTick(()=>{r=!0})}),_.onActivated(()=>{r&&t()})}function wu(t,r,o={}){if(!Ko)return;const{target:c=window,passive:u=!1,capture:f=!1}=o;let m=!1,g;const C=v=>{if(m)return;const P=_.unref(v);P&&!g&&(P.addEventListener(t,r,{capture:f,passive:u}),g=!0)},x=v=>{if(m)return;const P=_.unref(v);P&&g&&(P.removeEventListener(t,r,f),g=!1)};_.onUnmounted(()=>x(c)),_.onDeactivated(()=>x(c)),yu(()=>C(c));let A;return _.isRef(c)&&(A=_.watch(c,(v,P)=>{x(P),C(v)})),()=>{A?.(),x(c),m=!0}}var _i,ho;function W2(){if(!_i&&(_i=_.ref(0),ho=_.ref(0),Ko)){const t=()=>{_i.value=window.innerWidth,ho.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:_i,height:ho}}var j2=/scroll|auto|overlay/i,G2=Ko?window:void 0;function X2(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function q2(t,r=G2){let o=t;for(;o&&o!==r&&X2(o);){const{overflowY:c}=window.getComputedStyle(o);if(j2.test(c))return o;o=o.parentNode}return r}Z2();const Y2=t=>t.stopPropagation();function _u(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Y2(t)}W2();function Cn(t){if(tr(t))return xu(t)?`${t}px`:String(t)}function K2(t){if(tr(t)){if(Array.isArray(t))return{width:Cn(t[0]),height:Cn(t[1])};const r=Cn(t);return{width:r,height:r}}}function J2(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const Q2=/-(\w)/g,vu=t=>t.replace(Q2,(r,o)=>o.toUpperCase()),ex=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:tx}=Object.prototype;function nx(t,r,o){const c=r[o];tr(c)&&(!tx.call(t,o)||!Li(c)?t[o]=c:t[o]=Cu(Object(t[o]),c))}function Cu(t,r){return Object.keys(r).forEach(o=>{nx(t,r,o)}),t}var rx={name:"姓名",tel:"电话",save:"保存",clear:"清空",undo:"撤销",cancel:"取消",confirm:"确认",delete:"删除",loading:"加载中...",noCoupon:"暂无优惠券",nameEmpty:"请填写姓名",addContact:"添加联系人",telInvalid:"请填写正确的电话",vanCalendar:{end:"结束",start:"开始",title:"日期选择",weekdays:["日","一","二","三","四","五","六"],monthTitle:(t,r)=>`${t}年${r}月`,rangePrompt:t=>`最多选择 ${t} 天`},vanCascader:{select:"请选择"},vanPagination:{prev:"上一页",next:"下一页"},vanPullRefresh:{pulling:"下拉即可刷新...",loosing:"释放即可刷新..."},vanSubmitBar:{label:"合计:"},vanCoupon:{unlimited:"无门槛",discount:t=>`${t}折`,condition:t=>`满${t}元可用`},vanCouponCell:{title:"优惠券",count:t=>`${t}张可用`},vanCouponList:{exchange:"兑换",close:"不使用",enable:"可用",disabled:"不可用",placeholder:"输入优惠码"},vanAddressEdit:{area:"地区",areaEmpty:"请选择地区",addressEmpty:"请填写详细地址",addressDetail:"详细地址",defaultAddress:"设为默认收货地址"},vanAddressList:{add:"新增地址"}};const Za=_.ref("zh-CN"),$a=_.reactive({"zh-CN":rx}),ix={messages(){return $a[Za.value]},use(t,r){Za.value=t,this.add({[t]:r})},add(t={}){Cu($a,t)}};var ox=ix;function sx(t){const r=vu(t)+".";return(o,...c)=>{const u=ox.messages(),f=Va(u,r+o)||Va(u,o);return ko(f)?f(...c):f}}function Ro(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((o,c)=>o+Ro(t,c),""):Object.keys(r).reduce((o,c)=>o+(r[c]?Ro(t,c):""),""):""}function ax(t){return(r,o)=>(r&&typeof r!="string"&&(o=r,r=""),r=r?`${t}__${r}`:t,`${r}${Ro(r,o)}`)}function gr(t){const r=`van-${t}`;return[r,ax(r),sx(r)]}const lx="van-haptics-feedback",Ha=5;function cx(t,{args:r=[],done:o,canceled:c,error:u}){if(t){const f=t.apply(null,r);V2(f)?f.then(m=>{m?o():c&&c()}).catch(u||z2):f?o():c&&c()}else o()}function ii(t){return t.install=r=>{const{name:o}=t;o&&(r.component(o,t),r.component(vu(`-${o}`),t))},t}const ux=Symbol();function bu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[dx,Wa]=gr("badge"),fx={dot:Boolean,max:un,tag:dn("div"),color:String,offset:Array,content:un,showZero:fr,position:dn("top-right")};var hx=_.defineComponent({name:dx,props:fx,setup(t,{slots:r}){const o=()=>{if(r.content)return!0;const{content:g,showZero:C}=t;return tr(g)&&g!==""&&(C||g!==0&&g!=="0")},c=()=>{const{dot:g,max:C,content:x}=t;if(!g&&o())return r.content?r.content():tr(C)&&xu(x)&&+x>+C?`${C}+`:x},u=g=>g.startsWith("-")?g.replace("-",""):`-${g}`,f=_.computed(()=>{const g={background:t.color};if(t.offset){const[C,x]=t.offset,{position:A}=t,[v,P]=A.split("-");r.default?(typeof x=="number"?g[v]=Cn(v==="top"?x:-x):g[v]=v==="top"?Cn(x):u(x),typeof C=="number"?g[P]=Cn(P==="left"?C:-C):g[P]=P==="left"?Cn(C):u(C)):(g.marginTop=Cn(x),g.marginLeft=Cn(C))}return g}),m=()=>{if(o()||t.dot)return _.createVNode("div",{class:Wa([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:g}=t;return _.createVNode(g,{class:Wa("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const px=ii(hx);let Eu=2e3;const mx=()=>++Eu,gx=t=>{Eu=t},[Au,xx]=gr("config-provider"),Iu=Symbol(Au),yx={tag:dn("div"),theme:dn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:dn("local"),iconPrefix:String};function wx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function _x(t){const r={};return Object.keys(t).forEach(o=>{const c=wx(ex(o));r[`--van-${c}`]=t[o]}),r}function vi(t={},r={}){Object.keys(t).forEach(o=>{t[o]!==r[o]&&document.documentElement.style.setProperty(o,t[o])}),Object.keys(r).forEach(o=>{t[o]||document.documentElement.style.removeProperty(o)})}_.defineComponent({name:Au,props:yx,setup(t,{slots:r}){const o=_.computed(()=>_x(Pn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(Yo){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},u=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};_.watch(()=>t.theme,(f,m)=>{m&&u(m),c()},{immediate:!0}),_.onActivated(c),_.onDeactivated(u),_.onBeforeUnmount(u),_.watch(o,(f,m)=>{t.themeVarsScope==="global"&&vi(f,m)}),_.watch(()=>t.themeVarsScope,(f,m)=>{m==="global"&&vi({},o.value),f==="global"&&vi(o.value,{})}),t.themeVarsScope==="global"&&vi(o.value,{})}return _.provide(Iu,t),_.watchEffect(()=>{t.zIndex!==void 0&&gx(t.zIndex)}),()=>_.createVNode(t.tag,{class:xx(),style:t.themeVarsScope==="local"?o.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[vx,ja]=gr("icon"),Cx=t=>t?.includes("/"),bx={dot:Boolean,tag:dn("i"),name:String,size:un,badge:un,color:String,badgeProps:Object,classPrefix:String};var Ex=_.defineComponent({name:vx,props:bx,setup(t,{slots:r}){const o=_.inject(Iu,null),c=_.computed(()=>t.classPrefix||o?.iconPrefix||ja());return()=>{const{tag:u,dot:f,name:m,size:g,badge:C,color:x}=t,A=Cx(m);return _.createVNode(px,_.mergeProps({dot:f,tag:u,class:[c.value,A?"":`${c.value}-${m}`],style:{color:x,fontSize:Cn(g)},content:C},t.badgeProps),{default:()=>{var v;return[(v=r.default)==null?void 0:v.call(r),A&&_.createVNode("img",{class:ja("image"),src:m},null)]}})}}});const Jo=ii(Ex),[Ax,Gr]=gr("loading"),Ix=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Gr("line",String(r+1))},null)),Sx=_.createVNode("svg",{class:Gr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),Tx={size:un,type:dn("circular"),color:String,vertical:Boolean,textSize:un,textColor:String};var Nx=_.defineComponent({name:Ax,props:Tx,setup(t,{slots:r}){const o=_.computed(()=>Pn({color:t.color},K2(t.size))),c=()=>{const f=t.type==="spinner"?Ix:Sx;return _.createVNode("span",{class:Gr("spinner",t.type),style:o.value},[r.icon?r.icon():f])},u=()=>{var f;if(r.default)return _.createVNode("span",{class:Gr("text"),style:{fontSize:Cn(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:m}=t;return _.createVNode("div",{class:Gr([f,{vertical:m}]),"aria-live":"polite","aria-busy":!0},[c(),u()])}}});const Ox=ii(Nx),kx={show:Boolean,zIndex:un,overlay:fr,duration:un,teleport:[String,Object],lockScroll:fr,lazyRender:fr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Oi,transitionAppear:Boolean,closeOnClickOverlay:fr};function Rx(t,r){return t>r?"horizontal":r>t?"vertical":""}function Mx(){const t=_.ref(0),r=_.ref(0),o=_.ref(0),c=_.ref(0),u=_.ref(0),f=_.ref(0),m=_.ref(""),g=_.ref(!0),C=()=>m.value==="vertical",x=()=>m.value==="horizontal",A=()=>{o.value=0,c.value=0,u.value=0,f.value=0,m.value="",g.value=!0};return{move:(O=>{const M=O.touches[0];o.value=(M.clientX<0?0:M.clientX)-t.value,c.value=M.clientY-r.value,u.value=Math.abs(o.value),f.value=Math.abs(c.value);const D=10;(!m.value||u.value<D&&f.value<D)&&(m.value=Rx(u.value,f.value)),g.value&&(u.value>Ha||f.value>Ha)&&(g.value=!1)}),start:(O=>{A(),t.value=O.touches[0].clientX,r.value=O.touches[0].clientY}),reset:A,startX:t,startY:r,deltaX:o,deltaY:c,offsetX:u,offsetY:f,direction:m,isVertical:C,isHorizontal:x,isTap:g}}let Vr=0;const Ga="van-overflow-hidden";function Dx(t,r){const o=Mx(),c="01",u="10",f=A=>{o.move(A);const v=o.deltaY.value>0?u:c,P=q2(A.target,t.value),{scrollHeight:O,offsetHeight:M,scrollTop:D}=P;let B="11";D===0?B=M>=O?"00":"01":D+M>=O&&(B="10"),B!=="11"&&o.isVertical()&&!(parseInt(B,2)&parseInt(v,2))&&_u(A)},m=()=>{document.addEventListener("touchstart",o.start),document.addEventListener("touchmove",f,{passive:!1}),Vr||document.body.classList.add(Ga),Vr++},g=()=>{Vr&&(document.removeEventListener("touchstart",o.start),document.removeEventListener("touchmove",f),Vr--,Vr||document.body.classList.remove(Ga))},C=()=>r()&&m(),x=()=>r()&&g();yu(C),_.onDeactivated(x),_.onBeforeUnmount(x),_.watch(r,A=>{A?m():g()})}function Su(t){const r=_.ref(!1);return _.watch(t,o=>{o&&(r.value=o)},{immediate:!0}),o=>()=>r.value?o():null}const Xa=()=>{var t;const{scopeId:r}=((t=_.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[Px,Bx]=gr("overlay"),Lx={show:Boolean,zIndex:un,duration:un,className:Oi,lockScroll:fr,lazyRender:fr,customStyle:Object,teleport:[String,Object]};var Fx=_.defineComponent({name:Px,inheritAttrs:!1,props:Lx,setup(t,{attrs:r,slots:o}){const c=_.ref(),u=Su(()=>t.show||!t.lazyRender),f=g=>{t.lockScroll&&_u(g)},m=u(()=>{var g;const C=Pn(J2(t.zIndex),t.customStyle);return tr(t.duration)&&(C.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:C,class:[Bx(),t.className]},r),[(g=o.default)==null?void 0:g.call(o)]),[[_.vShow,t.show]])});return wu("touchmove",f,{target:c}),()=>{const g=_.createVNode(_.Transition,{name:"van-fade",appear:!0},{default:m});return t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[g]}):g}}});const Ux=ii(Fx),zx=Pn({},kx,{round:Boolean,position:dn("center"),closeIcon:dn("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:dn("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[Vx,qa]=gr("popup");var Zx=_.defineComponent({name:Vx,inheritAttrs:!1,props:zx,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:o,slots:c}){let u,f;const m=_.ref(),g=_.ref(),C=Su(()=>t.show||!t.lazyRender),x=_.computed(()=>{const V={zIndex:m.value};if(tr(t.duration)){const U=t.position==="center"?"animationDuration":"transitionDuration";V[U]=`${t.duration}s`}return V}),A=()=>{u||(u=!0,m.value=t.zIndex!==void 0?+t.zIndex:mx(),r("open"))},v=()=>{u&&cx(t.beforeClose,{done(){u=!1,r("close"),r("update:show",!1)}})},P=V=>{r("clickOverlay",V),t.closeOnClickOverlay&&v()},O=()=>{if(t.overlay){const V=Pn({show:t.show,class:t.overlayClass,zIndex:m.value,duration:t.duration,customStyle:t.overlayStyle,role:t.closeOnClickOverlay?"button":void 0,tabindex:t.closeOnClickOverlay?0:void 0},t.overlayProps);return _.createVNode(Ux,_.mergeProps(V,Xa(),{onClick:P}),{default:c["overlay-content"]})}},M=V=>{r("clickCloseIcon",V),v()},D=()=>{if(t.closeable)return _.createVNode(Jo,{role:"button",tabindex:0,name:t.closeIcon,class:[qa("close-icon",t.closeIconPosition),lx],classPrefix:t.iconPrefix,onClick:M},null)};let B;const G=()=>{B&&clearTimeout(B),B=setTimeout(()=>{r("opened")})},Z=()=>r("closed"),z=V=>r("keydown",V),ee=C(()=>{var V;const{destroyOnClose:U,round:J,position:S,safeAreaInsetTop:Te,safeAreaInsetBottom:ye,show:re}=t;if(!(!re&&U))return _.withDirectives(_.createVNode("div",_.mergeProps({ref:g,style:x.value,role:"dialog",tabindex:0,class:[qa({round:J,[S]:S}),{"van-safe-area-top":Te,"van-safe-area-bottom":ye}],onKeydown:z},o,Xa()),[(V=c.default)==null?void 0:V.call(c),D()]),[[_.vShow,re]])}),K=()=>{const{position:V,transition:U,transitionAppear:J}=t,S=V==="center"?"van-fade":`van-popup-slide-${V}`;return _.createVNode(_.Transition,{name:U||S,appear:J,onAfterEnter:G,onAfterLeave:Z},{default:ee})};return _.watch(()=>t.show,V=>{V&&!u&&(A(),o.tabindex===0&&_.nextTick(()=>{var U;(U=g.value)==null||U.focus()})),!V&&u&&(u=!1,r("close"))}),bu({popupRef:g}),Dx(g,()=>t.show&&t.lockScroll),wu("popstate",()=>{t.closeOnPopstate&&(v(),f=!1)}),_.onMounted(()=>{t.show&&A()}),_.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),_.onDeactivated(()=>{t.show&&t.teleport&&(v(),f=!0)}),_.provide(ux,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[O(),K()]}):_.createVNode(_.Fragment,null,[O(),K()])}});const $x=ii(Zx);let Zr=0;function Hx(t){t?(Zr||document.body.classList.add("van-toast--unclickable"),Zr++):Zr&&(Zr--,Zr||document.body.classList.remove("van-toast--unclickable"))}const[Wx,Sr]=gr("toast"),jx=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Gx={icon:String,show:Boolean,type:dn("text"),overlay:Boolean,message:un,iconSize:un,duration:H2(2e3),position:dn("middle"),teleport:[String,Object],wordBreak:String,className:Oi,iconPrefix:String,transition:dn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Oi,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:un};var Xx=_.defineComponent({name:Wx,props:Gx,emits:["update:show"],setup(t,{emit:r,slots:o}){let c,u=!1;const f=()=>{const v=t.show&&t.forbidClick;u!==v&&(u=v,Hx(u))},m=v=>r("update:show",v),g=()=>{t.closeOnClick&&m(!1)},C=()=>clearTimeout(c),x=()=>{const{icon:v,type:P,iconSize:O,iconPrefix:M,loadingType:D}=t;if(v||P==="success"||P==="fail")return _.createVNode(Jo,{name:v||P,size:O,class:Sr("icon"),classPrefix:M},null);if(P==="loading")return _.createVNode(Ox,{class:Sr("loading"),size:O,type:D},null)},A=()=>{const{type:v,message:P}=t;if(o.message)return _.createVNode("div",{class:Sr("text")},[o.message()]);if(tr(P)&&P!=="")return v==="html"?_.createVNode("div",{key:0,class:Sr("text"),innerHTML:String(P)},null):_.createVNode("div",{class:Sr("text")},[P])};return _.watch(()=>[t.show,t.forbidClick],f),_.watch(()=>[t.show,t.type,t.message,t.duration],()=>{C(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),_.onMounted(f),_.onUnmounted(f),()=>_.createVNode($x,_.mergeProps({class:[Sr([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:g,onClosed:C,"onUpdate:show":m},$2(t,jx)),{default:()=>[x(),A()]})}});function qx(){const t=_.reactive({show:!1}),r=u=>{t.show=u},o=u=>{Pn(t,u,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return bu({open:o,close:c,toggle:r}),{open:o,close:c,state:t,toggle:r}}function Yx(t){const r=_.createApp(t),o=document.createElement("div");return document.body.appendChild(o),{instance:r.mount(o),unmount(){r.unmount(),document.body.removeChild(o)}}}const Kx={icon:"",type:"text",message:"",className:"",overlay:!1,onClose:void 0,onOpened:void 0,duration:2e3,teleport:"body",iconSize:void 0,iconPrefix:void 0,position:"middle",transition:"van-fade",forbidClick:!1,loadingType:void 0,overlayClass:"",overlayStyle:void 0,closeOnClick:!1,closeOnClickOverlay:!1};let Ci=[],Jx=!1,Ya=Pn({},Kx);const Qx=new Map;function Tu(t){return Li(t)?t:{message:t}}function ey(){const{instance:t}=Yx({setup(){const r=_.ref(""),{open:o,state:c,close:u,toggle:f}=qx(),m=()=>{},g=()=>{const C={onClosed:m,"onUpdate:show":f};return _.createVNode(Xx,_.mergeProps(c,C),null)};return _.watch(r,C=>{c.message=C}),_.getCurrentInstance().render=g,{open:o,close:u,message:r}}});return t}function ty(){if(!Ci.length||Jx){const t=ey();Ci.push(t)}return Ci[Ci.length-1]}function Je(t={}){if(!Yo)return{};const r=ty(),o=Tu(t);return r.open(Pn({},Ya,Qx.get(o.type||Ya.type),o)),r}const ny=t=>r=>Je(Pn({type:t},Tu(r))),Nu=ny("loading"),ry=t=>{try{const r=JSON.parse(t),o=[];if(!r.mcpServers||typeof r.mcpServers!="object")throw new Error("JSON 格式错误:缺少 mcpServers 字段");for(const[c,u]of Object.entries(r.mcpServers)){const f=iy(u);f&&o.push({name:c,config:f})}return o}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},iy=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:o,sessionId:c,headers:u}=t;return r==="extension"?c?{type:"extension",url:o,sessionId:c,headers:u,useAISdkClient:!0}:null:r==="streamableHttp"||r==="sse"?{type:r,url:o,headers:u,useAISdkClient:!0}:{type:"streamableHttp",url:o,headers:u,useAISdkClient:!0}},oy=(t,r,o)=>{const c=async(f,m,g,C,x)=>{if(await t.insertMcpServer(f,m)){const v=t.mcpTools[f];if(v){const O={id:`plugin-${f.replace("mcp-server-","")}`,name:g,icon:x||o,description:C||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(v).map(M=>({id:M,name:M,description:v[M].description,enabled:!0})),originMcpConfig:_.markRaw(m)};return r.value.push(O),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{Nu("添加工具中...");try{if(f==="code"){if(typeof m!="string"){Je("添加工具失败:code 类型需要 JSON 字符串格式");return}const Z=ry(m);if(Z.length===0){Je("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let z=0,ee=0;for(const{name:K,config:V}of Z){const U=`mcp-server-${K}`;await c(U,V,K)?z++:ee++}await t.closeAll(),ee===0?Je(`成功添加 ${z} 个工具`):z>0?Je(`成功添加 ${z} 个工具,${ee} 个失败`):Je("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){Je("添加工具失败:数据格式不正确");return}const{description:g,headers:C,name:x,thumbnail:A,type:v,url:P}=m;if(!x||!P||!v){Je("添加工具失败:缺少必要参数(名称、URL或类型)");return}const M=`mcp-server-${`custom-${x}-${Date.now()}`}`;let D;if(typeof C=="string"&&C.trim())try{D=JSON.parse(C)}catch(Z){console.warn("Failed to parse headers JSON:",Z)}else typeof C=="object"&&(D=C);await c(M,{type:v,url:P,headers:D,useAISdkClient:!0},x,g,A)?(await t.closeAll(),Je("添加工具完成")):Je("重复添加工具或无法获取工具列表")}catch(g){console.error("handleCustomAdd error:",g),Je(`添加工具失败:${g instanceof Error?g.message:"未知错误"}`)}}}};function sy(t,r,o){const c=_.ref([]),u=_.ref([]),f=_.ref(!1),m=K=>t.mcpServers[K]?.type==="local",g=(K,V)=>{V?t.ignoreToolnames=t.ignoreToolnames.filter(U=>U!==K):t.ignoreToolnames.includes(K)||t.ignoreToolnames.push(K)},C=(K,V)=>{r.value||(r.value={});const U={...r.value};K===null?Object.keys(U).forEach(J=>{U[J]=V}):U[K]=V,r.value=U},x=K=>{const V=u.value.find(U=>U.id===K);V&&(V.addState="idle")},A=K=>{const V=t.mcpTools[K];if(!V)return[];const U=m(K),J=r.value||{};return Object.keys(V).map(S=>{const Te=Object.prototype.hasOwnProperty.call(J,S),ye=U&&Te?J[S]:!0;return g(S,ye),{id:S,name:S,description:V[S].description,enabled:ye}})},v=()=>{c.value.forEach(V=>{const U=new Map(V.tools.map(S=>[S.id,S.enabled])),J=A(V.id).map(S=>{const Te=U.has(S.id)?!!U.get(S.id):S.enabled;return g(S.id,Te),{...S,enabled:Te}});V.tools=J});const K=new Set(c.value.flatMap(V=>V.tools.map(U=>U.id)));t.ignoreToolnames=t.ignoreToolnames.filter(V=>K.has(V))},P=async K=>{const V=K.pluginId;if(!await t.insertMcpServer(V,K.mcpServer))return!1;if(!t.mcpTools[V])return await t.removeMcpServer(V),!1;const S=A(V);if(S.length===0&&K.mcpServer?.type!=="builtin")return await t.removeMcpServer(V),!1;const Te=c.value.find(re=>re.id===K.pluginId);if(Te)return Te.tools=S,Te.originMcpConfig=_.markRaw(K.mcpServer),!0;const ye={id:K.pluginId,name:K.name,icon:K.icon||o,description:K.description,enabled:!0,expanded:!1,tools:S,originMcpConfig:_.markRaw(K.mcpServer)};return c.value.push(ye),!0};return{installedPlugins:c,marketPlugins:u,pluginVisible:f,loadMcpServerToPlugin:async(K,V)=>{let U=V.name,J=V.description;if(!U||!J){if("type"in V&&V.type==="local")U=U||"本地工具",J=J||"本地工具列表";else if("type"in V&&V.type==="builtin")U=U||"浏览器内置工具",J=J||"通过 navigator.modelContextTesting 暴露的浏览器原生 MCP 工具";else if("url"in V)try{const S=new URL(V.url);U=U||S.origin,J=J||S.searchParams.get("sessionId")||("sessionId"in V?V.sessionId:"")||""}catch(S){console.error("[usePlugin] Failed to parse MCP server URL:",V.url,S),U=U||"未知插件",J=J||""}}await P({pluginId:K,name:U||"",description:J||"",mcpServer:V})},togglePlugin:(K,V)=>{const U=m(K.id);K.tools.forEach(J=>{J.enabled=V,g(J.id,V),U&&C(J.id,V)})},toggleTool:(K,V,U)=>{const J=m(K.id);K.tools.forEach(S=>{S.id===V&&(S.enabled=U)}),g(V,U),J&&C(V,U)},deletePlugin:async K=>{const V=c.value.find(J=>J.id===K.id);if(!V)return;c.value=c.value.filter(J=>J.id!==V.id),x(V.id);const U=K.id;await t.removeMcpServer(U)},addPluginCore:P,addPluginFromMarket:async K=>{K.addState="loading";const V={type:K.type,url:K.url,headers:K.headers,useAISdkClient:!0},U=await P({pluginId:K.id,name:K.name,description:K.description||"",icon:K.icon,mcpServer:V});K.addState=U?"added":"idle"},addPluginFromScan:async(K,V)=>{const U={type:"streamableHttp",url:`${V}mcp?sessionId=${K}`};let J="未知插件";try{J=new URL(`${V}mcp?sessionId=${K}`).origin}catch(S){console.error("[usePlugin] Failed to parse scan URL:",S)}return await P({pluginId:`plugin-${K}`,name:J,description:K,mcpServer:U})},handleClientDisconnected:async K=>{const V=K,U=c.value.find(J=>J.id===V);return await t.removeMcpServer(K),U?(c.value=c.value.filter(J=>J.id!==V),x(V),U):null},searchPlugin:(K,V)=>K.trim()===""||V.name.toLowerCase().includes(K.toLowerCase()),syncInstalledPluginTools:v}}function ay(t){const{onToolCatalogChanged:r}=t,o=typeof window<"u"&&window!==window.top,c=P=>P===window||o&&P===window.parent;let u=!1,f=!1,m=!1;const g=async()=>{if(!(!r||u)){if(f){m=!0;return}f=!0;try{do{m=!1;try{await r()}catch(P){console.warn("[useRouteBasedTools] refresh tool catalog failed:",P)}}while(m&&!u)}finally{f=!1}}},C=P=>{!c(P.source)||P.data?.type!==Vn.MSG_TOOL_REGISTERED&&P.data?.type!==Vn.MSG_TOOL_UNREGISTERED||g()};let x=!1;const A=()=>{x||(u=!1,x=!0,window.addEventListener("message",C),o&&window.parent&&window.parent.postMessage({type:Vn.MSG_REMOTER_READY},"*"))},v=()=>{x&&(u=!0,m=!1,x=!1,window.removeEventListener("message",C))};_.onMounted(()=>{A()}),_.onUnmounted(()=>{v()})}function ly(t){const{skillsRef:r,customAgentProvider:o}=t,c=_.computed(async()=>{const g=r?.value;return g?await Vn.getSkillOverviews(g):[]}),u=_.computed(()=>{const g=c.value;return g.length>0?Vn.formatSkillsForSystemPrompt(g):""}),f=_.computed(()=>{const g=r?.value;return g?Vn.createSkillTools(g):{}});return _.watchEffect(()=>{if(o.promptManager.setSkillMeta(u.value),o.llmConfig){const g=o.llmConfig.extraTools??{};o.llmConfig.extraTools={...g,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:u,skillTools:f,skillOverviews:c}}const cy=["title"],uy=_.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,o=_.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:g=0,inputTokenDetails:C,outputTokenDetails:x}=r.usage,A=C?.cacheReadTokens||0,v=x?.reasoningTokens||0;return{cachedInputTokens:[A/g*100+"%",A],inputTokens:[(f-A)/g*100+"%",f],reasoningTokens:[v/g*100+"%",v],outputTokens:[(m-v)/g*100+"%",m]}}),u=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:g=0,inputTokenDetails:C,outputTokenDetails:x}=r.usage,A=C?.cacheReadTokens||0,v=x?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${g}`,`cachedInputTokens: ${A}`,`reasoningTokens: ${v}`].join(`
56
- `)});return(f,m)=>o.value?_.createCommentVNode("",!0):(_.openBlock(),_.createElementBlock("div",{key:0,class:"token-usage-wrap",title:u.value},[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(c.value,(g,C)=>(_.openBlock(),_.createElementBlock("div",{key:C,class:_.normalizeClass(C),style:_.normalizeStyle({width:g[0]})},null,6))),128))],8,cy))}}),nr=(t,r)=>{const o=t.__vccOpts||t;for(const[c,u]of r)o[c]=u;return o},dy=nr(uy,[["__scopeId","data-v-000098b4"]]),fy={width:"100.000000",height:"100.000000",viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"};function hy(t,r){return _.openBlock(),_.createElementBlock("svg",fy,[...r[0]||(r[0]=[_.createStaticVNode('<desc> Created with Pixso. </desc><defs><radialGradient gradientTransform="translate(32.4474 65.1156) rotate(128.932) scale(22.991 20.6919)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3090_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient><linearGradient x1="30.999874" y1="85.000229" x2="30.499891" y2="70.500214" id="paint_linear_9_3092_0" gradientUnits="userSpaceOnUse"><stop stop-color="#000000" stop-opacity="0.000000"></stop><stop offset="1.000000" stop-color="#000000"></stop></linearGradient><radialGradient gradientTransform="translate(26.9999 24.7118) rotate(38.3655) scale(77.7996 109.496)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3094_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient></defs><rect id="NEXT-LOGO-无背景渐变-右" width="100.000000" height="99.999939" transform="matrix(-1 0 0 1 100 0)" fill="#FFFFFF" fill-opacity="0"></rect>',3),_.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[_.createElementVNode("rect",{id:"画板 1773",width:"99.999962",height:"99.999947",transform:"matrix(-1 0 0 1 100 6.10352e-05)",fill:"#000000","fill-opacity":"1.000000"})],-1),_.createStaticVNode('<g mask="url(#mask9_3088)"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_radial_9_3090_0)" fill-opacity="1.000000" fill-rule="evenodd"></path><g opacity="0.100000" style="mix-blend-mode:normal;"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_linear_9_3092_0)" fill-opacity="1.000000" fill-rule="evenodd"></path></g><rect id="矩形 5" x="12.000000" y="19.000183" rx="26.999992" width="75.999977" height="53.999985" fill="url(#paint_radial_9_3094_0)" fill-opacity="1.000000"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" fill="#000000" fill-opacity="0"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" stroke="#000000" stroke-opacity="0" stroke-width="1.000000"></rect><path id="path" d="M45.39 59.06C44.22 60.05 42.9 60.66 41.43 60.89C39.95 61.12 38.57 61.04 37.28 60.65C36 60.26 34.04 58.58 34.04 58.58C34.04 58.58 29.02 54.73 29.02 45.61C29.02 36.5 33.5 32.5 33.5 32.5C33.5 32.5 34.72 31.31 36.5 31C38.29 30.68 39.43 30.98 40.66 31.33C50.89 34.23 62.38 34.33 72.58 31.33C73.81 30.98 74.91 30.93 75.89 31.17C76.87 31.42 77.71 31.89 78.42 32.59C81.65 35.81 82.87 41.06 83 45.61C83.12 50.09 81.97 55.24 78.94 58.54C78.04 59.52 76.98 60.22 75.78 60.63C74.58 61.04 73.32 61.12 71.99 60.89C70.66 60.66 69.48 60.05 68.46 59.06C68.01 58.62 67.39 58.07 66.57 57.4C65.76 56.73 64.83 56.08 63.79 55.44C62.75 54.8 61.62 54.25 60.39 53.8C59.16 53.35 57.91 53.13 56.62 53.13C55.36 53.13 54.16 53.36 53 53.83C51.85 54.29 50.79 54.84 49.82 55.48C48.86 56.12 48 56.78 47.26 57.45C46.51 58.11 45.89 58.65 45.39 59.06Z" fill="#FFFFFF" fill-opacity="1.000000" fill-rule="nonzero"></path><rect id="矩形 841" rx="2.000000" width="3.999999" height="11.999996" transform="matrix(-0.999983 0.00577157 0.00577157 0.999983 76.1109 38.0356)" fill="#1476FF" fill-opacity="1.000000"></rect><path id="合并" d="M42.96 38C43.77 37.97 44.55 38.42 44.92 39.19L48.73 47.11C49.22 48.13 48.79 49.34 47.75 49.81C46.72 50.28 45.48 49.83 44.99 48.8L42.96 44.59L40.94 48.81C40.45 49.83 39.21 50.28 38.18 49.81C37.14 49.34 36.7 48.13 37.2 47.11L41 39.19C41.37 38.42 42.16 37.98 42.96 38Z" fill="#1476FF" fill-opacity="1.000000" fill-rule="evenodd"></path></g>',1)])])}const Ou={render:hy};function py(t){const{messages:r,messageState:o,inputMessage:c,handleSendMessage:u}=t,f=_.h(Ou,{style:{width:"48px",height:"48px"}}),m=_.ref({}),g=_.computed(()=>Jn.GeneratingStatus.includes(o.status)),C=_.computed(()=>r.value.findLastIndex(O=>O.role==="assistant")),x=O=>O===void 0?"复制":m.value[O]?"复制成功":"复制",A=async O=>{const D=r.value[O].uiContent.map(B=>B.content).join(`
57
- `);try{await navigator.clipboard.writeText(D),O!==void 0&&(m.value[O]=!0,setTimeout(()=>{m.value[O]=!1},3e3))}catch(B){console.error("复制失败:",B),Je("复制失败,请重试")}},v=async O=>{const M=r.value.findLastIndex((B,G)=>B.role==="user"&&G<=O);if(M===-1){console.warn("未找到可重新生成的用户消息"),Je("无法重新生成消息");return}const D=r.value[M];if(r.value=r.value.slice(0,M),Array.isArray(D.content)){const G=D.content.find(z=>z.type==="text")?.text||"",Z=D.content.filter(z=>z.type!=="text");c.value=G,await u(G,Z.length>0?Z:void 0)}else c.value=D.content,await u(D.content)},P={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:O})=>{const M=C.value===O;return g.value&&M?"":_.h("div",{class:["assistant-actions",{"latest-assistant":M,"historical-assistant":!M}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[_.h(Ut.IconButton,{icon:Or.IconRefresh,size:24,onClick:()=>v(O)}),_.h(fd,{effect:"light",content:x(O),placement:"right",visibleArrow:!1},()=>_.h(Ut.IconButton,{icon:Or.IconCopy,size:24,onClick:()=>A(O)})),r.value[O].usage?_.h(dy,{usage:r.value[O].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:P,copyingStates:m,isProcessing:g,latestAssistantMessageIndex:C,copyTooltipContent:x,copyMessageToClipboard:A,regenerateMessage:v}}function my(t){const{createConversation:r,switchConversation:o,deleteConversation:c,getCurrentConversation:u,abortRequest:f,conversationState:m,customAgentProvider:g}=t,C=_.ref(!1),x=()=>{_.nextTick(()=>{const M=document.querySelector("div.tr-bubble-list");M&&M.scrollTo({top:M.scrollHeight,behavior:"smooth"})})};return{showHistory:C,handleCreateConversation:()=>{f();const M=[];g.agent.responseMessages=M,r();const D=u();D.aiSdkMessages=M},handleHistorySelect:M=>{f(),o(M.id);const D=u();g.agent.responseMessages=D.aiSdkMessages,C.value=!1,x()},handleHistoryUpdateTitle:(M,D)=>{D.title=M},handleHistoryDelete:(M,D)=>{if(M.id==="delete"){if(m.currentId===D.id){Je("不允许删除当前会话");return}c(D.id)}},scrollToBottom:x}}function gy(t){const{sessionId:r,agentRoot:o,mode:c,qrCodeUrl:u,remoteUrl:f,menuItems:m,AILogoUrl:g,show:C,addPluginFromScan:x,inputMessage:A}=t;let v=null,P=!1;const O=async Z=>{if(Nu("添加工具中..."),Z){const z=await x(Z,o);Je(z?"添加工具完成":"重复添加工具或添加失败")}else Je("添加工具失败")},M=async Z=>{if(/^\/[A-Za-z0-9-]{6,}$/.test(Z)){try{const z=await fetch(`${o}client?sessionId=${Z.slice(1)}`);if(!z.ok)throw new Error(`HTTP ${z.status}`);const K=(await z.json())?.data?.sessionId;K?await O(K):Je("添加工具失败,请检查识别码是否正确"),A.value=""}catch(z){console.error("识别码处理失败:",z),Je("添加工具失败,请检查识别码是否正确"),A.value=""}return!0}return!1},D=()=>{const Z=z=>{v&&(v.destroy(),v=null),v=Vn.createRemoter({sessionId:z||void 0,qrCodeUrl:u,remoteUrl:f,menuItems:m?.value,logoUrl:g,onShowAIChat:()=>C.value=!0}),C.value&&v.hide()};_.watch(r,z=>{if(c!=="remoter")return;const ee=!!z;v?!P&&ee&&(Z(z),P=!0):(Z(z),P=ee)},{immediate:!0}),m&&_.watch(m,()=>{c==="remoter"&&v&&Z(r.value)},{deep:!0}),_.watch(C,z=>{v&&(z?v.hide():v.show())},{immediate:!0})},B=()=>{_.watch(r,Z=>{Z&&O(Z)})};return{handleScanSuccess:O,handleSessionIdInput:M,initialize:()=>{r.value&&O(r.value),c==="remoter"&&D(),B()},initializeRemoter:D,watchSessionIdChanges:B}}function xy(t){return new Promise((r,o)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=o,c.readAsDataURL(t)})}function yy(t){return t.type.startsWith("image/")}function wy(t,r){const o=r*1024*1024;return t.size<=o}async function _y(t){if(t.length===0)return[];const r=[];for(const o of t)if(o.rawFile)try{const c=await xy(o.rawFile);yy(o.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),Je({type:"fail",message:"文件处理失败"})}return r}function vy(t={}){const r=_.ref([]),o=async u=>{if(!u||u.length===0)return;c();const f=_.unref(t.maxFileSize)||10,m=_.unref(t.supportedTypes)||["image/"];for(const g of u){if(!m.some(x=>g.type.startsWith(x))){Je({type:"fail",message:`不支持的文件类型: ${g.type}`});continue}if(!wy(g,f)){Je({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:g,url:URL.createObjectURL(g)})}},c=()=>{r.value.forEach(u=>{u.url&&URL.revokeObjectURL(u.url)}),r.value=[]};return{attachments:r,handleFilesSelected:o,clearAttachments:c}}function Cy(t){const{selectedModel:r,selectedModelId:o}=t,c=_.computed(()=>r.value?.multimodal?.supportImages??!1),u=_.computed(()=>r.value?.multimodal?.maxFileSize||10),f=_.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:m,handleFilesSelected:g,clearAttachments:C}=vy({maxFileSize:u,supportedTypes:f});return _.watch(o,()=>{if(m.value.length>0&&r.value){const O=r.value.multimodal?.maxFileSize||10,M=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(B=>{if(!B.rawFile||!M.some(z=>B.rawFile.type.startsWith(z)))return!0;const Z=O*1024*1024;return B.rawFile.size>Z}).length>0&&(C(),Je("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:O=>{g(O)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(Je("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await _y(m.value),cleanupAttachments:()=>{m.value.length>0&&C()},clearAttachments:C}}var _e;(function(t){t[t.QR_CODE=0]="QR_CODE",t[t.AZTEC=1]="AZTEC",t[t.CODABAR=2]="CODABAR",t[t.CODE_39=3]="CODE_39",t[t.CODE_93=4]="CODE_93",t[t.CODE_128=5]="CODE_128",t[t.DATA_MATRIX=6]="DATA_MATRIX",t[t.MAXICODE=7]="MAXICODE",t[t.ITF=8]="ITF",t[t.EAN_13=9]="EAN_13",t[t.EAN_8=10]="EAN_8",t[t.PDF_417=11]="PDF_417",t[t.RSS_14=12]="RSS_14",t[t.RSS_EXPANDED=13]="RSS_EXPANDED",t[t.UPC_A=14]="UPC_A",t[t.UPC_E=15]="UPC_E",t[t.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(_e||(_e={}));var Ka=new Map([[_e.QR_CODE,"QR_CODE"],[_e.AZTEC,"AZTEC"],[_e.CODABAR,"CODABAR"],[_e.CODE_39,"CODE_39"],[_e.CODE_93,"CODE_93"],[_e.CODE_128,"CODE_128"],[_e.DATA_MATRIX,"DATA_MATRIX"],[_e.MAXICODE,"MAXICODE"],[_e.ITF,"ITF"],[_e.EAN_13,"EAN_13"],[_e.EAN_8,"EAN_8"],[_e.PDF_417,"PDF_417"],[_e.RSS_14,"RSS_14"],[_e.RSS_EXPANDED,"RSS_EXPANDED"],[_e.UPC_A,"UPC_A"],[_e.UPC_E,"UPC_E"],[_e.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),Ja;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(Ja||(Ja={}));function by(t){return Object.values(_e).includes(t)}var ei;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(ei||(ei={}));var Ey=(function(){function t(){}return t.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",t.SCAN_DEFAULT_FPS=2,t.DEFAULT_DISABLE_FLIP=!1,t.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,t.DEFAULT_SUPPORTED_SCAN_TYPE=[ei.SCAN_TYPE_CAMERA,ei.SCAN_TYPE_FILE],t})(),ku=(function(){function t(r,o){this.format=r,this.formatName=o}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!Ka.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,Ka.get(r))},t})(),Qa=(function(){function t(){}return t.createFromText=function(r){var o={text:r};return{decodedText:r,result:o}},t.createFromQrcodeResult=function(r){return{decodedText:r.text,result:r}},t})(),Mo;(function(t){t[t.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",t[t.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",t[t.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(Mo||(Mo={}));var Ay=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Mo.UNKWOWN_ERROR}},t})(),Iy=(function(){function t(r){this.verbose=r}return t.prototype.log=function(r){this.verbose&&console.log(r)},t.prototype.warn=function(r){this.verbose&&console.warn(r)},t.prototype.logError=function(r,o){(this.verbose||o===!0)&&console.error(r)},t.prototype.logErrors=function(r){if(r.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(r)},t})();function Fn(t){return typeof t>"u"||t===null}var Nr=(function(){function t(){}return t.codeParseError=function(r){return"QR code parse error, error = ".concat(r)},t.errorGettingUserMedia=function(r){return"Error getting userMedia, error = ".concat(r)},t.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},t.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},t.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},t.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},t.scannerPaused=function(){return"Scanner paused"},t})(),Ru=(function(){function t(){}return t.isMediaStreamConstraintsValid=function(r,o){if(typeof r!="object"){var c=typeof r;return o.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(c,"."),!0),!1}for(var u=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],f=new Set(u),m=Object.keys(r),g=0,C=m;g<C.length;g++){var x=C[g];if(f.has(x))return o.logError("".concat(x," is not supported videoConstaints."),!0),!1}return!0},t})(),bi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Sy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Hr={exports:{}},Ty=Hr.exports,el;function Ny(){return el||(el=1,(function(t,r){(function(o,c){c(r)})(Ty,(function(o){function c(b){return b==null}var u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var n in e)e.hasOwnProperty(n)&&(b[n]=e[n])};function f(b,e){u(b,e);function n(){this.constructor=b}b.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(b,e){var n=Object.setPrototypeOf;n?n(b,e):b.__proto__=e}function g(b,e){e===void 0&&(e=b.constructor);var n=Error.captureStackTrace;n&&n(b,e)}var C=(function(b){f(e,b);function e(n){var i=this.constructor,s=b.call(this,n)||this;return Object.defineProperty(s,"name",{value:i.name,enumerable:!1}),m(s,i.prototype),g(s),s}return e})(Error);class x extends C{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}x.kind="Exception";class A extends x{}A.kind="ArgumentException";class v extends x{}v.kind="IllegalArgumentException";class P{constructor(e){if(this.binarizer=e,e===null)throw new v("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,i,s){const a=this.binarizer.getLuminanceSource().crop(e,n,i,s);return new P(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new P(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new P(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class O extends x{static getChecksumInstance(){return new O}}O.kind="ChecksumException";class M{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class D{static arraycopy(e,n,i,s,a){for(;a--;)i[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class B extends x{}B.kind="IndexOutOfBoundsException";class G extends B{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}G.kind="ArrayIndexOutOfBoundsException";class Z{static fill(e,n){for(let i=0,s=e.length;i<s;i++)e[i]=n}static fillWithin(e,n,i,s){Z.rangeCheck(e.length,n,i);for(let a=n;a<i;a++)e[a]=s}static rangeCheck(e,n,i){if(n>i)throw new v("fromIndex("+n+") > toIndex("+i+")");if(n<0)throw new G(n);if(i>e)throw new G(i)}static asList(...e){return e}static create(e,n,i){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(i))}static createInt32Array(e,n,i){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(i))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let i=0,s=e.length;i<s;i++)if(e[i]!==n[i])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const i of e)n=31*n+i;return n}static fillUint8Array(e,n){for(let i=0;i!==e.length;i++)e[i]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const i=new Uint8Array(n);return i.set(e),i}return e.slice(0,n)}static copyOfRange(e,n,i){const s=i-n,a=new Int32Array(s);return D.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,i){i===void 0&&(i=Z.numberComparator);let s=0,a=e.length-1;for(;s<=a;){const l=a+s>>1,d=i(n,e[l]);if(d>0)s=l+1;else if(d<0)a=l-1;else return l}return-s-1}static numberComparator(e,n){return e-n}}class z{static numberOfTrailingZeros(e){let n;if(e===0)return 32;let i=31;return n=e<<16,n!==0&&(i-=16,e=n),n=e<<8,n!==0&&(i-=8,e=n),n=e<<4,n!==0&&(i-=4,e=n),n=e<<2,n!==0&&(i-=2,e=n),i-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let n=1;return e>>>16||(n+=16,e<<=16),e>>>24||(n+=8,e<<=8),e>>>28||(n+=4,e<<=4),e>>>30||(n+=2,e<<=2),n-=e>>>31,n}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,n){return Math.trunc(e/n)}static parseInt(e,n=void 0){return parseInt(e,n)}}z.MIN_VALUE_32_BITS=-2147483648,z.MAX_VALUE=Number.MAX_SAFE_INTEGER;class ee{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=ee.makeArray(e):this.bits=n)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const n=ee.makeArray(e);D.arraycopy(this.bits,0,n,0,this.bits.length),this.bits=n}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const n=this.size;if(e>=n)return n;const i=this.bits;let s=Math.floor(e/32),a=i[s];a&=~((1<<(e&31))-1);const l=i.length;for(;a===0;){if(++s===l)return n;a=i[s]}const d=s*32+z.numberOfTrailingZeros(a);return d>n?n:d}getNextUnset(e){const n=this.size;if(e>=n)return n;const i=this.bits;let s=Math.floor(e/32),a=~i[s];a&=~((1<<(e&31))-1);const l=i.length;for(;a===0;){if(++s===l)return n;a=~i[s]}const d=s*32+z.numberOfTrailingZeros(a);return d>n?n:d}setBulk(e,n){this.bits[Math.floor(e/32)]=n}setRange(e,n){if(n<e||e<0||n>this.size)throw new v;if(n===e)return;n--;const i=Math.floor(e/32),s=Math.floor(n/32),a=this.bits;for(let l=i;l<=s;l++){const d=l>i?0:e&31,p=(2<<(l<s?31:n&31))-(1<<d);a[l]|=p}}clear(){const e=this.bits.length,n=this.bits;for(let i=0;i<e;i++)n[i]=0}isRange(e,n,i){if(n<e||e<0||n>this.size)throw new v;if(n===e)return!0;n--;const s=Math.floor(e/32),a=Math.floor(n/32),l=this.bits;for(let d=s;d<=a;d++){const h=d>s?0:e&31,y=(2<<(d<a?31:n&31))-(1<<h)&4294967295;if((l[d]&y)!==(i?y:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,n){if(n<0||n>32)throw new v("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(let i=n;i>0;i--)this.appendBit((e>>i-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let i=0;i<n;i++)this.appendBit(e.get(i))}xor(e){if(this.size!==e.size)throw new v("Sizes don't match");const n=this.bits;for(let i=0,s=n.length;i<s;i++)n[i]^=e.bits[i]}toBytes(e,n,i,s){for(let a=0;a<s;a++){let l=0;for(let d=0;d<8;d++)this.get(e)&&(l|=1<<7-d),e++;n[i+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),i=n+1,s=this.bits;for(let a=0;a<i;a++){let l=s[a];l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,e[n-a]=l}if(this.size!==i*32){const a=i*32-this.size;let l=e[0]>>>a;for(let d=1;d<i;d++){const h=e[d];l|=h<<32-a,e[d-1]=l,l=h>>>a}e[i-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof ee))return!1;const n=e;return this.size===n.size&&Z.equals(this.bits,n.bits)}hashCode(){return 31*this.size+Z.hashCode(this.bits)}toString(){let e="";for(let n=0,i=this.size;n<i;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new ee(this.size,this.bits.slice())}}var K;(function(b){b[b.OTHER=0]="OTHER",b[b.PURE_BARCODE=1]="PURE_BARCODE",b[b.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",b[b.TRY_HARDER=3]="TRY_HARDER",b[b.CHARACTER_SET=4]="CHARACTER_SET",b[b.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",b[b.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",b[b.ASSUME_GS1=7]="ASSUME_GS1",b[b.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",b[b.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",b[b.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(K||(K={}));var V=K;class U extends x{static getFormatInstance(){return new U}}U.kind="FormatException";var J;(function(b){b[b.Cp437=0]="Cp437",b[b.ISO8859_1=1]="ISO8859_1",b[b.ISO8859_2=2]="ISO8859_2",b[b.ISO8859_3=3]="ISO8859_3",b[b.ISO8859_4=4]="ISO8859_4",b[b.ISO8859_5=5]="ISO8859_5",b[b.ISO8859_6=6]="ISO8859_6",b[b.ISO8859_7=7]="ISO8859_7",b[b.ISO8859_8=8]="ISO8859_8",b[b.ISO8859_9=9]="ISO8859_9",b[b.ISO8859_10=10]="ISO8859_10",b[b.ISO8859_11=11]="ISO8859_11",b[b.ISO8859_13=12]="ISO8859_13",b[b.ISO8859_14=13]="ISO8859_14",b[b.ISO8859_15=14]="ISO8859_15",b[b.ISO8859_16=15]="ISO8859_16",b[b.SJIS=16]="SJIS",b[b.Cp1250=17]="Cp1250",b[b.Cp1251=18]="Cp1251",b[b.Cp1252=19]="Cp1252",b[b.Cp1256=20]="Cp1256",b[b.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",b[b.UTF8=22]="UTF8",b[b.ASCII=23]="ASCII",b[b.Big5=24]="Big5",b[b.GB18030=25]="GB18030",b[b.EUC_KR=26]="EUC_KR"})(J||(J={}));class S{constructor(e,n,i,...s){this.valueIdentifier=e,this.name=i,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,S.VALUE_IDENTIFIER_TO_ECI.set(e,this),S.NAME_TO_ECI.set(i,this);const a=this.values;for(let l=0,d=a.length;l!==d;l++){const h=a[l];S.VALUES_TO_ECI.set(h,this)}for(const l of s)S.NAME_TO_ECI.set(l,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new U("incorect value");const n=S.VALUES_TO_ECI.get(e);if(n===void 0)throw new U("incorect value");return n}static getCharacterSetECIByName(e){const n=S.NAME_TO_ECI.get(e);if(n===void 0)throw new U("incorect value");return n}equals(e){if(!(e instanceof S))return!1;const n=e;return this.getName()===n.getName()}}S.VALUE_IDENTIFIER_TO_ECI=new Map,S.VALUES_TO_ECI=new Map,S.NAME_TO_ECI=new Map,S.Cp437=new S(J.Cp437,Int32Array.from([0,2]),"Cp437"),S.ISO8859_1=new S(J.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),S.ISO8859_2=new S(J.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),S.ISO8859_3=new S(J.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),S.ISO8859_4=new S(J.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),S.ISO8859_5=new S(J.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),S.ISO8859_6=new S(J.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),S.ISO8859_7=new S(J.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),S.ISO8859_8=new S(J.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),S.ISO8859_9=new S(J.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),S.ISO8859_10=new S(J.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),S.ISO8859_11=new S(J.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),S.ISO8859_13=new S(J.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),S.ISO8859_14=new S(J.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),S.ISO8859_15=new S(J.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),S.ISO8859_16=new S(J.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),S.SJIS=new S(J.SJIS,20,"SJIS","Shift_JIS"),S.Cp1250=new S(J.Cp1250,21,"Cp1250","windows-1250"),S.Cp1251=new S(J.Cp1251,22,"Cp1251","windows-1251"),S.Cp1252=new S(J.Cp1252,23,"Cp1252","windows-1252"),S.Cp1256=new S(J.Cp1256,24,"Cp1256","windows-1256"),S.UnicodeBigUnmarked=new S(J.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),S.UTF8=new S(J.UTF8,26,"UTF8","UTF-8"),S.ASCII=new S(J.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),S.Big5=new S(J.Big5,28,"Big5"),S.GB18030=new S(J.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),S.EUC_KR=new S(J.EUC_KR,30,"EUC_KR","EUC-KR");class Te extends x{}Te.kind="UnsupportedOperationException";class ye{static decode(e,n){const i=this.encodingName(n);return this.customDecoder?this.customDecoder(e,i):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(i)?this.decodeFallback(e,i):new TextDecoder(i).decode(e)}static shouldDecodeOnFallback(e){return!ye.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const i=this.encodingName(n);return this.customEncoder?this.customEncoder(e,i):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof S?e:S.getCharacterSetECIByName(e)}static decodeFallback(e,n){const i=this.encodingCharacterSet(n);if(ye.isDecodeFallbackSupported(i)){let s="";for(let a=0,l=e.length;a<l;a++){let d=e[a].toString(16);d.length<2&&(d="0"+d),s+="%"+d}return decodeURIComponent(s)}if(i.equals(S.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new Te(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(S.UTF8)||e.equals(S.ISO8859_1)||e.equals(S.ASCII)}static encodeFallback(e){const i=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<i.length;a++)s.push(i[a].charCodeAt(0));return new Uint8Array(s)}}class re{static castAsNonUtf8Char(e,n=null){const i=n?n.getName():this.ISO88591;return ye.decode(new Uint8Array([e]),i)}static guessEncoding(e,n){if(n!=null&&n.get(V.CHARACTER_SET)!==void 0)return n.get(V.CHARACTER_SET).toString();const i=e.length;let s=!0,a=!0,l=!0,d=0,h=0,p=0,y=0,E=0,I=0,k=0,L=0,F=0,H=0,Y=0;const le=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let ce=0;ce<i&&(s||a||l);ce++){const ae=e[ce]&255;l&&(d>0?(ae&128)===0?l=!1:d--:(ae&128)!==0&&((ae&64)===0?l=!1:(d++,(ae&32)===0?h++:(d++,(ae&16)===0?p++:(d++,(ae&8)===0?y++:l=!1))))),s&&(ae>127&&ae<160?s=!1:ae>159&&(ae<192||ae===215||ae===247)&&Y++),a&&(E>0?ae<64||ae===127||ae>252?a=!1:E--:ae===128||ae===160||ae>239?a=!1:ae>160&&ae<224?(I++,L=0,k++,k>F&&(F=k)):ae>127?(E++,k=0,L++,L>H&&(H=L)):(k=0,L=0))}return l&&d>0&&(l=!1),a&&E>0&&(a=!1),l&&(le||h+p+y>0)?re.UTF8:a&&(re.ASSUME_SHIFT_JIS||F>=3||H>=3)?re.SHIFT_JIS:s&&a?F===2&&I===2||Y*10>=i?re.SHIFT_JIS:re.ISO88591:s?re.ISO88591:a?re.SHIFT_JIS:l?re.UTF8:re.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let i=-1;function s(l,d,h,p,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,k;switch(E){case"s":k=n[i];break;case"c":k=n[i][0];break;case"f":k=parseFloat(n[i]).toFixed(l);break;case"p":k=parseFloat(n[i]).toPrecision(l);break;case"e":k=parseFloat(n[i]).toExponential(l);break;case"x":k=parseInt(n[i]).toString(I||16);break;case"d":k=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}k=typeof k=="object"?JSON.stringify(k):(+k).toString(I);let L=parseInt(h),F=h&&h[0]+""=="0"?"0":" ";for(;k.length<L;)k=d!==void 0?k+F:F+k;return k}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return ye.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}re.SHIFT_JIS=S.SJIS.getName(),re.GB2312="GB2312",re.ISO88591=S.ISO8859_1.getName(),re.EUC_JP="EUC_JP",re.UTF8=S.UTF8.getName(),re.PLATFORM_DEFAULT_ENCODING=re.UTF8,re.ASSUME_SHIFT_JIS=!1;class xe{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=re.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,n,i){for(let s=n;n<n+i;s++)this.append(e[s]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+1)}substring(e,n){return this.value.substring(e,n)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+n.length)}}class Me{constructor(e,n,i,s){if(this.width=e,this.height=n,this.rowSize=i,this.bits=s,n==null&&(n=e),this.height=n,e<1||n<1)throw new v("Both dimensions must be greater than 0");i==null&&(i=Math.floor((e+31)/32)),this.rowSize=i,s==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const n=e.length,i=e[0].length,s=new Me(i,n);for(let a=0;a<n;a++){const l=e[a];for(let d=0;d<i;d++)l[d]&&s.set(d,a)}return s}static parseFromString(e,n,i){if(e===null)throw new v("stringRepresentation cannot be null");const s=new Array(e.length);let a=0,l=0,d=-1,h=0,p=0;for(;p<e.length;)if(e.charAt(p)===`
58
- `||e.charAt(p)==="\r"){if(a>l){if(d===-1)d=a-l;else if(a-l!==d)throw new v("row lengths do not match");l=a,h++}p++}else if(e.substring(p,p+n.length)===n)p+=n.length,s[a]=!0,a++;else if(e.substring(p,p+i.length)===i)p+=i.length,s[a]=!1,a++;else throw new v("illegal character encountered: "+e.substring(p));if(a>l){if(d===-1)d=a-l;else if(a-l!==d)throw new v("row lengths do not match");h++}const y=new Me(d,h);for(let E=0;E<a;E++)s[E]&&y.set(Math.floor(E%d),Math.floor(E/d));return y}get(e,n){const i=n*this.rowSize+Math.floor(e/32);return(this.bits[i]>>>(e&31)&1)!==0}set(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]|=1<<(e&31)&4294967295}unset(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]&=~(1<<(e&31)&4294967295)}flip(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]^=1<<(e&31)&4294967295}xor(e){if(this.width!==e.getWidth()||this.height!==e.getHeight()||this.rowSize!==e.getRowSize())throw new v("input matrix dimensions do not match");const n=new ee(Math.floor(this.width/32)+1),i=this.rowSize,s=this.bits;for(let a=0,l=this.height;a<l;a++){const d=a*i,h=e.getRow(a,n).getBitArray();for(let p=0;p<i;p++)s[d+p]^=h[p]}}clear(){const e=this.bits,n=e.length;for(let i=0;i<n;i++)e[i]=0}setRegion(e,n,i,s){if(n<0||e<0)throw new v("Left and top must be nonnegative");if(s<1||i<1)throw new v("Height and width must be at least 1");const a=e+i,l=n+s;if(l>this.height||a>this.width)throw new v("The region must fit inside the matrix");const d=this.rowSize,h=this.bits;for(let p=n;p<l;p++){const y=p*d;for(let E=e;E<a;E++)h[y+Math.floor(E/32)]|=1<<(E&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new ee(this.width):n.clear();const i=this.rowSize,s=this.bits,a=e*i;for(let l=0;l<i;l++)n.setBulk(l*32,s[a+l]);return n}setRow(e,n){D.arraycopy(n.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),n=this.getHeight();let i=new ee(e),s=new ee(e);for(let a=0,l=Math.floor((n+1)/2);a<l;a++)i=this.getRow(a,i),s=this.getRow(n-1-a,s),i.reverse(),s.reverse(),this.setRow(a,s),this.setRow(n-1-a,i)}getEnclosingRectangle(){const e=this.width,n=this.height,i=this.rowSize,s=this.bits;let a=e,l=n,d=-1,h=-1;for(let p=0;p<n;p++)for(let y=0;y<i;y++){const E=s[p*i+y];if(E!==0){if(p<l&&(l=p),p>h&&(h=p),y*32<a){let I=0;for(;(E<<31-I&4294967295)===0;)I++;y*32+I<a&&(a=y*32+I)}if(y*32+31>d){let I=31;for(;!(E>>>I);)I--;y*32+I>d&&(d=y*32+I)}}}return d<a||h<l?null:Int32Array.from([a,l,d-a+1,h-l+1])}getTopLeftOnBit(){const e=this.rowSize,n=this.bits;let i=0;for(;i<n.length&&n[i]===0;)i++;if(i===n.length)return null;const s=i/e;let a=i%e*32;const l=n[i];let d=0;for(;(l<<31-d&4294967295)===0;)d++;return a+=d,Int32Array.from([a,s])}getBottomRightOnBit(){const e=this.rowSize,n=this.bits;let i=n.length-1;for(;i>=0&&n[i]===0;)i--;if(i<0)return null;const s=Math.floor(i/e);let a=Math.floor(i%e)*32;const l=n[i];let d=31;for(;!(l>>>d);)d--;return a+=d,Int32Array.from([a,s])}getWidth(){return this.width}getHeight(){return this.height}getRowSize(){return this.rowSize}equals(e){if(!(e instanceof Me))return!1;const n=e;return this.width===n.width&&this.height===n.height&&this.rowSize===n.rowSize&&Z.equals(this.bits,n.bits)}hashCode(){let e=this.width;return e=31*e+this.width,e=31*e+this.height,e=31*e+this.rowSize,e=31*e+Z.hashCode(this.bits),e}toString(e="X ",n=" ",i=`
59
- `){return this.buildToString(e,n,i)}buildToString(e,n,i){let s=new xe;for(let a=0,l=this.height;a<l;a++){for(let d=0,h=this.width;d<h;d++)s.append(this.get(d,a)?e:n);s.append(i)}return s.toString()}clone(){return new Me(this.width,this.height,this.rowSize,this.bits.slice())}}class $ extends x{static getNotFoundInstance(){return new $}}$.kind="NotFoundException";class ge extends M{constructor(e){super(e),this.luminances=ge.EMPTY,this.buckets=new Int32Array(ge.LUMINANCE_BUCKETS)}getBlackRow(e,n){const i=this.getLuminanceSource(),s=i.getWidth();n==null||n.getSize()<s?n=new ee(s):n.clear(),this.initArrays(s);const a=i.getRow(e,this.luminances),l=this.buckets;for(let h=0;h<s;h++)l[(a[h]&255)>>ge.LUMINANCE_SHIFT]++;const d=ge.estimateBlackPoint(l);if(s<3)for(let h=0;h<s;h++)(a[h]&255)<d&&n.set(h);else{let h=a[0]&255,p=a[1]&255;for(let y=1;y<s-1;y++){const E=a[y+1]&255;(p*4-h-E)/2<d&&n.set(y),h=p,p=E}}return n}getBlackMatrix(){const e=this.getLuminanceSource(),n=e.getWidth(),i=e.getHeight(),s=new Me(n,i);this.initArrays(n);const a=this.buckets;for(let h=1;h<5;h++){const p=Math.floor(i*h/5),y=e.getRow(p,this.luminances),E=Math.floor(n*4/5);for(let I=Math.floor(n/5);I<E;I++){const k=y[I]&255;a[k>>ge.LUMINANCE_SHIFT]++}}const l=ge.estimateBlackPoint(a),d=e.getMatrix();for(let h=0;h<i;h++){const p=h*n;for(let y=0;y<n;y++)(d[p+y]&255)<l&&s.set(y,h)}return s}createBinarizer(e){return new ge(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const n=this.buckets;for(let i=0;i<ge.LUMINANCE_BUCKETS;i++)n[i]=0}static estimateBlackPoint(e){const n=e.length;let i=0,s=0,a=0;for(let y=0;y<n;y++)e[y]>a&&(s=y,a=e[y]),e[y]>i&&(i=e[y]);let l=0,d=0;for(let y=0;y<n;y++){const E=y-s,I=e[y]*E*E;I>d&&(l=y,d=I)}if(s>l){const y=s;s=l,l=y}if(l-s<=n/16)throw new $;let h=l-1,p=-1;for(let y=l-1;y>s;y--){const E=y-s,I=E*E*(l-y)*(i-e[y]);I>p&&(h=y,p=I)}return h<<ge.LUMINANCE_SHIFT}}ge.LUMINANCE_BITS=5,ge.LUMINANCE_SHIFT=8-ge.LUMINANCE_BITS,ge.LUMINANCE_BUCKETS=1<<ge.LUMINANCE_BITS,ge.EMPTY=Uint8ClampedArray.from([0]);class ne extends ge{constructor(e){super(e),this.matrix=null}getBlackMatrix(){if(this.matrix!==null)return this.matrix;const e=this.getLuminanceSource(),n=e.getWidth(),i=e.getHeight();if(n>=ne.MINIMUM_DIMENSION&&i>=ne.MINIMUM_DIMENSION){const s=e.getMatrix();let a=n>>ne.BLOCK_SIZE_POWER;(n&ne.BLOCK_SIZE_MASK)!==0&&a++;let l=i>>ne.BLOCK_SIZE_POWER;(i&ne.BLOCK_SIZE_MASK)!==0&&l++;const d=ne.calculateBlackPoints(s,a,l,n,i),h=new Me(n,i);ne.calculateThresholdForBlock(s,a,l,n,i,d,h),this.matrix=h}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new ne(e)}static calculateThresholdForBlock(e,n,i,s,a,l,d){const h=a-ne.BLOCK_SIZE,p=s-ne.BLOCK_SIZE;for(let y=0;y<i;y++){let E=y<<ne.BLOCK_SIZE_POWER;E>h&&(E=h);const I=ne.cap(y,2,i-3);for(let k=0;k<n;k++){let L=k<<ne.BLOCK_SIZE_POWER;L>p&&(L=p);const F=ne.cap(k,2,n-3);let H=0;for(let le=-2;le<=2;le++){const ce=l[I+le];H+=ce[F-2]+ce[F-1]+ce[F]+ce[F+1]+ce[F+2]}const Y=H/25;ne.thresholdBlock(e,L,E,Y,s,d)}}}static cap(e,n,i){return e<n?n:e>i?i:e}static thresholdBlock(e,n,i,s,a,l){for(let d=0,h=i*a+n;d<ne.BLOCK_SIZE;d++,h+=a)for(let p=0;p<ne.BLOCK_SIZE;p++)(e[h+p]&255)<=s&&l.set(n+p,i+d)}static calculateBlackPoints(e,n,i,s,a){const l=a-ne.BLOCK_SIZE,d=s-ne.BLOCK_SIZE,h=new Array(i);for(let p=0;p<i;p++){h[p]=new Int32Array(n);let y=p<<ne.BLOCK_SIZE_POWER;y>l&&(y=l);for(let E=0;E<n;E++){let I=E<<ne.BLOCK_SIZE_POWER;I>d&&(I=d);let k=0,L=255,F=0;for(let Y=0,le=y*s+I;Y<ne.BLOCK_SIZE;Y++,le+=s){for(let ce=0;ce<ne.BLOCK_SIZE;ce++){const ae=e[le+ce]&255;k+=ae,ae<L&&(L=ae),ae>F&&(F=ae)}if(F-L>ne.MIN_DYNAMIC_RANGE)for(Y++,le+=s;Y<ne.BLOCK_SIZE;Y++,le+=s)for(let ce=0;ce<ne.BLOCK_SIZE;ce++)k+=e[le+ce]&255}let H=k>>ne.BLOCK_SIZE_POWER*2;if(F-L<=ne.MIN_DYNAMIC_RANGE&&(H=L/2,p>0&&E>0)){const Y=(h[p-1][E]+2*h[p][E-1]+h[p-1][E-1])/4;L<Y&&(H=Y)}h[p][E]=H}}return h}}ne.BLOCK_SIZE_POWER=3,ne.BLOCK_SIZE=1<<ne.BLOCK_SIZE_POWER,ne.BLOCK_SIZE_MASK=ne.BLOCK_SIZE-1,ne.MINIMUM_DIMENSION=ne.BLOCK_SIZE*5,ne.MIN_DYNAMIC_RANGE=24;class Q{constructor(e,n){this.width=e,this.height=n}getWidth(){return this.width}getHeight(){return this.height}isCropSupported(){return!1}crop(e,n,i,s){throw new Te("This luminance source does not support cropping.")}isRotateSupported(){return!1}rotateCounterClockwise(){throw new Te("This luminance source does not support rotation by 90 degrees.")}rotateCounterClockwise45(){throw new Te("This luminance source does not support rotation by 45 degrees.")}toString(){const e=new Uint8ClampedArray(this.width);let n=new xe;for(let i=0;i<this.height;i++){const s=this.getRow(i,e);for(let a=0;a<this.width;a++){const l=s[a]&255;let d;l<64?d="#":l<128?d="+":l<192?d=".":d=" ",n.append(d)}n.append(`
60
- `)}return n.toString()}}class me extends Q{constructor(e){super(e.getWidth(),e.getHeight()),this.delegate=e}getRow(e,n){const i=this.delegate.getRow(e,n),s=this.getWidth();for(let a=0;a<s;a++)i[a]=255-(i[a]&255);return i}getMatrix(){const e=this.delegate.getMatrix(),n=this.getWidth()*this.getHeight(),i=new Uint8ClampedArray(n);for(let s=0;s<n;s++)i[s]=255-(e[s]&255);return i}isCropSupported(){return this.delegate.isCropSupported()}crop(e,n,i,s){return new me(this.delegate.crop(e,n,i,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new me(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new me(this.delegate.rotateCounterClockwise45())}}class fe extends Q{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=fe.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return fe.toGrayscaleBuffer(n.data,e.width,e.height)}static toGrayscaleBuffer(e,n,i){const s=new Uint8ClampedArray(n*i);for(let a=0,l=0,d=e.length;a<d;a+=4,l++){let h;if(e[a+3]===0)h=255;else{const y=e[a],E=e[a+1],I=e[a+2];h=306*y+601*E+117*I+512>>10}s[l]=h}return s}getRow(e,n){if(e<0||e>=this.getHeight())throw new v("Requested row is outside the image: "+e);const i=this.getWidth(),s=e*i;return n===null?n=this.buffer.slice(s,s+i):(n.length<i&&(n=new Uint8ClampedArray(i)),n.set(this.buffer.slice(s,s+i))),n}getMatrix(){return this.buffer}isCropSupported(){return!0}crop(e,n,i,s){return super.crop(e,n,i,s),this}isRotateSupported(){return!0}rotateCounterClockwise(){return this.rotate(-90),this}rotateCounterClockwise45(){return this.rotate(-45),this}getTempCanvasElement(){if(this.tempCanvasElement===null){const e=this.canvas.ownerDocument.createElement("canvas");e.width=this.canvas.width,e.height=this.canvas.height,this.tempCanvasElement=e}return this.tempCanvasElement}rotate(e){const n=this.getTempCanvasElement(),i=n.getContext("2d"),s=e*fe.DEGREE_TO_RADIANS,a=this.canvas.width,l=this.canvas.height,d=Math.ceil(Math.abs(Math.cos(s))*a+Math.abs(Math.sin(s))*l),h=Math.ceil(Math.abs(Math.sin(s))*a+Math.abs(Math.cos(s))*l);return n.width=d,n.height=h,i.translate(d/2,h/2),i.rotate(s),i.drawImage(this.canvas,a/-2,l/-2),this.buffer=fe.makeBufferFromCanvasImageData(n),this}invert(){return new me(this)}}fe.DEGREE_TO_RADIANS=Math.PI/180;class ie{constructor(e,n,i){this.deviceId=e,this.label=n,this.kind="videoinput",this.groupId=i||void 0}toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}}}var pe=(globalThis||bi||self||window||void 0)&&(globalThis||bi||self||window||void 0).__awaiter||function(b,e,n,i){function s(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function d(y){try{p(i.next(y))}catch(E){l(E)}}function h(y){try{p(i.throw(y))}catch(E){l(E)}}function p(y){y.done?a(y.value):s(y.value).then(d,h)}p((i=i.apply(b,e||[])).next())})};class vt{constructor(e,n=500,i){this.reader=e,this.timeBetweenScansMillis=n,this._hints=i,this._stopContinuousDecode=!1,this._stopAsyncDecode=!1,this._timeBetweenDecodingAttempts=0}get hasNavigator(){return typeof navigator<"u"}get isMediaDevicesSuported(){return this.hasNavigator&&!!navigator.mediaDevices}get canEnumerateDevices(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices)}get timeBetweenDecodingAttempts(){return this._timeBetweenDecodingAttempts}set timeBetweenDecodingAttempts(e){this._timeBetweenDecodingAttempts=e<0?0:e}set hints(e){this._hints=e||null}get hints(){return this._hints}listVideoInputDevices(){return pe(this,void 0,void 0,function*(){if(!this.hasNavigator)throw new Error("Can't enumerate devices, navigator is not present.");if(!this.canEnumerateDevices)throw new Error("Can't enumerate devices, method not supported.");const e=yield navigator.mediaDevices.enumerateDevices(),n=[];for(const i of e){const s=i.kind==="video"?"videoinput":i.kind;if(s!=="videoinput")continue;const a=i.deviceId||i.id,l=i.label||`Video device ${n.length+1}`,d=i.groupId,h={deviceId:a,label:l,kind:s,groupId:d};n.push(h)}return n})}getVideoInputDevices(){return pe(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new ie(n.deviceId,n.label))})}findDeviceById(e){return pe(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(i=>i.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return pe(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return pe(this,void 0,void 0,function*(){this.reset();let i;e?i={deviceId:{exact:e}}:i={facingMode:"environment"};const s={video:i};return yield this.decodeOnceFromConstraints(s,n)})}decodeOnceFromConstraints(e,n){return pe(this,void 0,void 0,function*(){const i=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(i,n)})}decodeOnceFromStream(e,n){return pe(this,void 0,void 0,function*(){this.reset();const i=yield this.attachStreamToVideo(e,n);return yield this.decodeOnce(i)})}decodeFromInputVideoDeviceContinuously(e,n,i){return pe(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,i)})}decodeFromVideoDevice(e,n,i){return pe(this,void 0,void 0,function*(){let s;e?s={deviceId:{exact:e}}:s={facingMode:"environment"};const a={video:s};return yield this.decodeFromConstraints(a,n,i)})}decodeFromConstraints(e,n,i){return pe(this,void 0,void 0,function*(){const s=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeFromStream(s,n,i)})}decodeFromStream(e,n,i){return pe(this,void 0,void 0,function*(){this.reset();const s=yield this.attachStreamToVideo(e,n);return yield this.decodeContinuously(s,i)})}stopAsyncDecode(){this._stopAsyncDecode=!0}stopContinuousDecode(){this._stopContinuousDecode=!0}attachStreamToVideo(e,n){return pe(this,void 0,void 0,function*(){const i=this.prepareVideoElement(n);return this.addVideoSource(i,e),this.videoElement=i,this.stream=e,yield this.playVideoOnLoadAsync(i),i})}playVideoOnLoadAsync(e){return new Promise((n,i)=>this.playVideoOnLoad(e,()=>n()))}playVideoOnLoad(e,n){this.videoEndedListener=()=>this.stopStreams(),this.videoCanPlayListener=()=>this.tryPlayVideo(e),e.addEventListener("ended",this.videoEndedListener),e.addEventListener("canplay",this.videoCanPlayListener),e.addEventListener("playing",n),this.tryPlayVideo(e)}isVideoPlaying(e){return e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2}tryPlayVideo(e){return pe(this,void 0,void 0,function*(){if(this.isVideoPlaying(e)){console.warn("Trying to play video that is already playing.");return}try{yield e.play()}catch{console.warn("It was not possible to play the video.")}})}getMediaElement(e,n){const i=document.getElementById(e);if(!i)throw new A(`element with id '${e}' not found`);if(i.nodeName.toLowerCase()!==n.toLowerCase())throw new A(`element with id '${e}' must be an ${n} element`);return i}decodeFromImage(e,n){if(!e&&!n)throw new A("either imageElement with a src set or an url must be provided");return n&&!e?this.decodeFromImageUrl(n):this.decodeFromImageElement(e)}decodeFromVideo(e,n){if(!e&&!n)throw new A("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrl(n):this.decodeFromVideoElement(e)}decodeFromVideoContinuously(e,n,i){if(e===void 0&&n===void 0)throw new A("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrlContinuously(n,i):this.decodeFromVideoElementContinuously(e,i)}decodeFromImageElement(e){if(!e)throw new A("An image element must be provided.");this.reset();const n=this.prepareImageElement(e);this.imageElement=n;let i;return this.isImageLoaded(n)?i=this.decodeOnce(n,!1,!0):i=this._decodeOnLoadImage(n),i}decodeFromVideoElement(e){const n=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideo(n)}decodeFromVideoElementContinuously(e,n){const i=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideoContinuously(i,n)}_decodeFromVideoElementSetup(e){if(!e)throw new A("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new A("An URL must be provided.");this.reset();const n=this.prepareImageElement();this.imageElement=n;const i=this._decodeOnLoadImage(n);return n.src=e,i}decodeFromVideoUrl(e){if(!e)throw new A("An URL must be provided.");this.reset();const n=this.prepareVideoElement(),i=this.decodeFromVideoElement(n);return n.src=e,i}decodeFromVideoUrlContinuously(e,n){if(!e)throw new A("An URL must be provided.");this.reset();const i=this.prepareVideoElement(),s=this.decodeFromVideoElementContinuously(i,n);return i.src=e,s}_decodeOnLoadImage(e){return new Promise((n,i)=>{this.imageLoadedListener=()=>this.decodeOnce(e,!1,!0).then(n,i),e.addEventListener("load",this.imageLoadedListener)})}_decodeOnLoadVideo(e){return pe(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return pe(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(e),this.decodeContinuously(e,n)})}isImageLoaded(e){return!(!e.complete||e.naturalWidth===0)}prepareImageElement(e){let n;return typeof e>"u"&&(n=document.createElement("img"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"img")),e instanceof HTMLImageElement&&(n=e),n}prepareVideoElement(e){let n;return!e&&typeof document<"u"&&(n=document.createElement("video"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"video")),e instanceof HTMLVideoElement&&(n=e),n.setAttribute("autoplay","true"),n.setAttribute("muted","true"),n.setAttribute("playsinline","true"),n}decodeOnce(e,n=!0,i=!0){this._stopAsyncDecode=!1;const s=(a,l)=>{if(this._stopAsyncDecode){l(new $("Video stream has ended before any code could be detected.")),this._stopAsyncDecode=void 0;return}try{const d=this.decode(e);a(d)}catch(d){const h=n&&d instanceof $,y=(d instanceof O||d instanceof U)&&i;if(h||y)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(d)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const i=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(i,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof O||s instanceof U,l=s instanceof $;(a||l)&&setTimeout(i,this._timeBetweenDecodingAttempts)}};i()}decode(e){const n=this.createBinaryBitmap(e);return this.decodeBitmap(n)}_isHTMLVideoElement(e){return e.videoWidth!==0}drawFrameOnCanvas(e,n,i){n||(n={sx:0,sy:0,sWidth:e.videoWidth,sHeight:e.videoHeight,dx:0,dy:0,dWidth:e.videoWidth,dHeight:e.videoHeight}),i||(i=this.captureCanvasContext),i.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}drawImageOnCanvas(e,n,i=this.captureCanvasContext){n||(n={sx:0,sy:0,sWidth:e.naturalWidth,sHeight:e.naturalHeight,dx:0,dy:0,dWidth:e.naturalWidth,dHeight:e.naturalHeight}),i||(i=this.captureCanvasContext),i.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}createBinaryBitmap(e){this.getCaptureCanvasContext(e),this._isHTMLVideoElement(e)?this.drawFrameOnCanvas(e):this.drawImageOnCanvas(e);const n=this.getCaptureCanvas(e),i=new fe(n),s=new ne(i);return new P(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const i=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=i}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const n=this.createCaptureCanvas(e);this.captureCanvas=n}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const n=document.createElement("canvas");let i,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(i=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(i=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=i+"px",n.style.height=s+"px",n.width=i,n.height=s,n}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,n){try{e.srcObject=n}catch{e.src=URL.createObjectURL(n)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class Ee{constructor(e,n,i=n==null?0:8*n.length,s,a,l=D.currentTimeMillis()){this.text=e,this.rawBytes=n,this.numBits=i,this.resultPoints=s,this.format=a,this.timestamp=l,this.text=e,this.rawBytes=n,i==null?this.numBits=n==null?0:8*n.length:this.numBits=i,this.resultPoints=s,this.format=a,this.resultMetadata=null,l==null?this.timestamp=D.currentTimeMillis():this.timestamp=l}getText(){return this.text}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}getResultPoints(){return this.resultPoints}getBarcodeFormat(){return this.format}getResultMetadata(){return this.resultMetadata}putMetadata(e,n){this.resultMetadata===null&&(this.resultMetadata=new Map),this.resultMetadata.set(e,n)}putAllMetadata(e){e!==null&&(this.resultMetadata===null?this.resultMetadata=e:this.resultMetadata=new Map(e))}addResultPoints(e){const n=this.resultPoints;if(n===null)this.resultPoints=e;else if(e!==null&&e.length>0){const i=new Array(n.length+e.length);D.arraycopy(n,0,i,0,n.length),D.arraycopy(e,0,i,n.length,e.length),this.resultPoints=i}}getTimestamp(){return this.timestamp}toString(){return this.text}}var Tt;(function(b){b[b.AZTEC=0]="AZTEC",b[b.CODABAR=1]="CODABAR",b[b.CODE_39=2]="CODE_39",b[b.CODE_93=3]="CODE_93",b[b.CODE_128=4]="CODE_128",b[b.DATA_MATRIX=5]="DATA_MATRIX",b[b.EAN_8=6]="EAN_8",b[b.EAN_13=7]="EAN_13",b[b.ITF=8]="ITF",b[b.MAXICODE=9]="MAXICODE",b[b.PDF_417=10]="PDF_417",b[b.QR_CODE=11]="QR_CODE",b[b.RSS_14=12]="RSS_14",b[b.RSS_EXPANDED=13]="RSS_EXPANDED",b[b.UPC_A=14]="UPC_A",b[b.UPC_E=15]="UPC_E",b[b.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(Tt||(Tt={}));var Ce=Tt,sn;(function(b){b[b.OTHER=0]="OTHER",b[b.ORIENTATION=1]="ORIENTATION",b[b.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",b[b.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",b[b.ISSUE_NUMBER=4]="ISSUE_NUMBER",b[b.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",b[b.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",b[b.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",b[b.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",b[b.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",b[b.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(sn||(sn={}));var Ue=sn;class Ht{constructor(e,n,i,s,a=-1,l=-1){this.rawBytes=e,this.text=n,this.byteSegments=i,this.ecLevel=s,this.structuredAppendSequenceNumber=a,this.structuredAppendParity=l,this.numBits=e==null?0:8*e.length}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}setNumBits(e){this.numBits=e}getText(){return this.text}getByteSegments(){return this.byteSegments}getECLevel(){return this.ecLevel}getErrorsCorrected(){return this.errorsCorrected}setErrorsCorrected(e){this.errorsCorrected=e}getErasures(){return this.erasures}setErasures(e){this.erasures=e}getOther(){return this.other}setOther(e){this.other=e}hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0}getStructuredAppendParity(){return this.structuredAppendParity}getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber}}class de{exp(e){return this.expTable[e]}log(e){if(e===0)throw new v;return this.logTable[e]}static addOrSubtract(e,n){return e^n}}class Oe{constructor(e,n){if(n.length===0)throw new v;this.field=e;const i=n.length;if(i>1&&n[0]===0){let s=1;for(;s<i&&n[s]===0;)s++;s===i?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(i-s),D.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);const n=this.coefficients;let i;if(e===1){i=0;for(let l=0,d=n.length;l!==d;l++){const h=n[l];i=de.addOrSubtract(i,h)}return i}i=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)i=de.addOrSubtract(a.multiply(e,i),n[l]);return i}addOrSubtract(e){if(!this.field.equals(e.field))throw new v("GenericGFPolys do not have same GenericGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,i=e.coefficients;if(n.length>i.length){const l=n;n=i,i=l}let s=new Int32Array(i.length);const a=i.length-n.length;D.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=de.addOrSubtract(n[l-a],i[l]);return new Oe(this.field,s)}multiply(e){if(!this.field.equals(e.field))throw new v("GenericGFPolys do not have same GenericGF field");if(this.isZero()||e.isZero())return this.field.getZero();const n=this.coefficients,i=n.length,s=e.coefficients,a=s.length,l=new Int32Array(i+a-1),d=this.field;for(let h=0;h<i;h++){const p=n[h];for(let y=0;y<a;y++)l[h+y]=de.addOrSubtract(l[h+y],d.multiply(p,s[y]))}return new Oe(d,l)}multiplyScalar(e){if(e===0)return this.field.getZero();if(e===1)return this;const n=this.coefficients.length,i=this.field,s=new Int32Array(n),a=this.coefficients;for(let l=0;l<n;l++)s[l]=i.multiply(a[l],e);return new Oe(i,s)}multiplyByMonomial(e,n){if(e<0)throw new v;if(n===0)return this.field.getZero();const i=this.coefficients,s=i.length,a=new Int32Array(s+e),l=this.field;for(let d=0;d<s;d++)a[d]=l.multiply(i[d],n);return new Oe(l,a)}divide(e){if(!this.field.equals(e.field))throw new v("GenericGFPolys do not have same GenericGF field");if(e.isZero())throw new v("Divide by 0");const n=this.field;let i=n.getZero(),s=this;const a=e.getCoefficient(e.getDegree()),l=n.inverse(a);for(;s.getDegree()>=e.getDegree()&&!s.isZero();){const d=s.getDegree()-e.getDegree(),h=n.multiply(s.getCoefficient(s.getDegree()),l),p=e.multiplyByMonomial(d,h),y=n.buildMonomial(d,h);i=i.addOrSubtract(y),s=s.addOrSubtract(p)}return[i,s]}toString(){let e="";for(let n=this.getDegree();n>=0;n--){let i=this.getCoefficient(n);if(i!==0){if(i<0?(e+=" - ",i=-i):e.length>0&&(e+=" + "),n===0||i!==1){const s=this.field.log(i);s===0?e+="1":s===1?e+="a":(e+="a^",e+=s)}n!==0&&(n===1?e+="x":(e+="x^",e+=n))}}return e}}class yt extends x{}yt.kind="ArithmeticException";class be extends de{constructor(e,n,i){super(),this.primitive=e,this.size=n,this.generatorBase=i;const s=new Int32Array(n);let a=1;for(let d=0;d<n;d++)s[d]=a,a*=2,a>=n&&(a^=e,a&=n-1);this.expTable=s;const l=new Int32Array(n);for(let d=0;d<n-1;d++)l[s[d]]=d;this.logTable=l,this.zero=new Oe(this,Int32Array.from([0])),this.one=new Oe(this,Int32Array.from([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new v;if(n===0)return this.zero;const i=new Int32Array(e+1);return i[0]=n,new Oe(this,i)}inverse(e){if(e===0)throw new yt;return this.expTable[this.size-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.size-1)]}getSize(){return this.size}getGeneratorBase(){return this.generatorBase}toString(){return"GF(0x"+z.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}be.AZTEC_DATA_12=new be(4201,4096,1),be.AZTEC_DATA_10=new be(1033,1024,1),be.AZTEC_DATA_6=new be(67,64,1),be.AZTEC_PARAM=new be(19,16,1),be.QR_CODE_FIELD_256=new be(285,256,0),be.DATA_MATRIX_FIELD_256=new be(301,256,1),be.AZTEC_DATA_8=be.DATA_MATRIX_FIELD_256,be.MAXICODE_FIELD_64=be.AZTEC_DATA_6;class Xt extends x{}Xt.kind="ReedSolomonException";class Wt extends x{}Wt.kind="IllegalStateException";class In{constructor(e){this.field=e}decode(e,n){const i=this.field,s=new Oe(i,e),a=new Int32Array(n);let l=!0;for(let k=0;k<n;k++){const L=s.evaluateAt(i.exp(k+i.getGeneratorBase()));a[a.length-1-k]=L,L!==0&&(l=!1)}if(l)return;const d=new Oe(i,a),h=this.runEuclideanAlgorithm(i.buildMonomial(n,1),d,n),p=h[0],y=h[1],E=this.findErrorLocations(p),I=this.findErrorMagnitudes(y,E);for(let k=0;k<E.length;k++){const L=e.length-1-i.log(E[k]);if(L<0)throw new Xt("Bad error location");e[L]=be.addOrSubtract(e[L],I[k])}}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){const k=e;e=n,n=k}const s=this.field;let a=e,l=n,d=s.getZero(),h=s.getOne();for(;l.getDegree()>=(i/2|0);){let k=a,L=d;if(a=l,d=h,a.isZero())throw new Xt("r_{i-1} was zero");l=k;let F=s.getZero();const H=a.getCoefficient(a.getDegree()),Y=s.inverse(H);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const le=l.getDegree()-a.getDegree(),ce=s.multiply(l.getCoefficient(l.getDegree()),Y);F=F.addOrSubtract(s.buildMonomial(le,ce)),l=l.addOrSubtract(a.multiplyByMonomial(le,ce))}if(h=F.multiply(d).addOrSubtract(L),l.getDegree()>=a.getDegree())throw new Wt("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new Xt("sigmaTilde(0) was zero");const y=s.inverse(p),E=h.multiplyScalar(y),I=l.multiplyScalar(y);return[E,I]}findErrorLocations(e){const n=e.getDegree();if(n===1)return Int32Array.from([e.getCoefficient(1)]);const i=new Int32Array(n);let s=0;const a=this.field;for(let l=1;l<a.getSize()&&s<n;l++)e.evaluateAt(l)===0&&(i[s]=a.inverse(l),s++);if(s!==n)throw new Xt("Error locator degree does not match number of roots");return i}findErrorMagnitudes(e,n){const i=n.length,s=new Int32Array(i),a=this.field;for(let l=0;l<i;l++){const d=a.inverse(n[l]);let h=1;for(let p=0;p<i;p++)if(l!==p){const y=a.multiply(n[p],d),E=(y&1)===0?y|1:y&-2;h=a.multiply(h,E)}s[l]=a.multiply(e.evaluateAt(d),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],d))}return s}}var Ct;(function(b){b[b.UPPER=0]="UPPER",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.DIGIT=3]="DIGIT",b[b.PUNCT=4]="PUNCT",b[b.BINARY=5]="BINARY"})(Ct||(Ct={}));class Xe{decode(e){this.ddata=e;let n=e.getBits(),i=this.extractBits(n),s=this.correctBits(i),a=Xe.convertBoolArrayToByteArray(s),l=Xe.getEncodedData(s),d=new Ht(a,l,null,null);return d.setNumBits(s.length),d}static highLevelDecode(e){return this.getEncodedData(e)}static getEncodedData(e){let n=e.length,i=Ct.UPPER,s=Ct.UPPER,a="",l=0;for(;l<n;)if(s===Ct.BINARY){if(n-l<5)break;let d=Xe.readCode(e,l,5);if(l+=5,d===0){if(n-l<11)break;d=Xe.readCode(e,l,11)+31,l+=11}for(let h=0;h<d;h++){if(n-l<8){l=n;break}const p=Xe.readCode(e,l,8);a+=re.castAsNonUtf8Char(p),l+=8}s=i}else{let d=s===Ct.DIGIT?4:5;if(n-l<d)break;let h=Xe.readCode(e,l,d);l+=d;let p=Xe.getCharacter(s,h);p.startsWith("CTRL_")?(i=s,s=Xe.getTable(p.charAt(5)),p.charAt(6)==="L"&&(i=s)):(a+=p,s=i)}return a}static getTable(e){switch(e){case"L":return Ct.LOWER;case"P":return Ct.PUNCT;case"M":return Ct.MIXED;case"D":return Ct.DIGIT;case"B":return Ct.BINARY;case"U":default:return Ct.UPPER}}static getCharacter(e,n){switch(e){case Ct.UPPER:return Xe.UPPER_TABLE[n];case Ct.LOWER:return Xe.LOWER_TABLE[n];case Ct.MIXED:return Xe.MIXED_TABLE[n];case Ct.PUNCT:return Xe.PUNCT_TABLE[n];case Ct.DIGIT:return Xe.DIGIT_TABLE[n];default:throw new Wt("Bad table")}}correctBits(e){let n,i;this.ddata.getNbLayers()<=2?(i=6,n=be.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(i=8,n=be.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(i=10,n=be.AZTEC_DATA_10):(i=12,n=be.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/i;if(a<s)throw new U;let l=e.length%i,d=new Int32Array(a);for(let I=0;I<a;I++,l+=i)d[I]=Xe.readCode(e,l,i);try{new In(n).decode(d,a-s)}catch(I){throw new U(I)}let h=(1<<i)-1,p=0;for(let I=0;I<s;I++){let k=d[I];if(k===0||k===h)throw new U;(k===1||k===h-1)&&p++}let y=new Array(s*i-p),E=0;for(let I=0;I<s;I++){let k=d[I];if(k===1||k===h-1)y.fill(k>1,E,E+i-1),E+=i-1;else for(let L=i-1;L>=0;--L)y[E++]=(k&1<<L)!==0}return y}extractBits(e){let n=this.ddata.isCompact(),i=this.ddata.getNbLayers(),s=(n?11:14)+i*4,a=new Int32Array(s),l=new Array(this.totalBitsInLayer(i,n));if(n)for(let d=0;d<a.length;d++)a[d]=d;else{let d=s+1+2*z.truncDivision(z.truncDivision(s,2)-1,15),h=s/2,p=z.truncDivision(d,2);for(let y=0;y<h;y++){let E=y+z.truncDivision(y,15);a[h-y-1]=p-E-1,a[h+y]=p+E+1}}for(let d=0,h=0;d<i;d++){let p=(i-d)*4+(n?9:12),y=d*2,E=s-1-y;for(let I=0;I<p;I++){let k=I*2;for(let L=0;L<2;L++)l[h+k+L]=e.get(a[y+L],a[y+I]),l[h+2*p+k+L]=e.get(a[y+I],a[E-L]),l[h+4*p+k+L]=e.get(a[E-L],a[E-I]),l[h+6*p+k+L]=e.get(a[E-I],a[y+L])}h+=p*8}return l}static readCode(e,n,i){let s=0;for(let a=n;a<n+i;a++)s<<=1,e[a]&&(s|=1);return s}static readByte(e,n){let i=e.length-n;return i>=8?Xe.readCode(e,n,8):Xe.readCode(e,n,i)<<8-i}static convertBoolArrayToByteArray(e){let n=new Uint8Array((e.length+7)/8);for(let i=0;i<n.length;i++)n[i]=Xe.readByte(e,8*i);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Xe.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],Xe.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],Xe.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
61
- `,"\\13","\f","\r","\\33","\\34","\\35","\\36","\\37","@","\\","^","_","`","|","~","\\177","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],Xe.PUNCT_TABLE=["","\r",`\r
62
- `,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],Xe.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class Ze{constructor(){}static round(e){return e===NaN?0:e<=Number.MIN_SAFE_INTEGER?Number.MIN_SAFE_INTEGER:e>=Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+(e<0?-.5:.5)|0}static distance(e,n,i,s){const a=e-i,l=n-s;return Math.sqrt(a*a+l*l)}static sum(e){let n=0;for(let i=0,s=e.length;i!==s;i++){const a=e[i];n+=a}return n}}class Sn{static floatToIntBits(e){return e}}Sn.MAX_VALUE=Number.MAX_SAFE_INTEGER;class ve{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof ve){const n=e;return this.x===n.x&&this.y===n.y}return!1}hashCode(){return 31*Sn.floatToIntBits(this.x)+Sn.floatToIntBits(this.y)}toString(){return"("+this.x+","+this.y+")"}static orderBestPatterns(e){const n=this.distance(e[0],e[1]),i=this.distance(e[1],e[2]),s=this.distance(e[0],e[2]);let a,l,d;if(i>=n&&i>=s?(l=e[0],a=e[1],d=e[2]):s>=i&&s>=n?(l=e[1],a=e[0],d=e[2]):(l=e[2],a=e[0],d=e[1]),this.crossProductZ(a,l,d)<0){const h=a;a=d,d=h}e[0]=a,e[1]=l,e[2]=d}static distance(e,n){return Ze.distance(e.x,e.y,n.x,n.y)}static crossProductZ(e,n,i){const s=n.x,a=n.y;return(i.x-s)*(e.y-a)-(i.y-a)*(e.x-s)}}class Bn{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class Hn extends Bn{constructor(e,n,i,s,a){super(e,n),this.compact=i,this.nbDatablocks=s,this.nbLayers=a}getNbLayers(){return this.nbLayers}getNbDatablocks(){return this.nbDatablocks}isCompact(){return this.compact}}class Jt{constructor(e,n,i,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=Jt.INIT_SIZE),i==null&&(i=e.getWidth()/2|0),s==null&&(s=e.getHeight()/2|0);const a=n/2|0;if(this.leftInit=i-a,this.rightInit=i+a,this.upInit=s-a,this.downInit=s+a,this.upInit<0||this.leftInit<0||this.downInit>=this.height||this.rightInit>=this.width)throw new $}detect(){let e=this.leftInit,n=this.rightInit,i=this.upInit,s=this.downInit,a=!1,l=!0,d=!1,h=!1,p=!1,y=!1,E=!1;const I=this.width,k=this.height;for(;l;){l=!1;let L=!0;for(;(L||!h)&&n<I;)L=this.containsBlackPoint(i,s,n,!1),L?(n++,l=!0,h=!0):h||n++;if(n>=I){a=!0;break}let F=!0;for(;(F||!p)&&s<k;)F=this.containsBlackPoint(e,n,s,!0),F?(s++,l=!0,p=!0):p||s++;if(s>=k){a=!0;break}let H=!0;for(;(H||!y)&&e>=0;)H=this.containsBlackPoint(i,s,e,!1),H?(e--,l=!0,y=!0):y||e--;if(e<0){a=!0;break}let Y=!0;for(;(Y||!E)&&i>=0;)Y=this.containsBlackPoint(e,n,i,!0),Y?(i--,l=!0,E=!0):E||i--;if(i<0){a=!0;break}l&&(d=!0)}if(!a&&d){const L=n-e;let F=null;for(let ce=1;F===null&&ce<L;ce++)F=this.getBlackPointOnSegment(e,s-ce,e+ce,s);if(F==null)throw new $;let H=null;for(let ce=1;H===null&&ce<L;ce++)H=this.getBlackPointOnSegment(e,i+ce,e+ce,i);if(H==null)throw new $;let Y=null;for(let ce=1;Y===null&&ce<L;ce++)Y=this.getBlackPointOnSegment(n,i+ce,n-ce,i);if(Y==null)throw new $;let le=null;for(let ce=1;le===null&&ce<L;ce++)le=this.getBlackPointOnSegment(n,s-ce,n-ce,s);if(le==null)throw new $;return this.centerEdges(le,F,Y,H)}else throw new $}getBlackPointOnSegment(e,n,i,s){const a=Ze.round(Ze.distance(e,n,i,s)),l=(i-e)/a,d=(s-n)/a,h=this.image;for(let p=0;p<a;p++){const y=Ze.round(e+p*l),E=Ze.round(n+p*d);if(h.get(y,E))return new ve(y,E)}return null}centerEdges(e,n,i,s){const a=e.getX(),l=e.getY(),d=n.getX(),h=n.getY(),p=i.getX(),y=i.getY(),E=s.getX(),I=s.getY(),k=Jt.CORR;return a<this.width/2?[new ve(E-k,I+k),new ve(d+k,h+k),new ve(p-k,y-k),new ve(a+k,l-k)]:[new ve(E+k,I+k),new ve(d+k,h-k),new ve(p-k,y+k),new ve(a-k,l-k)]}containsBlackPoint(e,n,i,s){const a=this.image;if(s){for(let l=e;l<=n;l++)if(a.get(l,i))return!0}else for(let l=e;l<=n;l++)if(a.get(i,l))return!0;return!1}}Jt.INIT_SIZE=10,Jt.CORR=1;class Wn{static checkAndNudgePoints(e,n){const i=e.getWidth(),s=e.getHeight();let a=!0;for(let l=0;l<n.length&&a;l+=2){const d=Math.floor(n[l]),h=Math.floor(n[l+1]);if(d<-1||d>i||h<-1||h>s)throw new $;a=!1,d===-1?(n[l]=0,a=!0):d===i&&(n[l]=i-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}a=!0;for(let l=n.length-2;l>=0&&a;l-=2){const d=Math.floor(n[l]),h=Math.floor(n[l+1]);if(d<-1||d>i||h<-1||h>s)throw new $;a=!1,d===-1?(n[l]=0,a=!0):d===i&&(n[l]=i-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}}}class Bt{constructor(e,n,i,s,a,l,d,h,p){this.a11=e,this.a21=n,this.a31=i,this.a12=s,this.a22=a,this.a32=l,this.a13=d,this.a23=h,this.a33=p}static quadrilateralToQuadrilateral(e,n,i,s,a,l,d,h,p,y,E,I,k,L,F,H){const Y=Bt.quadrilateralToSquare(e,n,i,s,a,l,d,h);return Bt.squareToQuadrilateral(p,y,E,I,k,L,F,H).times(Y)}transformPoints(e){const n=e.length,i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,p=this.a31,y=this.a32,E=this.a33;for(let I=0;I<n;I+=2){const k=e[I],L=e[I+1],F=a*k+h*L+E;e[I]=(i*k+l*L+p)/F,e[I+1]=(s*k+d*L+y)/F}}transformPointsWithValues(e,n){const i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,p=this.a31,y=this.a32,E=this.a33,I=e.length;for(let k=0;k<I;k++){const L=e[k],F=n[k],H=a*L+h*F+E;e[k]=(i*L+l*F+p)/H,n[k]=(s*L+d*F+y)/H}}static squareToQuadrilateral(e,n,i,s,a,l,d,h){const p=e-i+a-d,y=n-s+l-h;if(p===0&&y===0)return new Bt(i-e,a-i,e,s-n,l-s,n,0,0,1);{const E=i-a,I=d-a,k=s-l,L=h-l,F=E*L-I*k,H=(p*L-I*y)/F,Y=(E*y-p*k)/F;return new Bt(i-e+H*i,d-e+Y*d,e,s-n+H*s,h-n+Y*h,n,H,Y,1)}}static quadrilateralToSquare(e,n,i,s,a,l,d,h){return Bt.squareToQuadrilateral(e,n,i,s,a,l,d,h).buildAdjoint()}buildAdjoint(){return new Bt(this.a22*this.a33-this.a23*this.a32,this.a23*this.a31-this.a21*this.a33,this.a21*this.a32-this.a22*this.a31,this.a13*this.a32-this.a12*this.a33,this.a11*this.a33-this.a13*this.a31,this.a12*this.a31-this.a11*this.a32,this.a12*this.a23-this.a13*this.a22,this.a13*this.a21-this.a11*this.a23,this.a11*this.a22-this.a12*this.a21)}times(e){return new Bt(this.a11*e.a11+this.a21*e.a12+this.a31*e.a13,this.a11*e.a21+this.a21*e.a22+this.a31*e.a23,this.a11*e.a31+this.a21*e.a32+this.a31*e.a33,this.a12*e.a11+this.a22*e.a12+this.a32*e.a13,this.a12*e.a21+this.a22*e.a22+this.a32*e.a23,this.a12*e.a31+this.a22*e.a32+this.a32*e.a33,this.a13*e.a11+this.a23*e.a12+this.a33*e.a13,this.a13*e.a21+this.a23*e.a22+this.a33*e.a23,this.a13*e.a31+this.a23*e.a32+this.a33*e.a33)}}class rr extends Wn{sampleGrid(e,n,i,s,a,l,d,h,p,y,E,I,k,L,F,H,Y,le,ce){const ae=Bt.quadrilateralToQuadrilateral(s,a,l,d,h,p,y,E,I,k,L,F,H,Y,le,ce);return this.sampleGridWithTransform(e,n,i,ae)}sampleGridWithTransform(e,n,i,s){if(n<=0||i<=0)throw new $;const a=new Me(n,i),l=new Float32Array(2*n);for(let d=0;d<i;d++){const h=l.length,p=d+.5;for(let y=0;y<h;y+=2)l[y]=y/2+.5,l[y+1]=p;s.transformPoints(l),Wn.checkAndNudgePoints(e,l);try{for(let y=0;y<h;y+=2)e.get(Math.floor(l[y]),Math.floor(l[y+1]))&&a.set(y/2,d)}catch{throw new $}}return a}}class R{static setGridSampler(e){R.gridSampler=e}static getInstance(){return R.gridSampler}}R.gridSampler=new rr;class oe{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new ve(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class qe{constructor(e){this.EXPECTED_CORNER_BITS=new Int32Array([3808,476,2107,1799]),this.image=e}detect(){return this.detectMirror(!1)}detectMirror(e){let n=this.getMatrixCenter(),i=this.getBullsEyeCorners(n);if(e){let l=i[0];i[0]=i[2],i[2]=l}this.extractParameters(i);let s=this.sampleGrid(this.image,i[this.shift%4],i[(this.shift+1)%4],i[(this.shift+2)%4],i[(this.shift+3)%4]),a=this.getMatrixCornerPoints(i);return new Hn(s,a,this.compact,this.nbDataBlocks,this.nbLayers)}extractParameters(e){if(!this.isValidPoint(e[0])||!this.isValidPoint(e[1])||!this.isValidPoint(e[2])||!this.isValidPoint(e[3]))throw new $;let n=2*this.nbCenterLayers,i=new Int32Array([this.sampleLine(e[0],e[1],n),this.sampleLine(e[1],e[2],n),this.sampleLine(e[2],e[3],n),this.sampleLine(e[3],e[0],n)]);this.shift=this.getRotation(i,n);let s=0;for(let l=0;l<4;l++){let d=i[(this.shift+l)%4];this.compact?(s<<=7,s+=d>>1&127):(s<<=10,s+=(d>>2&992)+(d>>1&31))}let a=this.getCorrectedParameterData(s,this.compact);this.compact?(this.nbLayers=(a>>6)+1,this.nbDataBlocks=(a&63)+1):(this.nbLayers=(a>>11)+1,this.nbDataBlocks=(a&2047)+1)}getRotation(e,n){let i=0;e.forEach((s,a,l)=>{let d=(s>>n-2<<1)+(s&1);i=(i<<3)+d}),i=((i&1)<<11)+(i>>1);for(let s=0;s<4;s++)if(z.bitCount(i^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new $}getCorrectedParameterData(e,n){let i,s;n?(i=7,s=2):(i=10,s=4);let a=i-s,l=new Int32Array(i);for(let h=i-1;h>=0;--h)l[h]=e&15,e>>=4;try{new In(be.AZTEC_PARAM).decode(l,a)}catch{throw new $}let d=0;for(let h=0;h<s;h++)d=(d<<4)+l[h];return d}getBullsEyeCorners(e){let n=e,i=e,s=e,a=e,l=!0;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){let E=this.getFirstDifferent(n,l,1,-1),I=this.getFirstDifferent(i,l,1,1),k=this.getFirstDifferent(s,l,-1,1),L=this.getFirstDifferent(a,l,-1,-1);if(this.nbCenterLayers>2){let F=this.distancePoint(L,E)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(F<.75||F>1.25||!this.isWhiteOrBlackRectangle(E,I,k,L))break}n=E,i=I,s=k,a=L,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new $;this.compact=this.nbCenterLayers===5;let d=new ve(n.getX()+.5,n.getY()-.5),h=new ve(i.getX()+.5,i.getY()+.5),p=new ve(s.getX()-.5,s.getY()+.5),y=new ve(a.getX()-.5,a.getY()-.5);return this.expandSquare([d,h,p,y],2*this.nbCenterLayers-3,2*this.nbCenterLayers)}getMatrixCenter(){let e,n,i,s;try{let d=new Jt(this.image).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{let h=this.image.getWidth()/2,p=this.image.getHeight()/2;e=this.getFirstDifferent(new oe(h+7,p-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new oe(h+7,p+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new oe(h-7,p+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new oe(h-7,p-7),!1,-1,-1).toResultPoint()}let a=Ze.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=Ze.round((e.getY()+s.getY()+n.getY()+i.getY())/4);try{let d=new Jt(this.image,15,a,l).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{e=this.getFirstDifferent(new oe(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new oe(a+7,l+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new oe(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new oe(a-7,l-7),!1,-1,-1).toResultPoint()}return a=Ze.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=Ze.round((e.getY()+s.getY()+n.getY()+i.getY())/4),new oe(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,i,s,a){let l=R.getInstance(),d=this.getDimension(),h=d/2-this.nbCenterLayers,p=d/2+this.nbCenterLayers;return l.sampleGrid(e,d,d,h,h,p,h,p,p,h,p,n.getX(),n.getY(),i.getX(),i.getY(),s.getX(),s.getY(),a.getX(),a.getY())}sampleLine(e,n,i){let s=0,a=this.distanceResultPoint(e,n),l=a/i,d=e.getX(),h=e.getY(),p=l*(n.getX()-e.getX())/a,y=l*(n.getY()-e.getY())/a;for(let E=0;E<i;E++)this.image.get(Ze.round(d+E*p),Ze.round(h+E*y))&&(s|=1<<i-E-1);return s}isWhiteOrBlackRectangle(e,n,i,s){let a=3;e=new oe(e.getX()-a,e.getY()+a),n=new oe(n.getX()-a,n.getY()-a),i=new oe(i.getX()+a,i.getY()-a),s=new oe(s.getX()+a,s.getY()+a);let l=this.getColor(s,e);if(l===0)return!1;let d=this.getColor(e,n);return d!==l||(d=this.getColor(n,i),d!==l)?!1:(d=this.getColor(i,s),d===l)}getColor(e,n){let i=this.distancePoint(e,n),s=(n.getX()-e.getX())/i,a=(n.getY()-e.getY())/i,l=0,d=e.getX(),h=e.getY(),p=this.image.get(e.getX(),e.getY()),y=Math.ceil(i);for(let I=0;I<y;I++)d+=s,h+=a,this.image.get(Ze.round(d),Ze.round(h))!==p&&l++;let E=l/i;return E>.1&&E<.9?0:E<=.1===p?1:-1}getFirstDifferent(e,n,i,s){let a=e.getX()+i,l=e.getY()+s;for(;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i,l+=s;for(a-=i,l-=s;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i;for(a-=i;this.isValid(a,l)&&this.image.get(a,l)===n;)l+=s;return l-=s,new oe(a,l)}expandSquare(e,n,i){let s=i/(2*n),a=e[0].getX()-e[2].getX(),l=e[0].getY()-e[2].getY(),d=(e[0].getX()+e[2].getX())/2,h=(e[0].getY()+e[2].getY())/2,p=new ve(d+s*a,h+s*l),y=new ve(d-s*a,h-s*l);a=e[1].getX()-e[3].getX(),l=e[1].getY()-e[3].getY(),d=(e[1].getX()+e[3].getX())/2,h=(e[1].getY()+e[3].getY())/2;let E=new ve(d+s*a,h+s*l),I=new ve(d-s*a,h-s*l);return[p,E,y,I]}isValid(e,n){return e>=0&&e<this.image.getWidth()&&n>0&&n<this.image.getHeight()}isValidPoint(e){let n=Ze.round(e.getX()),i=Ze.round(e.getY());return this.isValid(n,i)}distancePoint(e,n){return Ze.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return Ze.distance(e.getX(),e.getY(),n.getX(),n.getY())}getDimension(){return this.compact?4*this.nbLayers+11:this.nbLayers<=4?4*this.nbLayers+15:4*this.nbLayers+2*(z.truncDivision(this.nbLayers-4,8)+1)+15}}class lt{decode(e,n=null){let i=null,s=new qe(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Xe().decode(y)}catch(y){i=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Xe().decode(y)}catch(y){throw i??y}let d=new Ee(l.getText(),l.getRawBytes(),l.getNumBits(),a,Ce.AZTEC,D.currentTimeMillis()),h=l.getByteSegments();h!=null&&d.putMetadata(Ue.BYTE_SEGMENTS,h);let p=l.getECLevel();return p!=null&&d.putMetadata(Ue.ERROR_CORRECTION_LEVEL,p),d}reportFoundResultPoints(e,n){if(e!=null){let i=e.get(V.NEED_RESULT_POINT_CALLBACK);i!=null&&n.forEach((s,a,l)=>{i.foundPossibleResultPoint(s)})}}reset(){}}class xr extends vt{constructor(e=500){super(new lt,e)}}class bt{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(V.TRY_HARDER)===!0&&e.isRotateSupported()){const a=e.rotateCounterClockwise(),l=this.doDecode(a,n),d=l.getResultMetadata();let h=270;d!==null&&d.get(Ue.ORIENTATION)===!0&&(h=h+d.get(Ue.ORIENTATION)%360),l.putMetadata(Ue.ORIENTATION,h);const p=l.getResultPoints();if(p!==null){const y=a.getHeight();for(let E=0;E<p.length;E++)p[E]=new ve(y-p[E].getY()-1,p[E].getX())}return l}else throw new $}}reset(){}doDecode(e,n){const i=e.getWidth(),s=e.getHeight();let a=new ee(i);const l=n&&n.get(V.TRY_HARDER)===!0,d=Math.max(1,s>>(l?8:5));let h;l?h=s:h=15;const p=Math.trunc(s/2);for(let y=0;y<h;y++){const E=Math.trunc((y+1)/2),I=(y&1)===0,k=p+d*(I?E:-E);if(k<0||k>=s)break;try{a=e.getBlackRow(k,a)}catch{continue}for(let L=0;L<2;L++){if(L===1&&(a.reverse(),n&&n.get(V.NEED_RESULT_POINT_CALLBACK)===!0)){const F=new Map;n.forEach((H,Y)=>F.set(Y,H)),F.delete(V.NEED_RESULT_POINT_CALLBACK),n=F}try{const F=this.decodeRow(k,a,n);if(L===1){F.putMetadata(Ue.ORIENTATION,180);const H=F.getResultPoints();H!==null&&(H[0]=new ve(i-H[0].getX()-1,H[0].getY()),H[1]=new ve(i-H[1].getX()-1,H[1].getY()))}return F}catch{}}}throw new $}static recordPattern(e,n,i){const s=i.length;for(let p=0;p<s;p++)i[p]=0;const a=e.getSize();if(n>=a)throw new $;let l=!e.get(n),d=0,h=n;for(;h<a;){if(e.get(h)!==l)i[d]++;else{if(++d===s)break;i[d]=1,l=!l}h++}if(!(d===s||d===s-1&&h===a))throw new $}static recordPatternInReverse(e,n,i){let s=i.length,a=e.get(n);for(;n>0&&s>=0;)e.get(--n)!==a&&(s--,a=!a);if(s>=0)throw new $;bt.recordPattern(e,n+1,i)}static patternMatchVariance(e,n,i){const s=e.length;let a=0,l=0;for(let p=0;p<s;p++)a+=e[p],l+=n[p];if(a<l)return Number.POSITIVE_INFINITY;const d=a/l;i*=d;let h=0;for(let p=0;p<s;p++){const y=e[p],E=n[p]*d,I=y>E?y-E:E-y;if(I>i)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class he extends bt{static findStartPattern(e){const n=e.getSize(),i=e.getNextSet(0);let s=0,a=Int32Array.from([0,0,0,0,0,0]),l=i,d=!1;const h=6;for(let p=i;p<n;p++)if(e.get(p)!==d)a[s]++;else{if(s===h-1){let y=he.MAX_AVG_VARIANCE,E=-1;for(let I=he.CODE_START_A;I<=he.CODE_START_C;I++){const k=bt.patternMatchVariance(a,he.CODE_PATTERNS[I],he.MAX_INDIVIDUAL_VARIANCE);k<y&&(y=k,E=I)}if(E>=0&&e.isRange(Math.max(0,l-(p-l)/2),l,!1))return Int32Array.from([l,p,E]);l+=a[0]+a[1],a=a.slice(2,a.length-1),a[s-1]=0,a[s]=0,s--}else s++;a[s]=1,d=!d}throw new $}static decodeCode(e,n,i){bt.recordPattern(e,i,n);let s=he.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<he.CODE_PATTERNS.length;l++){const d=he.CODE_PATTERNS[l],h=this.patternMatchVariance(n,d,he.MAX_INDIVIDUAL_VARIANCE);h<s&&(s=h,a=l)}if(a>=0)return a;throw new $}decodeRow(e,n,i){const s=i&&i.get(V.ASSUME_GS1)===!0,a=he.findStartPattern(n),l=a[2];let d=0;const h=new Uint8Array(20);h[d++]=l;let p;switch(l){case he.CODE_START_A:p=he.CODE_CODE_A;break;case he.CODE_START_B:p=he.CODE_CODE_B;break;case he.CODE_START_C:p=he.CODE_CODE_C;break;default:throw new U}let y=!1,E=!1,I="",k=a[0],L=a[1];const F=Int32Array.from([0,0,0,0,0,0]);let H=0,Y=0,le=l,ce=0,ae=!0,We=!1,Fe=!1;for(;!y;){const Ir=E;switch(E=!1,H=Y,Y=he.decodeCode(n,F,L),h[d++]=Y,Y!==he.CODE_STOP&&(ae=!0),Y!==he.CODE_STOP&&(ce++,le+=ce*Y),k=L,L+=F.reduce((cd,ud)=>cd+ud,0),Y){case he.CODE_START_A:case he.CODE_START_B:case he.CODE_START_C:throw new U}switch(p){case he.CODE_CODE_A:if(Y<64)Fe===We?I+=String.fromCharCode(32+Y):I+=String.fromCharCode(32+Y+128),Fe=!1;else if(Y<96)Fe===We?I+=String.fromCharCode(Y-64):I+=String.fromCharCode(Y+64),Fe=!1;else switch(Y!==he.CODE_STOP&&(ae=!1),Y){case he.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case he.CODE_FNC_2:case he.CODE_FNC_3:break;case he.CODE_FNC_4_A:!We&&Fe?(We=!0,Fe=!1):We&&Fe?(We=!1,Fe=!1):Fe=!0;break;case he.CODE_SHIFT:E=!0,p=he.CODE_CODE_B;break;case he.CODE_CODE_B:p=he.CODE_CODE_B;break;case he.CODE_CODE_C:p=he.CODE_CODE_C;break;case he.CODE_STOP:y=!0;break}break;case he.CODE_CODE_B:if(Y<96)Fe===We?I+=String.fromCharCode(32+Y):I+=String.fromCharCode(32+Y+128),Fe=!1;else switch(Y!==he.CODE_STOP&&(ae=!1),Y){case he.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case he.CODE_FNC_2:case he.CODE_FNC_3:break;case he.CODE_FNC_4_B:!We&&Fe?(We=!0,Fe=!1):We&&Fe?(We=!1,Fe=!1):Fe=!0;break;case he.CODE_SHIFT:E=!0,p=he.CODE_CODE_A;break;case he.CODE_CODE_A:p=he.CODE_CODE_A;break;case he.CODE_CODE_C:p=he.CODE_CODE_C;break;case he.CODE_STOP:y=!0;break}break;case he.CODE_CODE_C:if(Y<100)Y<10&&(I+="0"),I+=Y;else switch(Y!==he.CODE_STOP&&(ae=!1),Y){case he.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case he.CODE_CODE_A:p=he.CODE_CODE_A;break;case he.CODE_CODE_B:p=he.CODE_CODE_B;break;case he.CODE_STOP:y=!0;break}break}Ir&&(p=p===he.CODE_CODE_A?he.CODE_CODE_B:he.CODE_CODE_A)}const nn=L-k;if(L=n.getNextUnset(L),!n.isRange(L,Math.min(n.getSize(),L+(L-k)/2),!1))throw new $;if(le-=ce*H,le%103!==H)throw new O;const yn=I.length;if(yn===0)throw new $;yn>0&&ae&&(p===he.CODE_CODE_C?I=I.substring(0,yn-2):I=I.substring(0,yn-1));const rn=(a[1]+a[0])/2,st=k+nn/2,$t=h.length,an=new Uint8Array($t);for(let Ir=0;Ir<$t;Ir++)an[Ir]=h[Ir];const Ar=[new ve(rn,e),new ve(st,e)];return new Ee(I,an,0,Ar,Ce.CODE_128,new Date().getTime())}}he.CODE_PATTERNS=[Int32Array.from([2,1,2,2,2,2]),Int32Array.from([2,2,2,1,2,2]),Int32Array.from([2,2,2,2,2,1]),Int32Array.from([1,2,1,2,2,3]),Int32Array.from([1,2,1,3,2,2]),Int32Array.from([1,3,1,2,2,2]),Int32Array.from([1,2,2,2,1,3]),Int32Array.from([1,2,2,3,1,2]),Int32Array.from([1,3,2,2,1,2]),Int32Array.from([2,2,1,2,1,3]),Int32Array.from([2,2,1,3,1,2]),Int32Array.from([2,3,1,2,1,2]),Int32Array.from([1,1,2,2,3,2]),Int32Array.from([1,2,2,1,3,2]),Int32Array.from([1,2,2,2,3,1]),Int32Array.from([1,1,3,2,2,2]),Int32Array.from([1,2,3,1,2,2]),Int32Array.from([1,2,3,2,2,1]),Int32Array.from([2,2,3,2,1,1]),Int32Array.from([2,2,1,1,3,2]),Int32Array.from([2,2,1,2,3,1]),Int32Array.from([2,1,3,2,1,2]),Int32Array.from([2,2,3,1,1,2]),Int32Array.from([3,1,2,1,3,1]),Int32Array.from([3,1,1,2,2,2]),Int32Array.from([3,2,1,1,2,2]),Int32Array.from([3,2,1,2,2,1]),Int32Array.from([3,1,2,2,1,2]),Int32Array.from([3,2,2,1,1,2]),Int32Array.from([3,2,2,2,1,1]),Int32Array.from([2,1,2,1,2,3]),Int32Array.from([2,1,2,3,2,1]),Int32Array.from([2,3,2,1,2,1]),Int32Array.from([1,1,1,3,2,3]),Int32Array.from([1,3,1,1,2,3]),Int32Array.from([1,3,1,3,2,1]),Int32Array.from([1,1,2,3,1,3]),Int32Array.from([1,3,2,1,1,3]),Int32Array.from([1,3,2,3,1,1]),Int32Array.from([2,1,1,3,1,3]),Int32Array.from([2,3,1,1,1,3]),Int32Array.from([2,3,1,3,1,1]),Int32Array.from([1,1,2,1,3,3]),Int32Array.from([1,1,2,3,3,1]),Int32Array.from([1,3,2,1,3,1]),Int32Array.from([1,1,3,1,2,3]),Int32Array.from([1,1,3,3,2,1]),Int32Array.from([1,3,3,1,2,1]),Int32Array.from([3,1,3,1,2,1]),Int32Array.from([2,1,1,3,3,1]),Int32Array.from([2,3,1,1,3,1]),Int32Array.from([2,1,3,1,1,3]),Int32Array.from([2,1,3,3,1,1]),Int32Array.from([2,1,3,1,3,1]),Int32Array.from([3,1,1,1,2,3]),Int32Array.from([3,1,1,3,2,1]),Int32Array.from([3,3,1,1,2,1]),Int32Array.from([3,1,2,1,1,3]),Int32Array.from([3,1,2,3,1,1]),Int32Array.from([3,3,2,1,1,1]),Int32Array.from([3,1,4,1,1,1]),Int32Array.from([2,2,1,4,1,1]),Int32Array.from([4,3,1,1,1,1]),Int32Array.from([1,1,1,2,2,4]),Int32Array.from([1,1,1,4,2,2]),Int32Array.from([1,2,1,1,2,4]),Int32Array.from([1,2,1,4,2,1]),Int32Array.from([1,4,1,1,2,2]),Int32Array.from([1,4,1,2,2,1]),Int32Array.from([1,1,2,2,1,4]),Int32Array.from([1,1,2,4,1,2]),Int32Array.from([1,2,2,1,1,4]),Int32Array.from([1,2,2,4,1,1]),Int32Array.from([1,4,2,1,1,2]),Int32Array.from([1,4,2,2,1,1]),Int32Array.from([2,4,1,2,1,1]),Int32Array.from([2,2,1,1,1,4]),Int32Array.from([4,1,3,1,1,1]),Int32Array.from([2,4,1,1,1,2]),Int32Array.from([1,3,4,1,1,1]),Int32Array.from([1,1,1,2,4,2]),Int32Array.from([1,2,1,1,4,2]),Int32Array.from([1,2,1,2,4,1]),Int32Array.from([1,1,4,2,1,2]),Int32Array.from([1,2,4,1,1,2]),Int32Array.from([1,2,4,2,1,1]),Int32Array.from([4,1,1,2,1,2]),Int32Array.from([4,2,1,1,1,2]),Int32Array.from([4,2,1,2,1,1]),Int32Array.from([2,1,2,1,4,1]),Int32Array.from([2,1,4,1,2,1]),Int32Array.from([4,1,2,1,2,1]),Int32Array.from([1,1,1,1,4,3]),Int32Array.from([1,1,1,3,4,1]),Int32Array.from([1,3,1,1,4,1]),Int32Array.from([1,1,4,1,1,3]),Int32Array.from([1,1,4,3,1,1]),Int32Array.from([4,1,1,1,1,3]),Int32Array.from([4,1,1,3,1,1]),Int32Array.from([1,1,3,1,4,1]),Int32Array.from([1,1,4,1,3,1]),Int32Array.from([3,1,1,1,4,1]),Int32Array.from([4,1,1,1,3,1]),Int32Array.from([2,1,1,4,1,2]),Int32Array.from([2,1,1,2,1,4]),Int32Array.from([2,1,1,2,3,2]),Int32Array.from([2,3,3,1,1,1,2])],he.MAX_AVG_VARIANCE=.25,he.MAX_INDIVIDUAL_VARIANCE=.7,he.CODE_SHIFT=98,he.CODE_CODE_C=99,he.CODE_CODE_B=100,he.CODE_CODE_A=101,he.CODE_FNC_1=102,he.CODE_FNC_2=97,he.CODE_FNC_3=96,he.CODE_FNC_4_A=101,he.CODE_FNC_4_B=100,he.CODE_START_A=103,he.CODE_START_B=104,he.CODE_START_C=105,he.CODE_STOP=106;class Nt extends bt{constructor(e=!1,n=!1){super(),this.usingCheckDigit=e,this.extendedMode=n,this.decodeRowResult="",this.counters=new Int32Array(9)}decodeRow(e,n,i){let s=this.counters;s.fill(0),this.decodeRowResult="";let a=Nt.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),d=n.getSize(),h,p;do{Nt.recordPattern(n,l,s);let F=Nt.toNarrowWidePattern(s);if(F<0)throw new $;h=Nt.patternToChar(F),this.decodeRowResult+=h,p=l;for(let H of s)l+=H;l=n.getNextSet(l)}while(h!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let y=0;for(let F of s)y+=F;let E=l-p-y;if(l!==d&&E*2<y)throw new $;if(this.usingCheckDigit){let F=this.decodeRowResult.length-1,H=0;for(let Y=0;Y<F;Y++)H+=Nt.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(Y));if(this.decodeRowResult.charAt(F)!==Nt.ALPHABET_STRING.charAt(H%43))throw new O;this.decodeRowResult=this.decodeRowResult.substring(0,F)}if(this.decodeRowResult.length===0)throw new $;let I;this.extendedMode?I=Nt.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let k=(a[1]+a[0])/2,L=p+y/2;return new Ee(I,null,0,[new ve(k,e),new ve(L,e)],Ce.CODE_39,new Date().getTime())}static findAsteriskPattern(e,n){let i=e.getSize(),s=e.getNextSet(0),a=0,l=s,d=!1,h=n.length;for(let p=s;p<i;p++)if(e.get(p)!==d)n[a]++;else{if(a===h-1){if(this.toNarrowWidePattern(n)===Nt.ASTERISK_ENCODING&&e.isRange(Math.max(0,l-Math.floor((p-l)/2)),l,!1))return[l,p];l+=n[0]+n[1],n.copyWithin(0,2,2+a-1),n[a-1]=0,n[a]=0,a--}else a++;n[a]=1,d=!d}throw new $}static toNarrowWidePattern(e){let n=e.length,i=0,s;do{let a=2147483647;for(let h of e)h<a&&h>i&&(a=h);i=a,s=0;let l=0,d=0;for(let h=0;h<n;h++){let p=e[h];p>i&&(d|=1<<n-1-h,s++,l+=p)}if(s===3){for(let h=0;h<n&&s>0;h++){let p=e[h];if(p>i&&(s--,p*2>=l))return-1}return d}}while(s>3);return-1}static patternToChar(e){for(let n=0;n<Nt.CHARACTER_ENCODINGS.length;n++)if(Nt.CHARACTER_ENCODINGS[n]===e)return Nt.ALPHABET_STRING.charAt(n);if(e===Nt.ASTERISK_ENCODING)return"*";throw new $}static decodeExtended(e){let n=e.length,i="";for(let s=0;s<n;s++){let a=e.charAt(s);if(a==="+"||a==="$"||a==="%"||a==="/"){let l=e.charAt(s+1),d="\0";switch(a){case"+":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)+32);else throw new U;break;case"$":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)-64);else throw new U;break;case"%":if(l>="A"&&l<="E")d=String.fromCharCode(l.charCodeAt(0)-38);else if(l>="F"&&l<="J")d=String.fromCharCode(l.charCodeAt(0)-11);else if(l>="K"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)+16);else if(l>="P"&&l<="T")d=String.fromCharCode(l.charCodeAt(0)+43);else if(l==="U")d="\0";else if(l==="V")d="@";else if(l==="W")d="`";else if(l==="X"||l==="Y"||l==="Z")d="";else throw new U;break;case"/":if(l>="A"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")d=":";else throw new U;break}i+=d,s++}else i+=a}return i}}Nt.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",Nt.CHARACTER_ENCODINGS=[52,289,97,352,49,304,112,37,292,100,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,168,162,138,42],Nt.ASTERISK_ENCODING=148;class nt extends bt{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,i){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new xe;nt.decodeMiddle(n,s[1],a[0],l);let d=l.toString(),h=null;i!=null&&(h=i.get(V.ALLOWED_LENGTHS)),h==null&&(h=nt.DEFAULT_ALLOWED_LENGTHS);let p=d.length,y=!1,E=0;for(let L of h){if(p===L){y=!0;break}L>E&&(E=L)}if(!y&&p>E&&(y=!0),!y)throw new U;const I=[new ve(s[1],e),new ve(a[0],e)];return new Ee(d,null,0,I,Ce.ITF,new Date().getTime())}static decodeMiddle(e,n,i,s){let a=new Int32Array(10),l=new Int32Array(5),d=new Int32Array(5);for(a.fill(0),l.fill(0),d.fill(0);n<i;){bt.recordPattern(e,n,a);for(let p=0;p<5;p++){let y=2*p;l[p]=a[y],d[p]=a[y+1]}let h=nt.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(d),s.append(h.toString()),a.forEach(function(p){n+=p})}}decodeStart(e){let n=nt.skipWhiteSpace(e),i=nt.findGuardPattern(e,n,nt.START_PATTERN);return this.narrowLineWidth=(i[1]-i[0])/4,this.validateQuietZone(e,i[0]),i}validateQuietZone(e,n){let i=this.narrowLineWidth*10;i=i<n?i:n;for(let s=n-1;i>0&&s>=0&&!e.get(s);s--)i--;if(i!==0)throw new $}static skipWhiteSpace(e){const n=e.getSize(),i=e.getNextSet(0);if(i===n)throw new $;return i}decodeEnd(e){e.reverse();try{let n=nt.skipWhiteSpace(e),i;try{i=nt.findGuardPattern(e,n,nt.END_PATTERN_REVERSED[0])}catch(a){a instanceof $&&(i=nt.findGuardPattern(e,n,nt.END_PATTERN_REVERSED[1]))}this.validateQuietZone(e,i[0]);let s=i[0];return i[0]=e.getSize()-i[1],i[1]=e.getSize()-s,i}finally{e.reverse()}}static findGuardPattern(e,n,i){let s=i.length,a=new Int32Array(s),l=e.getSize(),d=!1,h=0,p=n;a.fill(0);for(let y=n;y<l;y++)if(e.get(y)!==d)a[h]++;else{if(h===s-1){if(bt.patternMatchVariance(a,i,nt.MAX_INDIVIDUAL_VARIANCE)<nt.MAX_AVG_VARIANCE)return[p,y];p+=a[0]+a[1],D.arraycopy(a,2,a,0,h-1),a[h-1]=0,a[h]=0,h--}else h++;a[h]=1,d=!d}throw new $}static decodeDigit(e){let n=nt.MAX_AVG_VARIANCE,i=-1,s=nt.PATTERNS.length;for(let a=0;a<s;a++){let l=nt.PATTERNS[a],d=bt.patternMatchVariance(e,l,nt.MAX_INDIVIDUAL_VARIANCE);d<n?(n=d,i=a):d===n&&(i=-1)}if(i>=0)return i%10;throw new $}}nt.PATTERNS=[Int32Array.from([1,1,2,2,1]),Int32Array.from([2,1,1,1,2]),Int32Array.from([1,2,1,1,2]),Int32Array.from([2,2,1,1,1]),Int32Array.from([1,1,2,1,2]),Int32Array.from([2,1,2,1,1]),Int32Array.from([1,2,2,1,1]),Int32Array.from([1,1,1,2,2]),Int32Array.from([2,1,1,2,1]),Int32Array.from([1,2,1,2,1]),Int32Array.from([1,1,3,3,1]),Int32Array.from([3,1,1,1,3]),Int32Array.from([1,3,1,1,3]),Int32Array.from([3,3,1,1,1]),Int32Array.from([1,1,3,1,3]),Int32Array.from([3,1,3,1,1]),Int32Array.from([1,3,3,1,1]),Int32Array.from([1,1,1,3,3]),Int32Array.from([3,1,1,3,1]),Int32Array.from([1,3,1,3,1])],nt.MAX_AVG_VARIANCE=.38,nt.MAX_INDIVIDUAL_VARIANCE=.5,nt.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],nt.START_PATTERN=Int32Array.from([1,1,1,1]),nt.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class mt extends bt{constructor(){super(...arguments),this.decodeRowStringBuffer=""}static findStartGuardPattern(e){let n=!1,i,s=0,a=Int32Array.from([0,0,0]);for(;!n;){a=Int32Array.from([0,0,0]),i=mt.findGuardPattern(e,s,!1,this.START_END_PATTERN,a);let l=i[0];s=i[1];let d=l-(s-l);d>=0&&(n=e.isRange(d,l,!1))}return i}static checkChecksum(e){return mt.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return mt.getStandardUPCEANChecksum(e.substring(0,n-1))===i}static getStandardUPCEANChecksum(e){let n=e.length,i=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new U;i+=a}i*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new U;i+=a}return(1e3-i)%10}static decodeEnd(e,n){return mt.findGuardPattern(e,n,!1,mt.START_END_PATTERN,new Int32Array(mt.START_END_PATTERN.length).fill(0))}static findGuardPatternWithoutCounters(e,n,i,s){return this.findGuardPattern(e,n,i,s,new Int32Array(s.length))}static findGuardPattern(e,n,i,s,a){let l=e.getSize();n=i?e.getNextUnset(n):e.getNextSet(n);let d=0,h=n,p=s.length,y=i;for(let E=n;E<l;E++)if(e.get(E)!==y)a[d]++;else{if(d===p-1){if(bt.patternMatchVariance(a,s,mt.MAX_INDIVIDUAL_VARIANCE)<mt.MAX_AVG_VARIANCE)return Int32Array.from([h,E]);h+=a[0]+a[1];let I=a.slice(2,a.length-1);for(let k=0;k<d-1;k++)a[k]=I[k];a[d-1]=0,a[d]=0,d--}else d++;a[d]=1,y=!y}throw new $}static decodeDigit(e,n,i,s){this.recordPattern(e,i,n);let a=this.MAX_AVG_VARIANCE,l=-1,d=s.length;for(let h=0;h<d;h++){let p=s[h],y=bt.patternMatchVariance(n,p,mt.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new $}}mt.MAX_AVG_VARIANCE=.48,mt.MAX_INDIVIDUAL_VARIANCE=.7,mt.START_END_PATTERN=Int32Array.from([1,1,1]),mt.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),mt.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),mt.L_PATTERNS=[Int32Array.from([3,2,1,1]),Int32Array.from([2,2,2,1]),Int32Array.from([2,1,2,2]),Int32Array.from([1,4,1,1]),Int32Array.from([1,1,3,2]),Int32Array.from([1,2,3,1]),Int32Array.from([1,1,1,4]),Int32Array.from([1,3,1,2]),Int32Array.from([1,2,1,3]),Int32Array.from([3,1,1,2])];class $e{constructor(){this.CHECK_DIGIT_ENCODINGS=[24,20,18,17,12,6,3,10,9,5],this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,i){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,i,s),l=s.toString(),d=$e.parseExtensionString(l),h=[new ve((i[0]+i[1])/2,e),new ve(a,e)],p=new Ee(l,null,0,h,Ce.UPC_EAN_EXTENSION,new Date().getTime());return d!=null&&p.putAllMetadata(d),p}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let p=0;p<5&&l<a;p++){let y=mt.decodeDigit(e,s,l,mt.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<4-p),p!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==5)throw new $;let h=this.determineCheckDigit(d);if($e.extensionChecksum(i.toString())!==h)throw new $;return l}static extensionChecksum(e){let n=e.length,i=0;for(let s=n-2;s>=0;s-=2)i+=e.charAt(s).charCodeAt(0)-48;i*=3;for(let s=n-1;s>=0;s-=2)i+=e.charAt(s).charCodeAt(0)-48;return i*=3,i%10}determineCheckDigit(e){for(let n=0;n<10;n++)if(e===this.CHECK_DIGIT_ENCODINGS[n])return n;throw new $}static parseExtensionString(e){if(e.length!==5)return null;let n=$e.parseExtension5String(e);return n==null?null:new Map([[Ue.SUGGESTED_PRICE,n]])}static parseExtension5String(e){let n;switch(e.charAt(0)){case"0":n="£";break;case"5":n="$";break;case"9":switch(e){case"90000":return null;case"99991":return"0.00";case"99990":return"Used"}n="";break;default:n="";break}let i=parseInt(e.substring(1)),s=(i/100).toString(),a=i%100,l=a<10?"0"+a:a.toString();return n+s+"."+l}}class ke{constructor(){this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,i){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,i,s),l=s.toString(),d=ke.parseExtensionString(l),h=[new ve((i[0]+i[1])/2,e),new ve(a,e)],p=new Ee(l,null,0,h,Ce.UPC_EAN_EXTENSION,new Date().getTime());return d!=null&&p.putAllMetadata(d),p}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let h=0;h<2&&l<a;h++){let p=mt.decodeDigit(e,s,l,mt.L_AND_G_PATTERNS);i+=String.fromCharCode(48+p%10);for(let y of s)l+=y;p>=10&&(d|=1<<1-h),h!==1&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==2)throw new $;if(parseInt(i.toString())%4!==d)throw new $;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[Ue.ISSUE_NUMBER,parseInt(e)]])}}class Ye{static decodeRow(e,n,i){let s=mt.findGuardPattern(n,i,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new $e().decodeRow(e,n,s)}catch{return new ke().decodeRow(e,n,s)}}}Ye.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class He extends mt{constructor(){super(),this.decodeRowStringBuffer="",He.L_AND_G_PATTERNS=He.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=He.L_PATTERNS[e-10],i=new Int32Array(n.length);for(let s=0;s<n.length;s++)i[s]=n[n.length-s-1];He.L_AND_G_PATTERNS[e]=i}}decodeRow(e,n,i){let s=He.findStartGuardPattern(n),a=i==null?null:i.get(V.NEED_RESULT_POINT_CALLBACK);if(a!=null){const ae=new ve((s[0]+s[1])/2,e);a.foundPossibleResultPoint(ae)}let l=this.decodeMiddle(n,s,this.decodeRowStringBuffer),d=l.rowOffset,h=l.resultString;if(a!=null){const ae=new ve(d,e);a.foundPossibleResultPoint(ae)}let p=this.decodeEnd(n,d);if(a!=null){const ae=new ve((p[0]+p[1])/2,e);a.foundPossibleResultPoint(ae)}let y=p[1],E=y+(y-p[0]);if(E>=n.getSize()||!n.isRange(y,E,!1))throw new $;let I=h.toString();if(I.length<8)throw new U;if(!He.checkChecksum(I))throw new O;let k=(s[1]+s[0])/2,L=(p[1]+p[0])/2,F=this.getBarcodeFormat(),H=[new ve(k,e),new ve(L,e)],Y=new Ee(I,null,0,H,F,new Date().getTime()),le=0;try{let ae=Ye.decodeRow(e,n,p[1]);Y.putMetadata(Ue.UPC_EAN_EXTENSION,ae.getText()),Y.putAllMetadata(ae.getResultMetadata()),Y.addResultPoints(ae.getResultPoints()),le=ae.getText().length}catch{}let ce=i==null?null:i.get(V.ALLOWED_EAN_EXTENSIONS);if(ce!=null){let ae=!1;for(let We in ce)if(le.toString()===We){ae=!0;break}if(!ae)throw new $}return Y}decodeEnd(e,n){return He.findGuardPattern(e,n,!1,He.START_END_PATTERN,new Int32Array(He.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return He.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return He.getStandardUPCEANChecksum(e.substring(0,n-1))===i}static getStandardUPCEANChecksum(e){let n=e.length,i=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new U;i+=a}i*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new U;i+=a}return(1e3-i)%10}}class Ln extends He{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let p=0;p<6&&l<a;p++){let y=He.decodeDigit(e,s,l,He.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-p)}i=Ln.determineFirstDigit(i,d),l=He.findGuardPattern(e,l,!0,He.MIDDLE_PATTERN,new Int32Array(He.MIDDLE_PATTERN.length).fill(0))[1];for(let p=0;p<6&&l<a;p++){let y=He.decodeDigit(e,s,l,He.L_PATTERNS);i+=String.fromCharCode(48+y);for(let E of s)l+=E}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return Ce.EAN_13}static determineFirstDigit(e,n){for(let i=0;i<10;i++)if(n===this.FIRST_DIGIT_ENCODINGS[i])return e=String.fromCharCode(48+i)+e,e;throw new $}}Ln.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class ns extends He{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,i){const s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1];for(let h=0;h<4&&l<a;h++){let p=He.decodeDigit(e,s,l,He.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}l=He.findGuardPattern(e,l,!0,He.MIDDLE_PATTERN,new Int32Array(He.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let p=He.decodeDigit(e,s,l,He.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return Ce.EAN_8}}class rs extends He{constructor(){super(...arguments),this.ean13Reader=new Ln}getBarcodeFormat(){return Ce.UPC_A}decode(e,n){return this.maybeReturnResult(this.ean13Reader.decode(e))}decodeRow(e,n,i){return this.maybeReturnResult(this.ean13Reader.decodeRow(e,n,i))}decodeMiddle(e,n,i){return this.ean13Reader.decodeMiddle(e,n,i)}maybeReturnResult(e){let n=e.getText();if(n.charAt(0)==="0"){let i=new Ee(n.substring(1),null,null,e.getResultPoints(),Ce.UPC_A);return e.getResultMetadata()!=null&&i.putAllMetadata(e.getResultMetadata()),i}else throw new $}reset(){this.ean13Reader.reset()}}class xn extends He{constructor(){super(),this.decodeMiddleCounters=new Int32Array(4)}decodeMiddle(e,n,i){const s=this.decodeMiddleCounters.map(p=>p);s[0]=0,s[1]=0,s[2]=0,s[3]=0;const a=e.getSize();let l=n[1],d=0;for(let p=0;p<6&&l<a;p++){const y=xn.decodeDigit(e,s,l,xn.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-p)}let h=xn.determineNumSysAndCheckDigit(i,d);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return xn.findGuardPatternWithoutCounters(e,n,!0,xn.MIDDLE_END_PATTERN)}checkChecksum(e){return He.checkChecksum(xn.convertUPCEtoUPCA(e))}static determineNumSysAndCheckDigit(e,n){for(let i=0;i<=1;i++)for(let s=0;s<10;s++)if(n===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[i][s]){let a=String.fromCharCode(48+i),l=String.fromCharCode(48+s);return a+e+l}throw $.getNotFoundInstance()}getBarcodeFormat(){return Ce.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),i=new xe;i.append(e.charAt(0));let s=n[5];switch(s){case 0:case 1:case 2:i.appendChars(n,0,2),i.append(s),i.append("0000"),i.appendChars(n,2,3);break;case 3:i.appendChars(n,0,3),i.append("00000"),i.appendChars(n,3,2);break;case 4:i.appendChars(n,0,4),i.append("00000"),i.append(n[4]);break;default:i.appendChars(n,0,5),i.append("0000"),i.append(s);break}return e.length>=8&&i.append(e.charAt(7)),i.toString()}}xn.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),xn.NUMSYS_AND_CHECK_DIGIT_PATTERNS=[Int32Array.from([56,52,50,49,44,38,35,42,41,37]),Int32Array.from([7,11,13,14,19,25,28,21,22,26])];class Fi extends bt{constructor(e){super();let n=e==null?null:e.get(V.POSSIBLE_FORMATS),i=[];c(n)?(i.push(new Ln),i.push(new rs),i.push(new ns),i.push(new xn)):(n.indexOf(Ce.EAN_13)>-1&&i.push(new Ln),n.indexOf(Ce.UPC_A)>-1&&i.push(new rs),n.indexOf(Ce.EAN_8)>-1&&i.push(new ns),n.indexOf(Ce.UPC_E)>-1&&i.push(new xn)),this.readers=i}decodeRow(e,n,i){for(let s of this.readers)try{const a=s.decodeRow(e,n,i),l=a.getBarcodeFormat()===Ce.EAN_13&&a.getText().charAt(0)==="0",d=i==null?null:i.get(V.POSSIBLE_FORMATS),h=d==null||d.includes(Ce.UPC_A);if(l&&h){const p=a.getRawBytes(),y=new Ee(a.getText().substring(1),p,p?p.length:null,a.getResultPoints(),Ce.UPC_A);return y.putAllMetadata(a.getResultMetadata()),y}return a}catch{}throw new $}reset(){for(let e of this.readers)e.reset()}}class jt extends bt{constructor(){super(),this.decodeFinderCounters=new Int32Array(4),this.dataCharacterCounters=new Int32Array(8),this.oddRoundingErrors=new Array(4),this.evenRoundingErrors=new Array(4),this.oddCounts=new Array(this.dataCharacterCounters.length/2),this.evenCounts=new Array(this.dataCharacterCounters.length/2)}getDecodeFinderCounters(){return this.decodeFinderCounters}getDataCharacterCounters(){return this.dataCharacterCounters}getOddRoundingErrors(){return this.oddRoundingErrors}getEvenRoundingErrors(){return this.evenRoundingErrors}getOddCounts(){return this.oddCounts}getEvenCounts(){return this.evenCounts}parseFinderValue(e,n){for(let i=0;i<n.length;i++)if(bt.patternMatchVariance(e,n[i],jt.MAX_INDIVIDUAL_VARIANCE)<jt.MAX_AVG_VARIANCE)return i;throw new $}static count(e){return Ze.sum(new Int32Array(e))}static increment(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]>s&&(s=n[a],i=a);e[i]++}static decrement(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]<s&&(s=n[a],i=a);e[i]--}static isFinderPattern(e){let n=e[0]+e[1],i=n+e[2]+e[3],s=n/i;if(s>=jt.MIN_FINDER_PATTERN_RATIO&&s<=jt.MAX_FINDER_PATTERN_RATIO){let a=Number.MAX_SAFE_INTEGER,l=Number.MIN_SAFE_INTEGER;for(let d of e)d>l&&(l=d),d<a&&(a=d);return l<10*a}return!1}}jt.MAX_AVG_VARIANCE=.2,jt.MAX_INDIVIDUAL_VARIANCE=.45,jt.MIN_FINDER_PATTERN_RATIO=9.5/12,jt.MAX_FINDER_PATTERN_RATIO=12.5/14;class yr{constructor(e,n){this.value=e,this.checksumPortion=n}getValue(){return this.value}getChecksumPortion(){return this.checksumPortion}toString(){return this.value+"("+this.checksumPortion+")"}equals(e){if(!(e instanceof yr))return!1;const n=e;return this.value===n.value&&this.checksumPortion===n.checksumPortion}hashCode(){return this.value^this.checksumPortion}}class oi{constructor(e,n,i,s,a){this.value=e,this.startEnd=n,this.value=e,this.startEnd=n,this.resultPoints=new Array,this.resultPoints.push(new ve(i,a)),this.resultPoints.push(new ve(s,a))}getValue(){return this.value}getStartEnd(){return this.startEnd}getResultPoints(){return this.resultPoints}equals(e){if(!(e instanceof oi))return!1;const n=e;return this.value===n.value}hashCode(){return this.value}}class Tn{constructor(){}static getRSSvalue(e,n,i){let s=0;for(let h of e)s+=h;let a=0,l=0,d=e.length;for(let h=0;h<d-1;h++){let p;for(p=1,l|=1<<h;p<e[h];p++,l&=~(1<<h)){let y=Tn.combins(s-p-1,d-h-2);if(i&&l===0&&s-p-(d-h-1)>=d-h-1&&(y-=Tn.combins(s-p-(d-h),d-h-2)),d-h-1>1){let E=0;for(let I=s-p-(d-h-2);I>n;I--)E+=Tn.combins(s-p-I-1,d-h-3);y-=E*(d-1-h)}else s-p>n&&y--;a+=y}s-=p}return a}static combins(e,n){let i,s;e-n>n?(s=n,i=e-n):(s=e-n,i=n);let a=1,l=1;for(let d=e;d>i;d--)a*=d,l<=s&&(a/=l,l++);for(;l<=s;)a/=l,l++;return a}}class Pu{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let i=12*n,s=new ee(i),a=0,d=e[0].getRightChar().getValue();for(let h=11;h>=0;--h)(d&1<<h)!=0&&s.set(a),a++;for(let h=1;h<e.length;++h){let p=e[h],y=p.getLeftChar().getValue();for(let E=11;E>=0;--E)(y&1<<E)!=0&&s.set(a),a++;if(p.getRightChar()!=null){let E=p.getRightChar().getValue();for(let I=11;I>=0;--I)(E&1<<I)!=0&&s.set(a),a++}}return s}}class ir{constructor(e,n){n?this.decodedInformation=null:(this.finished=e,this.decodedInformation=n)}getDecodedInformation(){return this.decodedInformation}isFinished(){return this.finished}}class Ui{constructor(e){this.newPosition=e}getNewPosition(){return this.newPosition}}class Qt extends Ui{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===Qt.FNC1}}Qt.FNC1="$";class or extends Ui{constructor(e,n,i){super(e),i?(this.remaining=!0,this.remainingValue=this.remainingValue):(this.remaining=!1,this.remainingValue=0),this.newString=n}getNewString(){return this.newString}isRemaining(){return this.remaining}getRemainingValue(){return this.remainingValue}}class hn extends Ui{constructor(e,n,i){if(super(e),n<0||n>10||i<0||i>10)throw new U;this.firstDigit=n,this.secondDigit=i}getFirstDigit(){return this.firstDigit}getSecondDigit(){return this.secondDigit}getValue(){return this.firstDigit*10+this.secondDigit}isFirstDigitFNC1(){return this.firstDigit===hn.FNC1}isSecondDigitFNC1(){return this.secondDigit===hn.FNC1}isAnyFNC1(){return this.firstDigit===hn.FNC1||this.secondDigit===hn.FNC1}}hn.FNC1=10;class we{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new $;let n=e.substring(0,2);for(let a of we.TWO_DIGIT_DATA_LENGTH)if(a[0]===n)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(2,a[2],e):we.processFixedAI(2,a[1],e);if(e.length<3)throw new $;let i=e.substring(0,3);for(let a of we.THREE_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(3,a[2],e):we.processFixedAI(3,a[1],e);for(let a of we.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(4,a[2],e):we.processFixedAI(4,a[1],e);if(e.length<4)throw new $;let s=e.substring(0,4);for(let a of we.FOUR_DIGIT_DATA_LENGTH)if(a[0]===s)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(4,a[2],e):we.processFixedAI(4,a[1],e);throw new $}static processFixedAI(e,n,i){if(i.length<e)throw new $;let s=i.substring(0,e);if(i.length<e+n)throw new $;let a=i.substring(e,e+n),l=i.substring(e+n),d="("+s+")"+a,h=we.parseFieldsInGeneralPurpose(l);return h==null?d:d+h}static processVariableAI(e,n,i){let s=i.substring(0,e),a;i.length<e+n?a=i.length:a=e+n;let l=i.substring(e,a),d=i.substring(a),h="("+s+")"+l,p=we.parseFieldsInGeneralPurpose(d);return p==null?h:h+p}}we.VARIABLE_LENGTH=[],we.TWO_DIGIT_DATA_LENGTH=[["00",18],["01",14],["02",14],["10",we.VARIABLE_LENGTH,20],["11",6],["12",6],["13",6],["15",6],["17",6],["20",2],["21",we.VARIABLE_LENGTH,20],["22",we.VARIABLE_LENGTH,29],["30",we.VARIABLE_LENGTH,8],["37",we.VARIABLE_LENGTH,8],["90",we.VARIABLE_LENGTH,30],["91",we.VARIABLE_LENGTH,30],["92",we.VARIABLE_LENGTH,30],["93",we.VARIABLE_LENGTH,30],["94",we.VARIABLE_LENGTH,30],["95",we.VARIABLE_LENGTH,30],["96",we.VARIABLE_LENGTH,30],["97",we.VARIABLE_LENGTH,3],["98",we.VARIABLE_LENGTH,30],["99",we.VARIABLE_LENGTH,30]],we.THREE_DIGIT_DATA_LENGTH=[["240",we.VARIABLE_LENGTH,30],["241",we.VARIABLE_LENGTH,30],["242",we.VARIABLE_LENGTH,6],["250",we.VARIABLE_LENGTH,30],["251",we.VARIABLE_LENGTH,30],["253",we.VARIABLE_LENGTH,17],["254",we.VARIABLE_LENGTH,20],["400",we.VARIABLE_LENGTH,30],["401",we.VARIABLE_LENGTH,30],["402",17],["403",we.VARIABLE_LENGTH,30],["410",13],["411",13],["412",13],["413",13],["414",13],["420",we.VARIABLE_LENGTH,20],["421",we.VARIABLE_LENGTH,15],["422",3],["423",we.VARIABLE_LENGTH,15],["424",3],["425",3],["426",3]],we.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH=[["310",6],["311",6],["312",6],["313",6],["314",6],["315",6],["316",6],["320",6],["321",6],["322",6],["323",6],["324",6],["325",6],["326",6],["327",6],["328",6],["329",6],["330",6],["331",6],["332",6],["333",6],["334",6],["335",6],["336",6],["340",6],["341",6],["342",6],["343",6],["344",6],["345",6],["346",6],["347",6],["348",6],["349",6],["350",6],["351",6],["352",6],["353",6],["354",6],["355",6],["356",6],["357",6],["360",6],["361",6],["362",6],["363",6],["364",6],["365",6],["366",6],["367",6],["368",6],["369",6],["390",we.VARIABLE_LENGTH,15],["391",we.VARIABLE_LENGTH,18],["392",we.VARIABLE_LENGTH,15],["393",we.VARIABLE_LENGTH,18],["703",we.VARIABLE_LENGTH,30]],we.FOUR_DIGIT_DATA_LENGTH=[["7001",13],["7002",we.VARIABLE_LENGTH,30],["7003",10],["8001",14],["8002",we.VARIABLE_LENGTH,20],["8003",we.VARIABLE_LENGTH,30],["8004",we.VARIABLE_LENGTH,30],["8005",6],["8006",18],["8007",we.VARIABLE_LENGTH,30],["8008",we.VARIABLE_LENGTH,12],["8018",18],["8020",we.VARIABLE_LENGTH,25],["8100",6],["8101",10],["8102",2],["8110",we.VARIABLE_LENGTH,70],["8200",we.VARIABLE_LENGTH,70]];class wr{constructor(e){this.buffer=new xe,this.information=e}decodeAllCodes(e,n){let i=n,s=null;do{let a=this.decodeGeneralPurposeField(i,s),l=we.parseFieldsInGeneralPurpose(a.getNewString());if(l!=null&&e.append(l),a.isRemaining()?s=""+a.getRemainingValue():s=null,i===a.getNewPosition())break;i=a.getNewPosition()}while(!0);return e.toString()}isStillNumeric(e){if(e+7>this.information.getSize())return e+4<=this.information.getSize();for(let n=e;n<e+3;++n)if(this.information.get(n))return!0;return this.information.get(e+3)}decodeNumeric(e){if(e+7>this.information.getSize()){let a=this.extractNumericValueFromBitArray(e,4);return a===0?new hn(this.information.getSize(),hn.FNC1,hn.FNC1):new hn(this.information.getSize(),a-1,hn.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),i=(n-8)/11,s=(n-8)%11;return new hn(e+7,i,s)}extractNumericValueFromBitArray(e,n){return wr.extractNumericValueFromBitArray(this.information,e,n)}static extractNumericValueFromBitArray(e,n,i){let s=0;for(let a=0;a<i;++a)e.get(n+a)&&(s|=1<<i-a-1);return s}decodeGeneralPurposeField(e,n){this.buffer.setLengthToZero(),n!=null&&this.buffer.append(n),this.current.setPosition(e);let i=this.parseBlocks();return i!=null&&i.isRemaining()?new or(this.current.getPosition(),this.buffer.toString(),i.getRemainingValue()):new or(this.current.getPosition(),this.buffer.toString())}parseBlocks(){let e,n;do{let i=this.current.getPosition();if(this.current.isAlpha()?(n=this.parseAlphaBlock(),e=n.isFinished()):this.current.isIsoIec646()?(n=this.parseIsoIec646Block(),e=n.isFinished()):(n=this.parseNumericBlock(),e=n.isFinished()),!(i!==this.current.getPosition())&&!e)break}while(!e);return n.getDecodedInformation()}parseNumericBlock(){for(;this.isStillNumeric(this.current.getPosition());){let e=this.decodeNumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFirstDigitFNC1()){let n;return e.isSecondDigitFNC1()?n=new or(this.current.getPosition(),this.buffer.toString()):n=new or(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new ir(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new or(this.current.getPosition(),this.buffer.toString());return new ir(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new ir(!1)}parseIsoIec646Block(){for(;this.isStillIsoIec646(this.current.getPosition());){let e=this.decodeIsoIec646(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new or(this.current.getPosition(),this.buffer.toString());return new ir(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setAlpha()),new ir(!1)}parseAlphaBlock(){for(;this.isStillAlpha(this.current.getPosition());){let e=this.decodeAlphanumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new or(this.current.getPosition(),this.buffer.toString());return new ir(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setIsoIec646()),new ir(!1)}isStillIsoIec646(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+7>this.information.getSize())return!1;let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<116)return!0;if(e+8>this.information.getSize())return!1;let s=this.extractNumericValueFromBitArray(e,8);return s>=232&&s<253}decodeIsoIec646(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Qt(e+5,Qt.FNC1);if(n>=5&&n<15)return new Qt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<90)return new Qt(e+7,""+(i+1));if(i>=90&&i<116)return new Qt(e+7,""+(i+7));let s=this.extractNumericValueFromBitArray(e,8),a;switch(s){case 232:a="!";break;case 233:a='"';break;case 234:a="%";break;case 235:a="&";break;case 236:a="'";break;case 237:a="(";break;case 238:a=")";break;case 239:a="*";break;case 240:a="+";break;case 241:a=",";break;case 242:a="-";break;case 243:a=".";break;case 244:a="/";break;case 245:a=":";break;case 246:a=";";break;case 247:a="<";break;case 248:a="=";break;case 249:a=">";break;case 250:a="?";break;case 251:a="_";break;case 252:a=" ";break;default:throw new U}return new Qt(e+8,a)}isStillAlpha(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+6>this.information.getSize())return!1;let i=this.extractNumericValueFromBitArray(e,6);return i>=16&&i<63}decodeAlphanumeric(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Qt(e+5,Qt.FNC1);if(n>=5&&n<15)return new Qt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,6);if(i>=32&&i<58)return new Qt(e+6,""+(i+33));let s;switch(i){case 58:s="*";break;case 59:s=",";break;case 60:s="-";break;case 61:s=".";break;case 62:s="/";break;default:throw new Wt("Decoding invalid alphanumeric value: "+i)}return new Qt(e+6,s)}isAlphaTo646ToAlphaLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<5&&n+e<this.information.getSize();++n)if(n===2){if(!this.information.get(e+2))return!1}else if(this.information.get(e+n))return!1;return!0}isAlphaOr646ToNumericLatch(e){if(e+3>this.information.getSize())return!1;for(let n=e;n<e+3;++n)if(this.information.get(n))return!1;return!0}isNumericToAlphaNumericLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<4&&n+e<this.information.getSize();++n)if(this.information.get(e+n))return!1;return!0}}class zi{constructor(e){this.information=e,this.generalDecoder=new wr(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class en extends zi{constructor(e){super(e)}encodeCompressedGtin(e,n){e.append("(01)");let i=e.length();e.append("9"),this.encodeCompressedGtinWithoutAI(e,n,i)}encodeCompressedGtinWithoutAI(e,n,i){for(let s=0;s<4;++s){let a=this.getGeneralDecoder().extractNumericValueFromBitArray(n+10*s,10);a/100===0&&e.append("0"),a/10===0&&e.append("0"),e.append(a)}en.appendCheckDigit(e,i)}static appendCheckDigit(e,n){let i=0;for(let s=0;s<13;s++){let a=e.charAt(s+n).charCodeAt(0)-48;i+=(s&1)===0?3*a:a}i=10-i%10,i===10&&(i=0),e.append(i)}}en.GTIN_SIZE=40;class _r extends en{constructor(e){super(e)}parseInformation(){let e=new xe;e.append("(01)");let n=e.length(),i=this.getGeneralDecoder().extractNumericValueFromBitArray(_r.HEADER_SIZE,4);return e.append(i),this.encodeCompressedGtinWithoutAI(e,_r.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,_r.HEADER_SIZE+44)}}_r.HEADER_SIZE=4;class si extends zi{constructor(e){super(e)}parseInformation(){let e=new xe;return this.getGeneralDecoder().decodeAllCodes(e,si.HEADER_SIZE)}}si.HEADER_SIZE=5;class ai extends en{constructor(e){super(e)}encodeCompressedWeight(e,n,i){let s=this.getGeneralDecoder().extractNumericValueFromBitArray(n,i);this.addWeightCode(e,s);let a=this.checkWeight(s),l=1e5;for(let d=0;d<5;++d)a/l===0&&e.append("0"),l/=10;e.append(a)}}class Nn extends ai{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=Nn.HEADER_SIZE+ai.GTIN_SIZE+Nn.WEIGHT_SIZE)throw new $;let e=new xe;return this.encodeCompressedGtin(e,Nn.HEADER_SIZE),this.encodeCompressedWeight(e,Nn.HEADER_SIZE+ai.GTIN_SIZE,Nn.WEIGHT_SIZE),e.toString()}}Nn.HEADER_SIZE=5,Nn.WEIGHT_SIZE=15;class Bu extends Nn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Lu extends Nn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class On extends en{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<On.HEADER_SIZE+en.GTIN_SIZE)throw new $;let e=new xe;this.encodeCompressedGtin(e,On.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(On.HEADER_SIZE+en.GTIN_SIZE,On.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let i=this.getGeneralDecoder().decodeGeneralPurposeField(On.HEADER_SIZE+en.GTIN_SIZE+On.LAST_DIGIT_SIZE,null);return e.append(i.getNewString()),e.toString()}}On.HEADER_SIZE=8,On.LAST_DIGIT_SIZE=2;class qt extends en{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<qt.HEADER_SIZE+en.GTIN_SIZE)throw new $;let e=new xe;this.encodeCompressedGtin(e,qt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(qt.HEADER_SIZE+en.GTIN_SIZE,qt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let i=this.getGeneralDecoder().extractNumericValueFromBitArray(qt.HEADER_SIZE+en.GTIN_SIZE+qt.LAST_DIGIT_SIZE,qt.FIRST_THREE_DIGITS_SIZE);i/100==0&&e.append("0"),i/10==0&&e.append("0"),e.append(i);let s=this.getGeneralDecoder().decodeGeneralPurposeField(qt.HEADER_SIZE+en.GTIN_SIZE+qt.LAST_DIGIT_SIZE+qt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}qt.HEADER_SIZE=8,qt.LAST_DIGIT_SIZE=2,qt.FIRST_THREE_DIGITS_SIZE=10;class gt extends ai{constructor(e,n,i){super(e),this.dateCode=i,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=gt.HEADER_SIZE+gt.GTIN_SIZE+gt.WEIGHT_SIZE+gt.DATE_SIZE)throw new $;let e=new xe;return this.encodeCompressedGtin(e,gt.HEADER_SIZE),this.encodeCompressedWeight(e,gt.HEADER_SIZE+gt.GTIN_SIZE,gt.WEIGHT_SIZE),this.encodeCompressedDate(e,gt.HEADER_SIZE+gt.GTIN_SIZE+gt.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let i=this.getGeneralDecoder().extractNumericValueFromBitArray(n,gt.DATE_SIZE);if(i==38400)return;e.append("("),e.append(this.dateCode),e.append(")");let s=i%32;i/=32;let a=i%12+1;i/=12;let l=i;l/10==0&&e.append("0"),e.append(l),a/10==0&&e.append("0"),e.append(a),s/10==0&&e.append("0"),e.append(s)}addWeightCode(e,n){e.append("("),e.append(this.firstAIdigits),e.append(n/1e5),e.append(")")}checkWeight(e){return e%1e5}}gt.HEADER_SIZE=8,gt.WEIGHT_SIZE=20,gt.DATE_SIZE=16;function is(b){try{if(b.get(1))return new _r(b);if(!b.get(2))return new si(b);switch(wr.extractNumericValueFromBitArray(b,1,4)){case 4:return new Bu(b);case 5:return new Lu(b)}switch(wr.extractNumericValueFromBitArray(b,1,5)){case 12:return new On(b);case 13:return new qt(b)}switch(wr.extractNumericValueFromBitArray(b,1,7)){case 56:return new gt(b,"310","11");case 57:return new gt(b,"320","11");case 58:return new gt(b,"310","13");case 59:return new gt(b,"320","13");case 60:return new gt(b,"310","15");case 61:return new gt(b,"320","15");case 62:return new gt(b,"310","17");case 63:return new gt(b,"320","17")}}catch(e){throw console.log(e),new Wt("unknown decoder: "+b)}}class jn{constructor(e,n,i,s){this.leftchar=e,this.rightchar=n,this.finderpattern=i,this.maybeLast=s}mayBeLast(){return this.maybeLast}getLeftChar(){return this.leftchar}getRightChar(){return this.rightchar}getFinderPattern(){return this.finderpattern}mustBeLast(){return this.rightchar==null}toString(){return"[ "+this.leftchar+", "+this.rightchar+" : "+(this.finderpattern==null?"null":this.finderpattern.getValue())+" ]"}static equals(e,n){return e instanceof jn?jn.equalsOrNull(e.leftchar,n.leftchar)&&jn.equalsOrNull(e.rightchar,n.rightchar)&&jn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:jn.equals(e,n)}hashCode(){return this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue()}}class Vi{constructor(e,n,i){this.pairs=e,this.rowNumber=n,this.wasReversed=i}getPairs(){return this.pairs}getRowNumber(){return this.rowNumber}isReversed(){return this.wasReversed}isEquivalent(e){return this.checkEqualitity(this,e)}toString(){return"{ "+this.pairs+" }"}equals(e,n){return e instanceof Vi?this.checkEqualitity(e,n)&&e.wasReversed===n.wasReversed:!1}checkEqualitity(e,n){if(!e||!n)return;let i;return e.forEach((s,a)=>{n.forEach(l=>{s.getLeftChar().getValue()===l.getLeftChar().getValue()&&s.getRightChar().getValue()===l.getRightChar().getValue()&&s.getFinderPatter().getValue()===l.getFinderPatter().getValue()&&(i=!0)})}),i}}class se extends jt{constructor(e){super(...arguments),this.pairs=new Array(se.MAX_PAIRS),this.rows=new Array,this.startEnd=[2],this.verbose=e===!0}decodeRow(e,n,i){this.pairs.length=0,this.startFromEven=!1;try{return se.constructResult(this.decodeRow2pairs(e,n))}catch(s){this.verbose&&console.log(s)}return this.pairs.length=0,this.startFromEven=!0,se.constructResult(this.decodeRow2pairs(e,n))}reset(){this.pairs.length=0,this.rows.length=0}decodeRow2pairs(e,n){let i=!1;for(;!i;)try{this.pairs.push(this.retrieveNextPair(n,this.pairs,e))}catch(a){if(a instanceof $){if(!this.pairs.length)throw new $;i=!0}}if(this.checkChecksum())return this.pairs;let s;if(this.rows.length?s=!0:s=!1,this.storeRow(e,!1),s){let a=this.checkRowsBoolean(!1);if(a!=null||(a=this.checkRowsBoolean(!0),a!=null))return a}throw new $}checkRowsBoolean(e){if(this.rows.length>25)return this.rows.length=0,null;this.pairs.length=0,e&&(this.rows=this.rows.reverse());let n=null;try{n=this.checkRows(new Array,0)}catch(i){this.verbose&&console.log(i)}return e&&(this.rows=this.rows.reverse()),n}checkRows(e,n){for(let i=n;i<this.rows.length;i++){let s=this.rows[i];this.pairs.length=0;for(let l of e)this.pairs.push(l.getPairs());if(this.pairs.push(s.getPairs()),!se.isValidSequence(this.pairs))continue;if(this.checkChecksum())return this.pairs;let a=new Array(e);a.push(s);try{return this.checkRows(a,i+1)}catch(l){this.verbose&&console.log(l)}}throw new $}static isValidSequence(e){for(let n of se.FINDER_PATTERN_SEQUENCES){if(e.length>n.length)continue;let i=!0;for(let s=0;s<e.length;s++)if(e[s].getFinderPattern().getValue()!=n[s]){i=!1;break}if(i)return!0}return!1}storeRow(e,n){let i=0,s=!1,a=!1;for(;i<this.rows.length;){let l=this.rows[i];if(l.getRowNumber()>e){a=l.isEquivalent(this.pairs);break}s=l.isEquivalent(this.pairs),i++}a||s||se.isPartialRow(this.pairs,this.rows)||(this.rows.push(i,new Vi(this.pairs,e,n)),this.removePartialRows(this.pairs,this.rows))}removePartialRows(e,n){for(let i of n)if(i.getPairs().length!==e.length){for(let s of i.getPairs())for(let a of e)if(jn.equals(s,a))break}}static isPartialRow(e,n){for(let i of n){let s=!0;for(let a of e){let l=!1;for(let d of i.getPairs())if(a.equals(d)){l=!0;break}if(!l){s=!1;break}}if(s)return!0}return!1}getRows(){return this.rows}static constructResult(e){let n=Pu.buildBitArray(e),s=is(n).parseInformation(),a=e[0].getFinderPattern().getResultPoints(),l=e[e.length-1].getFinderPattern().getResultPoints(),d=[a[0],a[1],l[0],l[1]];return new Ee(s,null,null,d,Ce.RSS_EXPANDED,null)}checkChecksum(){let e=this.pairs.get(0),n=e.getLeftChar(),i=e.getRightChar();if(i==null)return!1;let s=i.getChecksumPortion(),a=2;for(let d=1;d<this.pairs.size();++d){let h=this.pairs.get(d);s+=h.getLeftChar().getChecksumPortion(),a++;let p=h.getRightChar();p!=null&&(s+=p.getChecksumPortion(),a++)}return s%=211,211*(a-4)+s==n.getValue()}static getNextSecondBar(e,n){let i;return e.get(n)?(i=e.getNextUnset(n),i=e.getNextSet(i)):(i=e.getNextSet(n),i=e.getNextUnset(i)),i}retrieveNextPair(e,n,i){let s=n.length%2==0;this.startFromEven&&(s=!s);let a,l=!0,d=-1;do this.findNextPair(e,n,d),a=this.parseFoundFinderPattern(e,i,s),a==null?d=se.getNextSecondBar(e,this.startEnd[0]):l=!1;while(l);let h=this.decodeDataCharacter(e,a,s,!0);if(!this.isEmptyPair(n)&&n[n.length-1].mustBeLast())throw new $;let p;try{p=this.decodeDataCharacter(e,a,s,!1)}catch(y){p=null,this.verbose&&console.log(y)}return new jn(h,p,a,!0)}isEmptyPair(e){return e.length===0}findNextPair(e,n,i){let s=this.getDecodeFinderCounters();s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l;i>=0?l=i:this.isEmptyPair(n)?l=0:l=n[n.length-1].getFinderPattern().getStartEnd()[1];let d=n.length%2!=0;this.startFromEven&&(d=!d);let h=!1;for(;l<a&&(h=!e.get(l),!!h);)l++;let p=0,y=l;for(let E=l;E<a;E++)if(e.get(E)!=h)s[p]++;else{if(p==3){if(d&&se.reverseCounters(s),se.isFinderPattern(s)){this.startEnd[0]=y,this.startEnd[1]=E;return}d&&se.reverseCounters(s),y+=s[0]+s[1],s[0]=s[2],s[1]=s[3],s[2]=0,s[3]=0,p--}else p++;s[p]=1,h=!h}throw new $}static reverseCounters(e){let n=e.length;for(let i=0;i<n/2;++i){let s=e[i];e[i]=e[n-i-1],e[n-i-1]=s}}parseFoundFinderPattern(e,n,i){let s,a,l;if(i){let p=this.startEnd[0]-1;for(;p>=0&&!e.get(p);)p--;p++,s=this.startEnd[0]-p,a=p,l=this.startEnd[1]}else a=this.startEnd[0],l=e.getNextUnset(this.startEnd[1]+1),s=l-this.startEnd[1];let d=this.getDecodeFinderCounters();D.arraycopy(d,0,d,1,d.length-1),d[0]=s;let h;try{h=this.parseFinderValue(d,se.FINDER_PATTERNS)}catch{return null}return new oi(h,[a,l],a,l,n)}decodeDataCharacter(e,n,i,s){let a=this.getDataCharacterCounters();for(let st=0;st<a.length;st++)a[st]=0;if(s)se.recordPatternInReverse(e,n.getStartEnd()[0],a);else{se.recordPattern(e,n.getStartEnd()[1],a);for(let st=0,$t=a.length-1;st<$t;st++,$t--){let an=a[st];a[st]=a[$t],a[$t]=an}}let l=17,d=Ze.sum(new Int32Array(a))/l,h=(n.getStartEnd()[1]-n.getStartEnd()[0])/15;if(Math.abs(d-h)/h>.3)throw new $;let p=this.getOddCounts(),y=this.getEvenCounts(),E=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let st=0;st<a.length;st++){let $t=1*a[st]/d,an=$t+.5;if(an<1){if($t<.3)throw new $;an=1}else if(an>8){if($t>8.7)throw new $;an=8}let Ar=st/2;(st&1)==0?(p[Ar]=an,E[Ar]=$t-an):(y[Ar]=an,I[Ar]=$t-an)}this.adjustOddEvenCounts(l);let k=4*n.getValue()+(i?0:2)+(s?0:1)-1,L=0,F=0;for(let st=p.length-1;st>=0;st--){if(se.isNotA1left(n,i,s)){let $t=se.WEIGHTS[k][2*st];F+=p[st]*$t}L+=p[st]}let H=0;for(let st=y.length-1;st>=0;st--)if(se.isNotA1left(n,i,s)){let $t=se.WEIGHTS[k][2*st+1];H+=y[st]*$t}let Y=F+H;if((L&1)!=0||L>13||L<4)throw new $;let le=(13-L)/2,ce=se.SYMBOL_WIDEST[le],ae=9-ce,We=Tn.getRSSvalue(p,ce,!0),Fe=Tn.getRSSvalue(y,ae,!1),nn=se.EVEN_TOTAL_SUBSET[le],yn=se.GSUM[le],rn=We*nn+Fe+yn;return new yr(rn,Y)}static isNotA1left(e,n,i){return!(e.getValue()==0&&n&&i)}adjustOddEvenCounts(e){let n=Ze.sum(new Int32Array(this.getOddCounts())),i=Ze.sum(new Int32Array(this.getEvenCounts())),s=!1,a=!1;n>13?a=!0:n<4&&(s=!0);let l=!1,d=!1;i>13?d=!0:i<4&&(l=!0);let h=n+i-e,p=(n&1)==1,y=(i&1)==0;if(h==1)if(p){if(y)throw new $;a=!0}else{if(!y)throw new $;d=!0}else if(h==-1)if(p){if(y)throw new $;s=!0}else{if(!y)throw new $;l=!0}else if(h==0){if(p){if(!y)throw new $;n<i?(s=!0,d=!0):(a=!0,l=!0)}else if(y)throw new $}else throw new $;if(s){if(a)throw new $;se.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&se.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(d)throw new $;se.increment(this.getEvenCounts(),this.getOddRoundingErrors())}d&&se.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}se.SYMBOL_WIDEST=[7,5,4,3,1],se.EVEN_TOTAL_SUBSET=[4,20,52,104,204],se.GSUM=[0,348,1388,2948,3988],se.FINDER_PATTERNS=[Int32Array.from([1,8,4,1]),Int32Array.from([3,6,4,1]),Int32Array.from([3,4,6,1]),Int32Array.from([3,2,8,1]),Int32Array.from([2,6,5,1]),Int32Array.from([2,2,9,1])],se.WEIGHTS=[[1,3,9,27,81,32,96,77],[20,60,180,118,143,7,21,63],[189,145,13,39,117,140,209,205],[193,157,49,147,19,57,171,91],[62,186,136,197,169,85,44,132],[185,133,188,142,4,12,36,108],[113,128,173,97,80,29,87,50],[150,28,84,41,123,158,52,156],[46,138,203,187,139,206,196,166],[76,17,51,153,37,111,122,155],[43,129,176,106,107,110,119,146],[16,48,144,10,30,90,59,177],[109,116,137,200,178,112,125,164],[70,210,208,202,184,130,179,115],[134,191,151,31,93,68,204,190],[148,22,66,198,172,94,71,2],[6,18,54,162,64,192,154,40],[120,149,25,75,14,42,126,167],[79,26,78,23,69,207,199,175],[103,98,83,38,114,131,182,124],[161,61,183,127,170,88,53,159],[55,165,73,8,24,72,5,15],[45,135,194,160,58,174,100,89]],se.FINDER_PAT_A=0,se.FINDER_PAT_B=1,se.FINDER_PAT_C=2,se.FINDER_PAT_D=3,se.FINDER_PAT_E=4,se.FINDER_PAT_F=5,se.FINDER_PATTERN_SEQUENCES=[[se.FINDER_PAT_A,se.FINDER_PAT_A],[se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B],[se.FINDER_PAT_A,se.FINDER_PAT_C,se.FINDER_PAT_B,se.FINDER_PAT_D],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_C],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_D,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_D],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_E],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F]],se.MAX_PAIRS=11;class Fu extends yr{constructor(e,n,i){super(e,n),this.count=0,this.finderPattern=i}getFinderPattern(){return this.finderPattern}getCount(){return this.count}incrementCount(){this.count++}}class Et extends jt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,i){const s=this.decodePair(n,!1,e,i);Et.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,i);Et.addOrTally(this.possibleRightPairs,a),n.reverse();for(let l of this.possibleLeftPairs)if(l.getCount()>1){for(let d of this.possibleRightPairs)if(d.getCount()>1&&Et.checkChecksum(l,d))return Et.constructResult(l,d)}throw new $}static addOrTally(e,n){if(n==null)return;let i=!1;for(let s of e)if(s.getValue()===n.getValue()){s.incrementCount(),i=!0;break}i||e.push(n)}reset(){this.possibleLeftPairs.length=0,this.possibleRightPairs.length=0}static constructResult(e,n){let i=4537077*e.getValue()+n.getValue(),s=new String(i).toString(),a=new xe;for(let p=13-s.length;p>0;p--)a.append("0");a.append(s);let l=0;for(let p=0;p<13;p++){let y=a.charAt(p).charCodeAt(0)-48;l+=(p&1)===0?3*y:y}l=10-l%10,l===10&&(l=0),a.append(l.toString());let d=e.getFinderPattern().getResultPoints(),h=n.getFinderPattern().getResultPoints();return new Ee(a.toString(),null,0,[d[0],d[1],h[0],h[1]],Ce.RSS_14,new Date().getTime())}static checkChecksum(e,n){let i=(e.getChecksumPortion()+16*n.getChecksumPortion())%79,s=9*e.getFinderPattern().getValue()+n.getFinderPattern().getValue();return s>72&&s--,s>8&&s--,i===s}decodePair(e,n,i,s){try{let a=this.findFinderPattern(e,n),l=this.parseFoundFinderPattern(e,i,n,a),d=s==null?null:s.get(V.NEED_RESULT_POINT_CALLBACK);if(d!=null){let y=(a[0]+a[1])/2;n&&(y=e.getSize()-1-y),d.foundPossibleResultPoint(new ve(y,i))}let h=this.decodeDataCharacter(e,l,!0),p=this.decodeDataCharacter(e,l,!1);return new Fu(1597*h.getValue()+p.getValue(),h.getChecksumPortion()+4*p.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,i){let s=this.getDataCharacterCounters();for(let H=0;H<s.length;H++)s[H]=0;if(i)bt.recordPatternInReverse(e,n.getStartEnd()[0],s);else{bt.recordPattern(e,n.getStartEnd()[1]+1,s);for(let H=0,Y=s.length-1;H<Y;H++,Y--){let le=s[H];s[H]=s[Y],s[Y]=le}}let a=i?16:15,l=Ze.sum(new Int32Array(s))/a,d=this.getOddCounts(),h=this.getEvenCounts(),p=this.getOddRoundingErrors(),y=this.getEvenRoundingErrors();for(let H=0;H<s.length;H++){let Y=s[H]/l,le=Math.floor(Y+.5);le<1?le=1:le>8&&(le=8);let ce=Math.floor(H/2);(H&1)===0?(d[ce]=le,p[ce]=Y-le):(h[ce]=le,y[ce]=Y-le)}this.adjustOddEvenCounts(i,a);let E=0,I=0;for(let H=d.length-1;H>=0;H--)I*=9,I+=d[H],E+=d[H];let k=0,L=0;for(let H=h.length-1;H>=0;H--)k*=9,k+=h[H],L+=h[H];let F=I+3*k;if(i){if((E&1)!==0||E>12||E<4)throw new $;let H=(12-E)/2,Y=Et.OUTSIDE_ODD_WIDEST[H],le=9-Y,ce=Tn.getRSSvalue(d,Y,!1),ae=Tn.getRSSvalue(h,le,!0),We=Et.OUTSIDE_EVEN_TOTAL_SUBSET[H],Fe=Et.OUTSIDE_GSUM[H];return new yr(ce*We+ae+Fe,F)}else{if((L&1)!==0||L>10||L<4)throw new $;let H=(10-L)/2,Y=Et.INSIDE_ODD_WIDEST[H],le=9-Y,ce=Tn.getRSSvalue(d,Y,!0),ae=Tn.getRSSvalue(h,le,!1),We=Et.INSIDE_ODD_TOTAL_SUBSET[H],Fe=Et.INSIDE_GSUM[H];return new yr(ae*We+ce+Fe,F)}}findFinderPattern(e,n){let i=this.getDecodeFinderCounters();i[0]=0,i[1]=0,i[2]=0,i[3]=0;let s=e.getSize(),a=!1,l=0;for(;l<s&&(a=!e.get(l),n!==a);)l++;let d=0,h=l;for(let p=l;p<s;p++)if(e.get(p)!==a)i[d]++;else{if(d===3){if(jt.isFinderPattern(i))return[h,p];h+=i[0]+i[1],i[0]=i[2],i[1]=i[3],i[2]=0,i[3]=0,d--}else d++;i[d]=1,a=!a}throw new $}parseFoundFinderPattern(e,n,i,s){let a=e.get(s[0]),l=s[0]-1;for(;l>=0&&a!==e.get(l);)l--;l++;const d=s[0]-l,h=this.getDecodeFinderCounters(),p=new Int32Array(h.length);D.arraycopy(h,0,p,1,h.length-1),p[0]=d;const y=this.parseFinderValue(p,Et.FINDER_PATTERNS);let E=l,I=s[1];return i&&(E=e.getSize()-1-E,I=e.getSize()-1-I),new oi(y,[l,s[1]],E,I,n)}adjustOddEvenCounts(e,n){let i=Ze.sum(new Int32Array(this.getOddCounts())),s=Ze.sum(new Int32Array(this.getEvenCounts())),a=!1,l=!1,d=!1,h=!1;e?(i>12?l=!0:i<4&&(a=!0),s>12?h=!0:s<4&&(d=!0)):(i>11?l=!0:i<5&&(a=!0),s>10?h=!0:s<4&&(d=!0));let p=i+s-n,y=(i&1)===(e?1:0),E=(s&1)===1;if(p===1)if(y){if(E)throw new $;l=!0}else{if(!E)throw new $;h=!0}else if(p===-1)if(y){if(E)throw new $;a=!0}else{if(!E)throw new $;d=!0}else if(p===0){if(y){if(!E)throw new $;i<s?(a=!0,h=!0):(l=!0,d=!0)}else if(E)throw new $}else throw new $;if(a){if(l)throw new $;jt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&jt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),d){if(h)throw new $;jt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&jt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}Et.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],Et.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],Et.OUTSIDE_GSUM=[0,161,961,2015,2715],Et.INSIDE_GSUM=[0,336,1036,1516],Et.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],Et.INSIDE_ODD_WIDEST=[2,4,6,8],Et.FINDER_PATTERNS=[Int32Array.from([3,8,2,1]),Int32Array.from([3,5,5,1]),Int32Array.from([3,3,7,1]),Int32Array.from([3,1,9,1]),Int32Array.from([2,7,4,1]),Int32Array.from([2,5,6,1]),Int32Array.from([2,3,8,1]),Int32Array.from([1,5,7,1]),Int32Array.from([1,3,9,1])];class vr extends bt{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const i=e?e.get(V.POSSIBLE_FORMATS):null,s=e&&e.get(V.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;i?((i.includes(Ce.EAN_13)||i.includes(Ce.UPC_A)||i.includes(Ce.EAN_8)||i.includes(Ce.UPC_E))&&this.readers.push(new Fi(e)),i.includes(Ce.CODE_39)&&this.readers.push(new Nt(s)),i.includes(Ce.CODE_128)&&this.readers.push(new he),i.includes(Ce.ITF)&&this.readers.push(new nt),i.includes(Ce.RSS_14)&&this.readers.push(new Et),i.includes(Ce.RSS_EXPANDED)&&this.readers.push(new se(this.verbose))):(this.readers.push(new Fi(e)),this.readers.push(new Nt),this.readers.push(new Fi(e)),this.readers.push(new he),this.readers.push(new nt),this.readers.push(new Et),this.readers.push(new se(this.verbose)))}decodeRow(e,n,i){for(let s=0;s<this.readers.length;s++)try{return this.readers[s].decodeRow(e,n,i)}catch{}throw new $}reset(){this.readers.forEach(e=>e.reset())}}class Uu extends vt{constructor(e=500,n){super(new vr(n),e,n)}}class et{constructor(e,n,i){this.ecCodewords=e,this.ecBlocks=[n],i&&this.ecBlocks.push(i)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class Ke{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class je{constructor(e,n,i,s,a,l){this.versionNumber=e,this.symbolSizeRows=n,this.symbolSizeColumns=i,this.dataRegionSizeRows=s,this.dataRegionSizeColumns=a,this.ecBlocks=l;let d=0;const h=l.getECCodewords(),p=l.getECBlocks();for(let y of p)d+=y.getCount()*(y.getDataCodewords()+h);this.totalCodewords=d}getVersionNumber(){return this.versionNumber}getSymbolSizeRows(){return this.symbolSizeRows}getSymbolSizeColumns(){return this.symbolSizeColumns}getDataRegionSizeRows(){return this.dataRegionSizeRows}getDataRegionSizeColumns(){return this.dataRegionSizeColumns}getTotalCodewords(){return this.totalCodewords}getECBlocks(){return this.ecBlocks}static getVersionForDimensions(e,n){if((e&1)!==0||(n&1)!==0)throw new U;for(let i of je.VERSIONS)if(i.symbolSizeRows===e&&i.symbolSizeColumns===n)return i;throw new U}toString(){return""+this.versionNumber}static buildVersions(){return[new je(1,10,10,8,8,new et(5,new Ke(1,3))),new je(2,12,12,10,10,new et(7,new Ke(1,5))),new je(3,14,14,12,12,new et(10,new Ke(1,8))),new je(4,16,16,14,14,new et(12,new Ke(1,12))),new je(5,18,18,16,16,new et(14,new Ke(1,18))),new je(6,20,20,18,18,new et(18,new Ke(1,22))),new je(7,22,22,20,20,new et(20,new Ke(1,30))),new je(8,24,24,22,22,new et(24,new Ke(1,36))),new je(9,26,26,24,24,new et(28,new Ke(1,44))),new je(10,32,32,14,14,new et(36,new Ke(1,62))),new je(11,36,36,16,16,new et(42,new Ke(1,86))),new je(12,40,40,18,18,new et(48,new Ke(1,114))),new je(13,44,44,20,20,new et(56,new Ke(1,144))),new je(14,48,48,22,22,new et(68,new Ke(1,174))),new je(15,52,52,24,24,new et(42,new Ke(2,102))),new je(16,64,64,14,14,new et(56,new Ke(2,140))),new je(17,72,72,16,16,new et(36,new Ke(4,92))),new je(18,80,80,18,18,new et(48,new Ke(4,114))),new je(19,88,88,20,20,new et(56,new Ke(4,144))),new je(20,96,96,22,22,new et(68,new Ke(4,174))),new je(21,104,104,24,24,new et(56,new Ke(6,136))),new je(22,120,120,18,18,new et(68,new Ke(6,175))),new je(23,132,132,20,20,new et(62,new Ke(8,163))),new je(24,144,144,22,22,new et(62,new Ke(8,156),new Ke(2,155))),new je(25,8,18,6,16,new et(7,new Ke(1,5))),new je(26,8,32,6,14,new et(11,new Ke(1,10))),new je(27,12,26,10,24,new et(14,new Ke(1,16))),new je(28,12,36,10,16,new et(18,new Ke(1,22))),new je(29,16,36,14,16,new et(24,new Ke(1,32))),new je(30,16,48,14,22,new et(28,new Ke(1,49)))]}}je.VERSIONS=je.buildVersions();class Zi{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new U;this.version=Zi.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new Me(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),i=e.getWidth();return je.getVersionForDimensions(n,i)}readCodewords(){const e=new Int8Array(this.version.getTotalCodewords());let n=0,i=4,s=0;const a=this.mappingBitMatrix.getHeight(),l=this.mappingBitMatrix.getWidth();let d=!1,h=!1,p=!1,y=!1;do if(i===a&&s===0&&!d)e[n++]=this.readCorner1(a,l)&255,i-=2,s+=2,d=!0;else if(i===a-2&&s===0&&(l&3)!==0&&!h)e[n++]=this.readCorner2(a,l)&255,i-=2,s+=2,h=!0;else if(i===a+4&&s===2&&(l&7)===0&&!p)e[n++]=this.readCorner3(a,l)&255,i-=2,s+=2,p=!0;else if(i===a-2&&s===0&&(l&7)===4&&!y)e[n++]=this.readCorner4(a,l)&255,i-=2,s+=2,y=!0;else{do i<a&&s>=0&&!this.readMappingMatrix.get(s,i)&&(e[n++]=this.readUtah(i,s,a,l)&255),i-=2,s+=2;while(i>=0&&s<l);i+=1,s+=3;do i>=0&&s<l&&!this.readMappingMatrix.get(s,i)&&(e[n++]=this.readUtah(i,s,a,l)&255),i+=2,s-=2;while(i<a&&s>=0);i+=3,s+=1}while(i<a||s<l);if(n!==this.version.getTotalCodewords())throw new U;return e}readModule(e,n,i,s){return e<0&&(e+=i,n+=4-(i+4&7)),n<0&&(n+=s,e+=4-(s+4&7)),this.readMappingMatrix.set(n,e),this.mappingBitMatrix.get(n,e)}readUtah(e,n,i,s){let a=0;return this.readModule(e-2,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e-2,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n,i,s)&&(a|=1),a<<=1,this.readModule(e,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e,n,i,s)&&(a|=1),a}readCorner1(e,n){let i=0;return this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,1,e,n)&&(i|=1),i<<=1,this.readModule(e-1,2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(2,n-1,e,n)&&(i|=1),i<<=1,this.readModule(3,n-1,e,n)&&(i|=1),i}readCorner2(e,n){let i=0;return this.readModule(e-3,0,e,n)&&(i|=1),i<<=1,this.readModule(e-2,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(0,n-4,e,n)&&(i|=1),i<<=1,this.readModule(0,n-3,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i}readCorner3(e,n){let i=0;return this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(0,n-3,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-3,e,n)&&(i|=1),i<<=1,this.readModule(1,n-2,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i}readCorner4(e,n){let i=0;return this.readModule(e-3,0,e,n)&&(i|=1),i<<=1,this.readModule(e-2,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(2,n-1,e,n)&&(i|=1),i<<=1,this.readModule(3,n-1,e,n)&&(i|=1),i}extractDataRegion(e){const n=this.version.getSymbolSizeRows(),i=this.version.getSymbolSizeColumns();if(e.getHeight()!==n)throw new v("Dimension of bitMatrix must match the version size");const s=this.version.getDataRegionSizeRows(),a=this.version.getDataRegionSizeColumns(),l=n/s|0,d=i/a|0,h=l*s,p=d*a,y=new Me(p,h);for(let E=0;E<l;++E){const I=E*s;for(let k=0;k<d;++k){const L=k*a;for(let F=0;F<s;++F){const H=E*(s+2)+1+F,Y=I+F;for(let le=0;le<a;++le){const ce=k*(a+2)+1+le;if(e.get(ce,H)){const ae=L+le;y.set(ae,Y)}}}}}return y}}class $i{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n){const i=n.getECBlocks();let s=0;const a=i.getECBlocks();for(let F of a)s+=F.getCount();const l=new Array(s);let d=0;for(let F of a)for(let H=0;H<F.getCount();H++){const Y=F.getDataCodewords(),le=i.getECCodewords()+Y;l[d++]=new $i(Y,new Uint8Array(le))}const p=l[0].codewords.length-i.getECCodewords(),y=p-1;let E=0;for(let F=0;F<y;F++)for(let H=0;H<d;H++)l[H].codewords[F]=e[E++];const I=n.getVersionNumber()===24,k=I?8:d;for(let F=0;F<k;F++)l[F].codewords[p-1]=e[E++];const L=l[0].codewords.length;for(let F=p;F<L;F++)for(let H=0;H<d;H++){const Y=I?(H+8)%d:H,le=I&&Y>7?F-1:F;l[Y].codewords[le]=e[E++]}if(E!==e.length)throw new v;return l}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}class Hi{constructor(e){this.bytes=e,this.byteOffset=0,this.bitOffset=0}getBitOffset(){return this.bitOffset}getByteOffset(){return this.byteOffset}readBits(e){if(e<1||e>32||e>this.available())throw new v(""+e);let n=0,i=this.bitOffset,s=this.byteOffset;const a=this.bytes;if(i>0){const l=8-i,d=e<l?e:l,h=l-d,p=255>>8-d<<h;n=(a[s]&p)>>h,e-=d,i+=d,i===8&&(i=0,s++)}if(e>0){for(;e>=8;)n=n<<8|a[s]&255,s++,e-=8;if(e>0){const l=8-e,d=255>>l<<l;n=n<<e|(a[s]&d)>>l,i+=e}}return this.bitOffset=i,this.byteOffset=s,n}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var Mt;(function(b){b[b.PAD_ENCODE=0]="PAD_ENCODE",b[b.ASCII_ENCODE=1]="ASCII_ENCODE",b[b.C40_ENCODE=2]="C40_ENCODE",b[b.TEXT_ENCODE=3]="TEXT_ENCODE",b[b.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",b[b.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",b[b.BASE256_ENCODE=6]="BASE256_ENCODE"})(Mt||(Mt={}));class Gn{static decode(e){const n=new Hi(e),i=new xe,s=new xe,a=new Array;let l=Mt.ASCII_ENCODE;do if(l===Mt.ASCII_ENCODE)l=this.decodeAsciiSegment(n,i,s);else{switch(l){case Mt.C40_ENCODE:this.decodeC40Segment(n,i);break;case Mt.TEXT_ENCODE:this.decodeTextSegment(n,i);break;case Mt.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,i);break;case Mt.EDIFACT_ENCODE:this.decodeEdifactSegment(n,i);break;case Mt.BASE256_ENCODE:this.decodeBase256Segment(n,i,a);break;default:throw new U}l=Mt.ASCII_ENCODE}while(l!==Mt.PAD_ENCODE&&n.available()>0);return s.length()>0&&i.append(s.toString()),new Ht(e,i.toString(),a.length===0?null:a,null)}static decodeAsciiSegment(e,n,i){let s=!1;do{let a=e.readBits(8);if(a===0)throw new U;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Mt.ASCII_ENCODE;if(a===129)return Mt.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Mt.C40_ENCODE;case 231:return Mt.BASE256_ENCODE;case 232:n.append("");break;case 233:case 234:break;case 235:s=!0;break;case 236:n.append("[)>05"),i.insert(0,"");break;case 237:n.append("[)>06"),i.insert(0,"");break;case 238:return Mt.ANSIX12_ENCODE;case 239:return Mt.TEXT_ENCODE;case 240:return Mt.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new U;break}}while(e.available()>0);return Mt.ASCII_ENCODE}static decodeC40Segment(e,n){let i=!1;const s=[];let a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let d=0;d<3;d++){const h=s[d];switch(a){case 0:if(h<3)a=h+1;else if(h<this.C40_BASIC_SET_CHARS.length){const p=this.C40_BASIC_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else throw new U;break;case 1:i?(n.append(String.fromCharCode(h+128)),i=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.C40_SHIFT2_SET_CHARS.length){const p=this.C40_SHIFT2_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:i=!0;break;default:throw new U}a=0;break;case 3:i?(n.append(String.fromCharCode(h+224)),i=!1):n.append(String.fromCharCode(h+96)),a=0;break;default:throw new U}}}while(e.available()>0)}static decodeTextSegment(e,n){let i=!1,s=[],a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let d=0;d<3;d++){const h=s[d];switch(a){case 0:if(h<3)a=h+1;else if(h<this.TEXT_BASIC_SET_CHARS.length){const p=this.TEXT_BASIC_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else throw new U;break;case 1:i?(n.append(String.fromCharCode(h+128)),i=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.TEXT_SHIFT2_SET_CHARS.length){const p=this.TEXT_SHIFT2_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:i=!0;break;default:throw new U}a=0;break;case 3:if(h<this.TEXT_SHIFT3_SET_CHARS.length){const p=this.TEXT_SHIFT3_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p),a=0}else throw new U;break;default:throw new U}}}while(e.available()>0)}static decodeAnsiX12Segment(e,n){const i=[];do{if(e.available()===8)return;const s=e.readBits(8);if(s===254)return;this.parseTwoBytes(s,e.readBits(8),i);for(let a=0;a<3;a++){const l=i[a];switch(l){case 0:n.append("\r");break;case 1:n.append("*");break;case 2:n.append(">");break;case 3:n.append(" ");break;default:if(l<14)n.append(String.fromCharCode(l+44));else if(l<40)n.append(String.fromCharCode(l+51));else throw new U;break}}}while(e.available()>0)}static parseTwoBytes(e,n,i){let s=(e<<8)+n-1,a=Math.floor(s/1600);i[0]=a,s-=a*1600,a=Math.floor(s/40),i[1]=a,i[2]=s-a*40}static decodeEdifactSegment(e,n){do{if(e.available()<=16)return;for(let i=0;i<4;i++){let s=e.readBits(6);if(s===31){const a=8-e.getBitOffset();a!==8&&e.readBits(a);return}(s&32)===0&&(s|=64),n.append(String.fromCharCode(s))}}while(e.available()>0)}static decodeBase256Segment(e,n,i){let s=1+e.getByteOffset();const a=this.unrandomize255State(e.readBits(8),s++);let l;if(a===0?l=e.available()/8|0:a<250?l=a:l=250*(a-249)+this.unrandomize255State(e.readBits(8),s++),l<0)throw new U;const d=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new U;d[h]=this.unrandomize255State(e.readBits(8),s++)}i.push(d);try{n.append(ye.decode(d,re.ISO88591))}catch(h){throw new Wt("Platform does not support required encoding: "+h.message)}}static unrandomize255State(e,n){const i=149*n%255+1,s=e-i;return s>=0?s:s+256}}Gn.C40_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],Gn.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],Gn.TEXT_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],Gn.TEXT_SHIFT2_SET_CHARS=Gn.C40_SHIFT2_SET_CHARS,Gn.TEXT_SHIFT3_SET_CHARS=["`","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","{","|","}","~",""];class zu{constructor(){this.rsDecoder=new In(be.DATA_MATRIX_FIELD_256)}decode(e){const n=new Zi(e),i=n.getVersion(),s=n.readCodewords(),a=$i.getDataBlocks(s,i);let l=0;for(let p of a)l+=p.getNumDataCodewords();const d=new Uint8Array(l),h=a.length;for(let p=0;p<h;p++){const y=a[p],E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let k=0;k<I;k++)d[k*h+p]=E[k]}return Gn.decode(d)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class Ot{constructor(e){this.image=e,this.rectangleDetector=new Jt(this.image)}detect(){const e=this.rectangleDetector.detect();let n=this.detectSolid1(e);if(n=this.detectSolid2(n),n[3]=this.correctTopRight(n),!n[3])throw new $;n=this.shiftToModuleCenter(n);const i=n[0],s=n[1],a=n[2],l=n[3];let d=this.transitionsBetween(i,l)+1,h=this.transitionsBetween(a,l)+1;(d&1)===1&&(d+=1),(h&1)===1&&(h+=1),4*d<7*h&&4*h<7*d&&(d=h=Math.max(d,h));let p=Ot.sampleGrid(this.image,i,s,a,l,d,h);return new Bn(p,[i,s,a,l])}static shiftPoint(e,n,i){let s=(n.getX()-e.getX())/(i+1),a=(n.getY()-e.getY())/(i+1);return new ve(e.getX()+s,e.getY()+a)}static moveAway(e,n,i){let s=e.getX(),a=e.getY();return s<n?s-=1:s+=1,a<i?a-=1:a+=1,new ve(s,a)}detectSolid1(e){let n=e[0],i=e[1],s=e[3],a=e[2],l=this.transitionsBetween(n,i),d=this.transitionsBetween(i,s),h=this.transitionsBetween(s,a),p=this.transitionsBetween(a,n),y=l,E=[a,n,i,s];return y>d&&(y=d,E[0]=n,E[1]=i,E[2]=s,E[3]=a),y>h&&(y=h,E[0]=i,E[1]=s,E[2]=a,E[3]=n),y>p&&(E[0]=s,E[1]=a,E[2]=n,E[3]=i),E}detectSolid2(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=Ot.shiftPoint(i,s,(l+1)*4),h=Ot.shiftPoint(s,i,(l+1)*4),p=this.transitionsBetween(d,n),y=this.transitionsBetween(h,a);return p<y?(e[0]=n,e[1]=i,e[2]=s,e[3]=a):(e[0]=i,e[1]=s,e[2]=a,e[3]=n),e}correctTopRight(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=this.transitionsBetween(i,a),h=Ot.shiftPoint(n,i,(d+1)*4),p=Ot.shiftPoint(s,i,(l+1)*4);l=this.transitionsBetween(h,a),d=this.transitionsBetween(p,a);let y=new ve(a.getX()+(s.getX()-i.getX())/(l+1),a.getY()+(s.getY()-i.getY())/(l+1)),E=new ve(a.getX()+(n.getX()-i.getX())/(d+1),a.getY()+(n.getY()-i.getY())/(d+1));if(!this.isValid(y))return this.isValid(E)?E:null;if(!this.isValid(E))return y;let I=this.transitionsBetween(h,y)+this.transitionsBetween(p,y),k=this.transitionsBetween(h,E)+this.transitionsBetween(p,E);return I>k?y:E}shiftToModuleCenter(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a)+1,d=this.transitionsBetween(s,a)+1,h=Ot.shiftPoint(n,i,d*4),p=Ot.shiftPoint(s,i,l*4);l=this.transitionsBetween(h,a)+1,d=this.transitionsBetween(p,a)+1,(l&1)===1&&(l+=1),(d&1)===1&&(d+=1);let y=(n.getX()+i.getX()+s.getX()+a.getX())/4,E=(n.getY()+i.getY()+s.getY()+a.getY())/4;n=Ot.moveAway(n,y,E),i=Ot.moveAway(i,y,E),s=Ot.moveAway(s,y,E),a=Ot.moveAway(a,y,E);let I,k;return h=Ot.shiftPoint(n,i,d*4),h=Ot.shiftPoint(h,a,l*4),I=Ot.shiftPoint(i,n,d*4),I=Ot.shiftPoint(I,s,l*4),p=Ot.shiftPoint(s,a,d*4),p=Ot.shiftPoint(p,i,l*4),k=Ot.shiftPoint(a,s,d*4),k=Ot.shiftPoint(k,n,l*4),[h,I,p,k]}isValid(e){return e.getX()>=0&&e.getX()<this.image.getWidth()&&e.getY()>0&&e.getY()<this.image.getHeight()}static sampleGrid(e,n,i,s,a,l,d){return R.getInstance().sampleGrid(e,l,d,.5,.5,l-.5,.5,l-.5,d-.5,.5,d-.5,n.getX(),n.getY(),a.getX(),a.getY(),s.getX(),s.getY(),i.getX(),i.getY())}transitionsBetween(e,n){let i=Math.trunc(e.getX()),s=Math.trunc(e.getY()),a=Math.trunc(n.getX()),l=Math.trunc(n.getY()),d=Math.abs(l-s)>Math.abs(a-i);if(d){let F=i;i=s,s=F,F=a,a=l,l=F}let h=Math.abs(a-i),p=Math.abs(l-s),y=-h/2,E=s<l?1:-1,I=i<a?1:-1,k=0,L=this.image.get(d?s:i,d?i:s);for(let F=i,H=s;F!==a;F+=I){let Y=this.image.get(d?H:F,d?F:H);if(Y!==L&&(k++,L=Y),y+=p,y>0){if(H===l)break;H+=E,y-=h}}return k}}class Xn{constructor(){this.decoder=new zu}decode(e,n=null){let i,s;if(n!=null&&n.has(V.PURE_BARCODE)){const p=Xn.extractPureBits(e.getBlackMatrix());i=this.decoder.decode(p),s=Xn.NO_POINTS}else{const p=new Ot(e.getBlackMatrix()).detect();i=this.decoder.decode(p.getBits()),s=p.getPoints()}const a=i.getRawBytes(),l=new Ee(i.getText(),a,8*a.length,s,Ce.DATA_MATRIX,D.currentTimeMillis()),d=i.getByteSegments();d!=null&&l.putMetadata(Ue.BYTE_SEGMENTS,d);const h=i.getECLevel();return h!=null&&l.putMetadata(Ue.ERROR_CORRECTION_LEVEL,h),l}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n==null||i==null)throw new $;const s=this.moduleSize(n,e);let a=n[1];const l=i[1];let d=n[0];const p=(i[0]-d+1)/s,y=(l-a+1)/s;if(p<=0||y<=0)throw new $;const E=s/2;a+=E,d+=E;const I=new Me(p,y);for(let k=0;k<y;k++){const L=a+k*s;for(let F=0;F<p;F++)e.get(d+F*s,L)&&I.set(F,k)}return I}static moduleSize(e,n){const i=n.getWidth();let s=e[0];const a=e[1];for(;s<i&&n.get(s,a);)s++;if(s===i)throw new $;const l=s-e[0];if(l===0)throw new $;return l}}Xn.NO_POINTS=[];class Vu extends vt{constructor(e=500){super(new Xn,e)}}var Cr;(function(b){b[b.L=0]="L",b[b.M=1]="M",b[b.Q=2]="Q",b[b.H=3]="H"})(Cr||(Cr={}));class ct{constructor(e,n,i){this.value=e,this.stringValue=n,this.bits=i,ct.FOR_BITS.set(i,this),ct.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return ct.L;case"M":return ct.M;case"Q":return ct.Q;case"H":return ct.H;default:throw new A(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof ct))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=ct.FOR_BITS.size)throw new v;return ct.FOR_BITS.get(e)}}ct.FOR_BITS=new Map,ct.FOR_VALUE=new Map,ct.L=new ct(Cr.L,"L",1),ct.M=new ct(Cr.M,"M",0),ct.Q=new ct(Cr.Q,"Q",3),ct.H=new ct(Cr.H,"H",2);class Gt{constructor(e){this.errorCorrectionLevel=ct.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return z.bitCount(e^n)}static decodeFormatInformation(e,n){const i=Gt.doDecodeFormatInformation(e,n);return i!==null?i:Gt.doDecodeFormatInformation(e^Gt.FORMAT_INFO_MASK_QR,n^Gt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let i=Number.MAX_SAFE_INTEGER,s=0;for(const a of Gt.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new Gt(a[1]);let d=Gt.numBitsDiffering(e,l);d<i&&(s=a[1],i=d),e!==n&&(d=Gt.numBitsDiffering(n,l),d<i&&(s=a[1],i=d))}return i<=3?new Gt(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof Gt))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}Gt.FORMAT_INFO_MASK_QR=21522,Gt.FORMAT_INFO_DECODE_LOOKUP=[Int32Array.from([21522,0]),Int32Array.from([20773,1]),Int32Array.from([24188,2]),Int32Array.from([23371,3]),Int32Array.from([17913,4]),Int32Array.from([16590,5]),Int32Array.from([20375,6]),Int32Array.from([19104,7]),Int32Array.from([30660,8]),Int32Array.from([29427,9]),Int32Array.from([32170,10]),Int32Array.from([30877,11]),Int32Array.from([26159,12]),Int32Array.from([25368,13]),Int32Array.from([27713,14]),Int32Array.from([26998,15]),Int32Array.from([5769,16]),Int32Array.from([5054,17]),Int32Array.from([7399,18]),Int32Array.from([6608,19]),Int32Array.from([1890,20]),Int32Array.from([597,21]),Int32Array.from([3340,22]),Int32Array.from([2107,23]),Int32Array.from([13663,24]),Int32Array.from([12392,25]),Int32Array.from([16177,26]),Int32Array.from([14854,27]),Int32Array.from([9396,28]),Int32Array.from([8579,29]),Int32Array.from([11994,30]),Int32Array.from([11245,31])];class W{constructor(e,...n){this.ecCodewordsPerBlock=e,this.ecBlocks=n}getECCodewordsPerBlock(){return this.ecCodewordsPerBlock}getNumBlocks(){let e=0;const n=this.ecBlocks;for(const i of n)e+=i.getCount();return e}getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks()}getECBlocks(){return this.ecBlocks}}class N{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Ie{constructor(e,n,...i){this.versionNumber=e,this.alignmentPatternCenters=n,this.ecBlocks=i;let s=0;const a=i[0].getECCodewordsPerBlock(),l=i[0].getECBlocks();for(const d of l)s+=d.getCount()*(d.getDataCodewords()+a);this.totalCodewords=s}getVersionNumber(){return this.versionNumber}getAlignmentPatternCenters(){return this.alignmentPatternCenters}getTotalCodewords(){return this.totalCodewords}getDimensionForVersion(){return 17+4*this.versionNumber}getECBlocksForLevel(e){return this.ecBlocks[e.getValue()]}static getProvisionalVersionForDimension(e){if(e%4!==1)throw new U;try{return this.getVersionForNumber((e-17)/4)}catch{throw new U}}static getVersionForNumber(e){if(e<1||e>40)throw new v;return Ie.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,i=0;for(let s=0;s<Ie.VERSION_DECODE_INFO.length;s++){const a=Ie.VERSION_DECODE_INFO[s];if(a===e)return Ie.getVersionForNumber(s+7);const l=Gt.numBitsDiffering(e,a);l<n&&(i=s+7,n=l)}return n<=3?Ie.getVersionForNumber(i):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new Me(e);n.setRegion(0,0,9,9),n.setRegion(e-8,0,8,9),n.setRegion(0,e-8,9,8);const i=this.alignmentPatternCenters.length;for(let s=0;s<i;s++){const a=this.alignmentPatternCenters[s]-2;for(let l=0;l<i;l++)s===0&&(l===0||l===i-1)||s===i-1&&l===0||n.setRegion(this.alignmentPatternCenters[l]-2,a,5,5)}return n.setRegion(6,9,1,e-17),n.setRegion(9,6,e-17,1),this.versionNumber>6&&(n.setRegion(e-11,0,3,6),n.setRegion(0,e-11,6,3)),n}toString(){return""+this.versionNumber}}Ie.VERSION_DECODE_INFO=Int32Array.from([31892,34236,39577,42195,48118,51042,55367,58893,63784,68472,70749,76311,79154,84390,87683,92361,96236,102084,102881,110507,110734,117786,119615,126325,127568,133589,136944,141498,145311,150283,152622,158308,161089,167017]),Ie.VERSIONS=[new Ie(1,new Int32Array(0),new W(7,new N(1,19)),new W(10,new N(1,16)),new W(13,new N(1,13)),new W(17,new N(1,9))),new Ie(2,Int32Array.from([6,18]),new W(10,new N(1,34)),new W(16,new N(1,28)),new W(22,new N(1,22)),new W(28,new N(1,16))),new Ie(3,Int32Array.from([6,22]),new W(15,new N(1,55)),new W(26,new N(1,44)),new W(18,new N(2,17)),new W(22,new N(2,13))),new Ie(4,Int32Array.from([6,26]),new W(20,new N(1,80)),new W(18,new N(2,32)),new W(26,new N(2,24)),new W(16,new N(4,9))),new Ie(5,Int32Array.from([6,30]),new W(26,new N(1,108)),new W(24,new N(2,43)),new W(18,new N(2,15),new N(2,16)),new W(22,new N(2,11),new N(2,12))),new Ie(6,Int32Array.from([6,34]),new W(18,new N(2,68)),new W(16,new N(4,27)),new W(24,new N(4,19)),new W(28,new N(4,15))),new Ie(7,Int32Array.from([6,22,38]),new W(20,new N(2,78)),new W(18,new N(4,31)),new W(18,new N(2,14),new N(4,15)),new W(26,new N(4,13),new N(1,14))),new Ie(8,Int32Array.from([6,24,42]),new W(24,new N(2,97)),new W(22,new N(2,38),new N(2,39)),new W(22,new N(4,18),new N(2,19)),new W(26,new N(4,14),new N(2,15))),new Ie(9,Int32Array.from([6,26,46]),new W(30,new N(2,116)),new W(22,new N(3,36),new N(2,37)),new W(20,new N(4,16),new N(4,17)),new W(24,new N(4,12),new N(4,13))),new Ie(10,Int32Array.from([6,28,50]),new W(18,new N(2,68),new N(2,69)),new W(26,new N(4,43),new N(1,44)),new W(24,new N(6,19),new N(2,20)),new W(28,new N(6,15),new N(2,16))),new Ie(11,Int32Array.from([6,30,54]),new W(20,new N(4,81)),new W(30,new N(1,50),new N(4,51)),new W(28,new N(4,22),new N(4,23)),new W(24,new N(3,12),new N(8,13))),new Ie(12,Int32Array.from([6,32,58]),new W(24,new N(2,92),new N(2,93)),new W(22,new N(6,36),new N(2,37)),new W(26,new N(4,20),new N(6,21)),new W(28,new N(7,14),new N(4,15))),new Ie(13,Int32Array.from([6,34,62]),new W(26,new N(4,107)),new W(22,new N(8,37),new N(1,38)),new W(24,new N(8,20),new N(4,21)),new W(22,new N(12,11),new N(4,12))),new Ie(14,Int32Array.from([6,26,46,66]),new W(30,new N(3,115),new N(1,116)),new W(24,new N(4,40),new N(5,41)),new W(20,new N(11,16),new N(5,17)),new W(24,new N(11,12),new N(5,13))),new Ie(15,Int32Array.from([6,26,48,70]),new W(22,new N(5,87),new N(1,88)),new W(24,new N(5,41),new N(5,42)),new W(30,new N(5,24),new N(7,25)),new W(24,new N(11,12),new N(7,13))),new Ie(16,Int32Array.from([6,26,50,74]),new W(24,new N(5,98),new N(1,99)),new W(28,new N(7,45),new N(3,46)),new W(24,new N(15,19),new N(2,20)),new W(30,new N(3,15),new N(13,16))),new Ie(17,Int32Array.from([6,30,54,78]),new W(28,new N(1,107),new N(5,108)),new W(28,new N(10,46),new N(1,47)),new W(28,new N(1,22),new N(15,23)),new W(28,new N(2,14),new N(17,15))),new Ie(18,Int32Array.from([6,30,56,82]),new W(30,new N(5,120),new N(1,121)),new W(26,new N(9,43),new N(4,44)),new W(28,new N(17,22),new N(1,23)),new W(28,new N(2,14),new N(19,15))),new Ie(19,Int32Array.from([6,30,58,86]),new W(28,new N(3,113),new N(4,114)),new W(26,new N(3,44),new N(11,45)),new W(26,new N(17,21),new N(4,22)),new W(26,new N(9,13),new N(16,14))),new Ie(20,Int32Array.from([6,34,62,90]),new W(28,new N(3,107),new N(5,108)),new W(26,new N(3,41),new N(13,42)),new W(30,new N(15,24),new N(5,25)),new W(28,new N(15,15),new N(10,16))),new Ie(21,Int32Array.from([6,28,50,72,94]),new W(28,new N(4,116),new N(4,117)),new W(26,new N(17,42)),new W(28,new N(17,22),new N(6,23)),new W(30,new N(19,16),new N(6,17))),new Ie(22,Int32Array.from([6,26,50,74,98]),new W(28,new N(2,111),new N(7,112)),new W(28,new N(17,46)),new W(30,new N(7,24),new N(16,25)),new W(24,new N(34,13))),new Ie(23,Int32Array.from([6,30,54,78,102]),new W(30,new N(4,121),new N(5,122)),new W(28,new N(4,47),new N(14,48)),new W(30,new N(11,24),new N(14,25)),new W(30,new N(16,15),new N(14,16))),new Ie(24,Int32Array.from([6,28,54,80,106]),new W(30,new N(6,117),new N(4,118)),new W(28,new N(6,45),new N(14,46)),new W(30,new N(11,24),new N(16,25)),new W(30,new N(30,16),new N(2,17))),new Ie(25,Int32Array.from([6,32,58,84,110]),new W(26,new N(8,106),new N(4,107)),new W(28,new N(8,47),new N(13,48)),new W(30,new N(7,24),new N(22,25)),new W(30,new N(22,15),new N(13,16))),new Ie(26,Int32Array.from([6,30,58,86,114]),new W(28,new N(10,114),new N(2,115)),new W(28,new N(19,46),new N(4,47)),new W(28,new N(28,22),new N(6,23)),new W(30,new N(33,16),new N(4,17))),new Ie(27,Int32Array.from([6,34,62,90,118]),new W(30,new N(8,122),new N(4,123)),new W(28,new N(22,45),new N(3,46)),new W(30,new N(8,23),new N(26,24)),new W(30,new N(12,15),new N(28,16))),new Ie(28,Int32Array.from([6,26,50,74,98,122]),new W(30,new N(3,117),new N(10,118)),new W(28,new N(3,45),new N(23,46)),new W(30,new N(4,24),new N(31,25)),new W(30,new N(11,15),new N(31,16))),new Ie(29,Int32Array.from([6,30,54,78,102,126]),new W(30,new N(7,116),new N(7,117)),new W(28,new N(21,45),new N(7,46)),new W(30,new N(1,23),new N(37,24)),new W(30,new N(19,15),new N(26,16))),new Ie(30,Int32Array.from([6,26,52,78,104,130]),new W(30,new N(5,115),new N(10,116)),new W(28,new N(19,47),new N(10,48)),new W(30,new N(15,24),new N(25,25)),new W(30,new N(23,15),new N(25,16))),new Ie(31,Int32Array.from([6,30,56,82,108,134]),new W(30,new N(13,115),new N(3,116)),new W(28,new N(2,46),new N(29,47)),new W(30,new N(42,24),new N(1,25)),new W(30,new N(23,15),new N(28,16))),new Ie(32,Int32Array.from([6,34,60,86,112,138]),new W(30,new N(17,115)),new W(28,new N(10,46),new N(23,47)),new W(30,new N(10,24),new N(35,25)),new W(30,new N(19,15),new N(35,16))),new Ie(33,Int32Array.from([6,30,58,86,114,142]),new W(30,new N(17,115),new N(1,116)),new W(28,new N(14,46),new N(21,47)),new W(30,new N(29,24),new N(19,25)),new W(30,new N(11,15),new N(46,16))),new Ie(34,Int32Array.from([6,34,62,90,118,146]),new W(30,new N(13,115),new N(6,116)),new W(28,new N(14,46),new N(23,47)),new W(30,new N(44,24),new N(7,25)),new W(30,new N(59,16),new N(1,17))),new Ie(35,Int32Array.from([6,30,54,78,102,126,150]),new W(30,new N(12,121),new N(7,122)),new W(28,new N(12,47),new N(26,48)),new W(30,new N(39,24),new N(14,25)),new W(30,new N(22,15),new N(41,16))),new Ie(36,Int32Array.from([6,24,50,76,102,128,154]),new W(30,new N(6,121),new N(14,122)),new W(28,new N(6,47),new N(34,48)),new W(30,new N(46,24),new N(10,25)),new W(30,new N(2,15),new N(64,16))),new Ie(37,Int32Array.from([6,28,54,80,106,132,158]),new W(30,new N(17,122),new N(4,123)),new W(28,new N(29,46),new N(14,47)),new W(30,new N(49,24),new N(10,25)),new W(30,new N(24,15),new N(46,16))),new Ie(38,Int32Array.from([6,32,58,84,110,136,162]),new W(30,new N(4,122),new N(18,123)),new W(28,new N(13,46),new N(32,47)),new W(30,new N(48,24),new N(14,25)),new W(30,new N(42,15),new N(32,16))),new Ie(39,Int32Array.from([6,26,54,82,110,138,166]),new W(30,new N(20,117),new N(4,118)),new W(28,new N(40,47),new N(7,48)),new W(30,new N(43,24),new N(22,25)),new W(30,new N(10,15),new N(67,16))),new Ie(40,Int32Array.from([6,30,58,86,114,142,170]),new W(30,new N(19,118),new N(6,119)),new W(28,new N(18,47),new N(31,48)),new W(30,new N(34,24),new N(34,25)),new W(30,new N(20,15),new N(61,16)))];var Lt;(function(b){b[b.DATA_MASK_000=0]="DATA_MASK_000",b[b.DATA_MASK_001=1]="DATA_MASK_001",b[b.DATA_MASK_010=2]="DATA_MASK_010",b[b.DATA_MASK_011=3]="DATA_MASK_011",b[b.DATA_MASK_100=4]="DATA_MASK_100",b[b.DATA_MASK_101=5]="DATA_MASK_101",b[b.DATA_MASK_110=6]="DATA_MASK_110",b[b.DATA_MASK_111=7]="DATA_MASK_111"})(Lt||(Lt={}));class pn{constructor(e,n){this.value=e,this.isMasked=n}unmaskBitMatrix(e,n){for(let i=0;i<n;i++)for(let s=0;s<n;s++)this.isMasked(i,s)&&e.flip(s,i)}}pn.values=new Map([[Lt.DATA_MASK_000,new pn(Lt.DATA_MASK_000,(b,e)=>(b+e&1)===0)],[Lt.DATA_MASK_001,new pn(Lt.DATA_MASK_001,(b,e)=>(b&1)===0)],[Lt.DATA_MASK_010,new pn(Lt.DATA_MASK_010,(b,e)=>e%3===0)],[Lt.DATA_MASK_011,new pn(Lt.DATA_MASK_011,(b,e)=>(b+e)%3===0)],[Lt.DATA_MASK_100,new pn(Lt.DATA_MASK_100,(b,e)=>(Math.floor(b/2)+Math.floor(e/3)&1)===0)],[Lt.DATA_MASK_101,new pn(Lt.DATA_MASK_101,(b,e)=>b*e%6===0)],[Lt.DATA_MASK_110,new pn(Lt.DATA_MASK_110,(b,e)=>b*e%6<3)],[Lt.DATA_MASK_111,new pn(Lt.DATA_MASK_111,(b,e)=>(b+e+b*e%3&1)===0)]]);class Zu{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new U;this.bitMatrix=e}readFormatInformation(){if(this.parsedFormatInfo!==null&&this.parsedFormatInfo!==void 0)return this.parsedFormatInfo;let e=0;for(let a=0;a<6;a++)e=this.copyBit(a,8,e);e=this.copyBit(7,8,e),e=this.copyBit(8,8,e),e=this.copyBit(8,7,e);for(let a=5;a>=0;a--)e=this.copyBit(8,a,e);const n=this.bitMatrix.getHeight();let i=0;const s=n-7;for(let a=n-1;a>=s;a--)i=this.copyBit(8,a,i);for(let a=n-8;a<n;a++)i=this.copyBit(a,8,i);if(this.parsedFormatInfo=Gt.decodeFormatInformation(e,i),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new U}readVersion(){if(this.parsedVersion!==null&&this.parsedVersion!==void 0)return this.parsedVersion;const e=this.bitMatrix.getHeight(),n=Math.floor((e-17)/4);if(n<=6)return Ie.getVersionForNumber(n);let i=0;const s=e-11;for(let l=5;l>=0;l--)for(let d=e-9;d>=s;d--)i=this.copyBit(d,l,i);let a=Ie.decodeVersionInformation(i);if(a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;i=0;for(let l=5;l>=0;l--)for(let d=e-9;d>=s;d--)i=this.copyBit(l,d,i);if(a=Ie.decodeVersionInformation(i),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new U}copyBit(e,n,i){return(this.isMirror?this.bitMatrix.get(n,e):this.bitMatrix.get(e,n))?i<<1|1:i<<1}readCodewords(){const e=this.readFormatInformation(),n=this.readVersion(),i=pn.values.get(e.getDataMask()),s=this.bitMatrix.getHeight();i.unmaskBitMatrix(this.bitMatrix,s);const a=n.buildFunctionPattern();let l=!0;const d=new Uint8Array(n.getTotalCodewords());let h=0,p=0,y=0;for(let E=s-1;E>0;E-=2){E===6&&E--;for(let I=0;I<s;I++){const k=l?s-1-I:I;for(let L=0;L<2;L++)a.get(E-L,k)||(y++,p<<=1,this.bitMatrix.get(E-L,k)&&(p|=1),y===8&&(d[h++]=p,y=0,p=0))}l=!l}if(h!==n.getTotalCodewords())throw new U;return d}remask(){if(this.parsedFormatInfo===null)return;const e=pn.values[this.parsedFormatInfo.getDataMask()],n=this.bitMatrix.getHeight();e.unmaskBitMatrix(this.bitMatrix,n)}setMirror(e){this.parsedVersion=null,this.parsedFormatInfo=null,this.isMirror=e}mirror(){const e=this.bitMatrix;for(let n=0,i=e.getWidth();n<i;n++)for(let s=n+1,a=e.getHeight();s<a;s++)e.get(n,s)!==e.get(s,n)&&(e.flip(s,n),e.flip(n,s))}}class Wi{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n,i){if(e.length!==n.getTotalCodewords())throw new v;const s=n.getECBlocksForLevel(i);let a=0;const l=s.getECBlocks();for(const L of l)a+=L.getCount();const d=new Array(a);let h=0;for(const L of l)for(let F=0;F<L.getCount();F++){const H=L.getDataCodewords(),Y=s.getECCodewordsPerBlock()+H;d[h++]=new Wi(H,new Uint8Array(Y))}const p=d[0].codewords.length;let y=d.length-1;for(;y>=0&&d[y].codewords.length!==p;)y--;y++;const E=p-s.getECCodewordsPerBlock();let I=0;for(let L=0;L<E;L++)for(let F=0;F<h;F++)d[F].codewords[L]=e[I++];for(let L=y;L<h;L++)d[L].codewords[E]=e[I++];const k=d[0].codewords.length;for(let L=E;L<k;L++)for(let F=0;F<h;F++){const H=F<y?L:L+1;d[F].codewords[H]=e[I++]}return d}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var mn;(function(b){b[b.TERMINATOR=0]="TERMINATOR",b[b.NUMERIC=1]="NUMERIC",b[b.ALPHANUMERIC=2]="ALPHANUMERIC",b[b.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",b[b.BYTE=4]="BYTE",b[b.ECI=5]="ECI",b[b.KANJI=6]="KANJI",b[b.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",b[b.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",b[b.HANZI=9]="HANZI"})(mn||(mn={}));class Ne{constructor(e,n,i,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=i,this.bits=s,Ne.FOR_BITS.set(s,this),Ne.FOR_VALUE.set(e,this)}static forBits(e){const n=Ne.FOR_BITS.get(e);if(n===void 0)throw new v;return n}getCharacterCountBits(e){const n=e.getVersionNumber();let i;return n<=9?i=0:n<=26?i=1:i=2,this.characterCountBitsForVersions[i]}getValue(){return this.value}getBits(){return this.bits}equals(e){if(!(e instanceof Ne))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}Ne.FOR_BITS=new Map,Ne.FOR_VALUE=new Map,Ne.TERMINATOR=new Ne(mn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Ne.NUMERIC=new Ne(mn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Ne.ALPHANUMERIC=new Ne(mn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Ne.STRUCTURED_APPEND=new Ne(mn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Ne.BYTE=new Ne(mn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Ne.ECI=new Ne(mn.ECI,"ECI",Int32Array.from([0,0,0]),7),Ne.KANJI=new Ne(mn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Ne.FNC1_FIRST_POSITION=new Ne(mn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Ne.FNC1_SECOND_POSITION=new Ne(mn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Ne.HANZI=new Ne(mn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class wt{static decode(e,n,i,s){const a=new Hi(e);let l=new xe;const d=new Array;let h=-1,p=-1;try{let y=null,E=!1,I;do{if(a.available()<4)I=Ne.TERMINATOR;else{const k=a.readBits(4);I=Ne.forBits(k)}switch(I){case Ne.TERMINATOR:break;case Ne.FNC1_FIRST_POSITION:case Ne.FNC1_SECOND_POSITION:E=!0;break;case Ne.STRUCTURED_APPEND:if(a.available()<16)throw new U;h=a.readBits(8),p=a.readBits(8);break;case Ne.ECI:const k=wt.parseECIValue(a);if(y=S.getCharacterSetECIByValue(k),y===null)throw new U;break;case Ne.HANZI:const L=a.readBits(4),F=a.readBits(I.getCharacterCountBits(n));L===wt.GB2312_SUBSET&&wt.decodeHanziSegment(a,l,F);break;default:const H=a.readBits(I.getCharacterCountBits(n));switch(I){case Ne.NUMERIC:wt.decodeNumericSegment(a,l,H);break;case Ne.ALPHANUMERIC:wt.decodeAlphanumericSegment(a,l,H,E);break;case Ne.BYTE:wt.decodeByteSegment(a,l,H,y,d,s);break;case Ne.KANJI:wt.decodeKanjiSegment(a,l,H);break;default:throw new U}break}}while(I!==Ne.TERMINATOR)}catch{throw new U}return new Ht(e,l.toString(),d.length===0?null:d,i===null?null:i.toString(),h,p)}static decodeHanziSegment(e,n,i){if(i*13>e.available())throw new U;const s=new Uint8Array(2*i);let a=0;for(;i>0;){const l=e.readBits(13);let d=l/96<<8&4294967295|l%96;d<959?d+=41377:d+=42657,s[a]=d>>8&255,s[a+1]=d&255,a+=2,i--}try{n.append(ye.decode(s,re.GB2312))}catch(l){throw new U(l)}}static decodeKanjiSegment(e,n,i){if(i*13>e.available())throw new U;const s=new Uint8Array(2*i);let a=0;for(;i>0;){const l=e.readBits(13);let d=l/192<<8&4294967295|l%192;d<7936?d+=33088:d+=49472,s[a]=d>>8,s[a+1]=d,a+=2,i--}try{n.append(ye.decode(s,re.SHIFT_JIS))}catch(l){throw new U(l)}}static decodeByteSegment(e,n,i,s,a,l){if(8*i>e.available())throw new U;const d=new Uint8Array(i);for(let p=0;p<i;p++)d[p]=e.readBits(8);let h;s===null?h=re.guessEncoding(d,l):h=s.getName();try{n.append(ye.decode(d,h))}catch(p){throw new U(p)}a.push(d)}static toAlphaNumericChar(e){if(e>=wt.ALPHANUMERIC_CHARS.length)throw new U;return wt.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,i,s){const a=n.length();for(;i>1;){if(e.available()<11)throw new U;const l=e.readBits(11);n.append(wt.toAlphaNumericChar(Math.floor(l/45))),n.append(wt.toAlphaNumericChar(l%45)),i-=2}if(i===1){if(e.available()<6)throw new U;n.append(wt.toAlphaNumericChar(e.readBits(6)))}if(s)for(let l=a;l<n.length();l++)n.charAt(l)==="%"&&(l<n.length()-1&&n.charAt(l+1)==="%"?n.deleteCharAt(l+1):n.setCharAt(l,""))}static decodeNumericSegment(e,n,i){for(;i>=3;){if(e.available()<10)throw new U;const s=e.readBits(10);if(s>=1e3)throw new U;n.append(wt.toAlphaNumericChar(Math.floor(s/100))),n.append(wt.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(wt.toAlphaNumericChar(s%10)),i-=3}if(i===2){if(e.available()<7)throw new U;const s=e.readBits(7);if(s>=100)throw new U;n.append(wt.toAlphaNumericChar(Math.floor(s/10))),n.append(wt.toAlphaNumericChar(s%10))}else if(i===1){if(e.available()<4)throw new U;const s=e.readBits(4);if(s>=10)throw new U;n.append(wt.toAlphaNumericChar(s))}}static parseECIValue(e){const n=e.readBits(8);if((n&128)===0)return n&127;if((n&192)===128){const i=e.readBits(8);return(n&63)<<8&4294967295|i}if((n&224)===192){const i=e.readBits(16);return(n&31)<<16&4294967295|i}throw new U}}wt.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",wt.GB2312_SUBSET=1;class os{constructor(e){this.mirrored=e}isMirrored(){return this.mirrored}applyMirroredCorrection(e){if(!this.mirrored||e===null||e.length<3)return;const n=e[0];e[0]=e[2],e[2]=n}}class $u{constructor(){this.rsDecoder=new In(be.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(Me.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const i=new Zu(e);let s=null;try{return this.decodeBitMatrixParser(i,n)}catch(a){s=a}try{i.remask(),i.setMirror(!0),i.readVersion(),i.readFormatInformation(),i.mirror();const a=this.decodeBitMatrixParser(i,n);return a.setOther(new os(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const i=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=Wi.getDataBlocks(a,i,s);let d=0;for(const y of l)d+=y.getNumDataCodewords();const h=new Uint8Array(d);let p=0;for(const y of l){const E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let k=0;k<I;k++)h[p++]=E[k]}return wt.decode(h,i,s,n)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class ji extends ve{constructor(e,n,i){super(e,n),this.estimatedModuleSize=i}aboutEquals(e,n,i){if(Math.abs(n-this.getY())<=e&&Math.abs(i-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,i){const s=(this.getX()+n)/2,a=(this.getY()+e)/2,l=(this.estimatedModuleSize+i)/2;return new ji(s,a,l)}}class li{constructor(e,n,i,s,a,l,d){this.image=e,this.startX=n,this.startY=i,this.width=s,this.height=a,this.moduleSize=l,this.resultPointCallback=d,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(3)}find(){const e=this.startX,n=this.height,i=this.width,s=e+i,a=this.startY+n/2,l=new Int32Array(3),d=this.image;for(let h=0;h<n;h++){const p=a+((h&1)===0?Math.floor((h+1)/2):-Math.floor((h+1)/2));l[0]=0,l[1]=0,l[2]=0;let y=e;for(;y<s&&!d.get(y,p);)y++;let E=0;for(;y<s;){if(d.get(y,p))if(E===1)l[1]++;else if(E===2){if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,y);if(I!==null)return I}l[0]=l[2],l[1]=1,l[2]=0,E=1}else l[++E]++;else E===1&&E++,l[E]++;y++}if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,s);if(I!==null)return I}}if(this.possibleCenters.length!==0)return this.possibleCenters[0];throw new $}static centerFromEnd(e,n){return n-e[2]-e[1]/2}foundPatternCross(e){const n=this.moduleSize,i=n/2;for(let s=0;s<3;s++)if(Math.abs(n-e[s])>=i)return!1;return!0}crossCheckVertical(e,n,i,s){const a=this.image,l=a.getHeight(),d=this.crossCheckStateCount;d[0]=0,d[1]=0,d[2]=0;let h=e;for(;h>=0&&a.get(n,h)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&!a.get(n,h)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(n,h)&&d[1]<=i;)d[1]++,h++;if(h===l||d[1]>i)return NaN;for(;h<l&&!a.get(n,h)&&d[2]<=i;)d[2]++,h++;if(d[2]>i)return NaN;const p=d[0]+d[1]+d[2];return 5*Math.abs(p-s)>=2*s?NaN:this.foundPatternCross(d)?li.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i){const s=e[0]+e[1]+e[2],a=li.centerFromEnd(e,i),l=this.crossCheckVertical(n,a,2*e[1],s);if(!isNaN(l)){const d=(e[0]+e[1]+e[2])/3;for(const p of this.possibleCenters)if(p.aboutEquals(d,l,a))return p.combineEstimate(l,a,d);const h=new ji(a,l,d);this.possibleCenters.push(h),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(h)}return null}}class Gi extends ve{constructor(e,n,i,s){super(e,n),this.estimatedModuleSize=i,this.count=s,s===void 0&&(this.count=1)}getEstimatedModuleSize(){return this.estimatedModuleSize}getCount(){return this.count}aboutEquals(e,n,i){if(Math.abs(n-this.getY())<=e&&Math.abs(i-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,i){const s=this.count+1,a=(this.count*this.getX()+n)/s,l=(this.count*this.getY()+e)/s,d=(this.count*this.estimatedModuleSize+i)/s;return new Gi(a,l,d,s)}}class Hu{constructor(e){this.bottomLeft=e[0],this.topLeft=e[1],this.topRight=e[2]}getBottomLeft(){return this.bottomLeft}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}}class Ft{constructor(e,n){this.image=e,this.resultPointCallback=n,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(5),this.resultPointCallback=n}getImage(){return this.image}getPossibleCenters(){return this.possibleCenters}find(e){const n=e!=null&&e.get(V.TRY_HARDER)!==void 0,i=e!=null&&e.get(V.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let d=Math.floor(3*a/(4*Ft.MAX_MODULES));(d<Ft.MIN_SKIP||n)&&(d=Ft.MIN_SKIP);let h=!1;const p=new Int32Array(5);for(let E=d-1;E<a&&!h;E+=d){p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0;let I=0;for(let k=0;k<l;k++)if(s.get(k,E))(I&1)===1&&I++,p[I]++;else if((I&1)===0)if(I===4)if(Ft.foundPatternCross(p)){if(this.handlePossibleCenter(p,E,k,i)===!0)if(d=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const F=this.findRowSkip();F>p[2]&&(E+=F-p[2]-d,k=l-1)}else{p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;continue}I=0,p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0}else p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;else p[++I]++;else p[I]++;Ft.foundPatternCross(p)&&this.handlePossibleCenter(p,E,l,i)===!0&&(d=p[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const y=this.selectBestPatterns();return ve.orderBestPatterns(y),new Hu(y)}static centerFromEnd(e,n){return n-e[4]-e[3]-e[2]/2}static foundPatternCross(e){let n=0;for(let a=0;a<5;a++){const l=e[a];if(l===0)return!1;n+=l}if(n<7)return!1;const i=n/7,s=i/2;return Math.abs(i-e[0])<s&&Math.abs(i-e[1])<s&&Math.abs(3*i-e[2])<3*s&&Math.abs(i-e[3])<s&&Math.abs(i-e[4])<s}getCrossCheckStateCount(){const e=this.crossCheckStateCount;return e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e}crossCheckDiagonal(e,n,i,s){const a=this.getCrossCheckStateCount();let l=0;const d=this.image;for(;e>=l&&n>=l&&d.get(n-l,e-l);)a[2]++,l++;if(e<l||n<l)return!1;for(;e>=l&&n>=l&&!d.get(n-l,e-l)&&a[1]<=i;)a[1]++,l++;if(e<l||n<l||a[1]>i)return!1;for(;e>=l&&n>=l&&d.get(n-l,e-l)&&a[0]<=i;)a[0]++,l++;if(a[0]>i)return!1;const h=d.getHeight(),p=d.getWidth();for(l=1;e+l<h&&n+l<p&&d.get(n+l,e+l);)a[2]++,l++;if(e+l>=h||n+l>=p)return!1;for(;e+l<h&&n+l<p&&!d.get(n+l,e+l)&&a[3]<i;)a[3]++,l++;if(e+l>=h||n+l>=p||a[3]>=i)return!1;for(;e+l<h&&n+l<p&&d.get(n+l,e+l)&&a[4]<i;)a[4]++,l++;if(a[4]>=i)return!1;const y=a[0]+a[1]+a[2]+a[3]+a[4];return Math.abs(y-s)<2*s&&Ft.foundPatternCross(a)}crossCheckVertical(e,n,i,s){const a=this.image,l=a.getHeight(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(n,h);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(n,h)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(n,h)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(n,h);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(n,h)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(n,h)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const p=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(p-s)>=2*s?NaN:Ft.foundPatternCross(d)?Ft.centerFromEnd(d,h):NaN}crossCheckHorizontal(e,n,i,s){const a=this.image,l=a.getWidth(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(h,n);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(h,n)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(h,n)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(h,n);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(h,n)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(h,n)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const p=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(p-s)>=s?NaN:Ft.foundPatternCross(d)?Ft.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=Ft.centerFromEnd(e,i),d=this.crossCheckVertical(n,Math.floor(l),e[2],a);if(!isNaN(d)&&(l=this.crossCheckHorizontal(Math.floor(l),Math.floor(d),e[2],a),!isNaN(l)&&(!s||this.crossCheckDiagonal(Math.floor(d),Math.floor(l),e[2],a)))){const h=a/7;let p=!1;const y=this.possibleCenters;for(let E=0,I=y.length;E<I;E++){const k=y[E];if(k.aboutEquals(h,d,l)){y[E]=k.combineEstimate(d,l,h),p=!0;break}}if(!p){const E=new Gi(l,d,h);y.push(E),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(E)}return!0}return!1}findRowSkip(){if(this.possibleCenters.length<=1)return 0;let n=null;for(const i of this.possibleCenters)if(i.getCount()>=Ft.CENTER_QUORUM)if(n==null)n=i;else return this.hasSkipped=!0,Math.floor((Math.abs(n.getX()-i.getX())-Math.abs(n.getY()-i.getY()))/2);return 0}haveMultiplyConfirmedCenters(){let e=0,n=0;const i=this.possibleCenters.length;for(const l of this.possibleCenters)l.getCount()>=Ft.CENTER_QUORUM&&(e++,n+=l.getEstimatedModuleSize());if(e<3)return!1;const s=n/i;let a=0;for(const l of this.possibleCenters)a+=Math.abs(l.getEstimatedModuleSize()-s);return a<=.05*n}selectBestPatterns(){const e=this.possibleCenters.length;if(e<3)throw new $;const n=this.possibleCenters;let i;if(e>3){let s=0,a=0;for(const h of this.possibleCenters){const p=h.getEstimatedModuleSize();s+=p,a+=p*p}i=s/e;let l=Math.sqrt(a/e-i*i);n.sort((h,p)=>{const y=Math.abs(p.getEstimatedModuleSize()-i),E=Math.abs(h.getEstimatedModuleSize()-i);return y<E?-1:y>E?1:0});const d=Math.max(.2*i,l);for(let h=0;h<n.length&&n.length>3;h++){const p=n[h];Math.abs(p.getEstimatedModuleSize()-i)>d&&(n.splice(h,1),h--)}}if(n.length>3){let s=0;for(const a of n)s+=a.getEstimatedModuleSize();i=s/n.length,n.sort((a,l)=>{if(l.getCount()===a.getCount()){const d=Math.abs(l.getEstimatedModuleSize()-i),h=Math.abs(a.getEstimatedModuleSize()-i);return d<h?1:d>h?-1:0}else return l.getCount()-a.getCount()}),n.splice(3)}return[n[0],n[1],n[2]]}}Ft.CENTER_QUORUM=2,Ft.MIN_SKIP=3,Ft.MAX_MODULES=57;class kr{constructor(e){this.image=e}getImage(){return this.image}getResultPointCallback(){return this.resultPointCallback}detect(e){this.resultPointCallback=e==null?null:e.get(V.NEED_RESULT_POINT_CALLBACK);const i=new Ft(this.image,this.resultPointCallback).find(e);return this.processFinderPatternInfo(i)}processFinderPatternInfo(e){const n=e.getTopLeft(),i=e.getTopRight(),s=e.getBottomLeft(),a=this.calculateModuleSize(n,i,s);if(a<1)throw new $("No pattern found in proccess finder.");const l=kr.computeDimension(n,i,s,a),d=Ie.getProvisionalVersionForDimension(l),h=d.getDimensionForVersion()-7;let p=null;if(d.getAlignmentPatternCenters().length>0){const k=i.getX()-n.getX()+s.getX(),L=i.getY()-n.getY()+s.getY(),F=1-3/h,H=Math.floor(n.getX()+F*(k-n.getX())),Y=Math.floor(n.getY()+F*(L-n.getY()));for(let le=4;le<=16;le<<=1)try{p=this.findAlignmentInRegion(a,H,Y,le);break}catch(ce){if(!(ce instanceof $))throw ce}}const y=kr.createTransform(n,i,s,p,l),E=kr.sampleGrid(this.image,y,l);let I;return p===null?I=[s,n,i]:I=[s,n,i,p],new Bn(E,I)}static createTransform(e,n,i,s,a){const l=a-3.5;let d,h,p,y;return s!==null?(d=s.getX(),h=s.getY(),p=l-3,y=p):(d=n.getX()-e.getX()+i.getX(),h=n.getY()-e.getY()+i.getY(),p=l,y=l),Bt.quadrilateralToQuadrilateral(3.5,3.5,l,3.5,p,y,3.5,l,e.getX(),e.getY(),n.getX(),n.getY(),d,h,i.getX(),i.getY())}static sampleGrid(e,n,i){return R.getInstance().sampleGridWithTransform(e,i,i,n)}static computeDimension(e,n,i,s){const a=Ze.round(ve.distance(e,n)/s),l=Ze.round(ve.distance(e,i)/s);let d=Math.floor((a+l)/2)+7;switch(d&3){case 0:d++;break;case 2:d--;break;case 3:throw new $("Dimensions could be not found.")}return d}calculateModuleSize(e,n,i){return(this.calculateModuleSizeOneWay(e,n)+this.calculateModuleSizeOneWay(e,i))/2}calculateModuleSizeOneWay(e,n){const i=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(e.getX()),Math.floor(e.getY()),Math.floor(n.getX()),Math.floor(n.getY())),s=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(n.getX()),Math.floor(n.getY()),Math.floor(e.getX()),Math.floor(e.getY()));return isNaN(i)?s/7:isNaN(s)?i/7:(i+s)/14}sizeOfBlackWhiteBlackRunBothWays(e,n,i,s){let a=this.sizeOfBlackWhiteBlackRun(e,n,i,s),l=1,d=e-(i-e);d<0?(l=e/(e-d),d=0):d>=this.image.getWidth()&&(l=(this.image.getWidth()-1-e)/(d-e),d=this.image.getWidth()-1);let h=Math.floor(n-(s-n)*l);return l=1,h<0?(l=n/(n-h),h=0):h>=this.image.getHeight()&&(l=(this.image.getHeight()-1-n)/(h-n),h=this.image.getHeight()-1),d=Math.floor(e+(d-e)*l),a+=this.sizeOfBlackWhiteBlackRun(e,n,d,h),a-1}sizeOfBlackWhiteBlackRun(e,n,i,s){const a=Math.abs(s-n)>Math.abs(i-e);if(a){let k=e;e=n,n=k,k=i,i=s,s=k}const l=Math.abs(i-e),d=Math.abs(s-n);let h=-l/2;const p=e<i?1:-1,y=n<s?1:-1;let E=0;const I=i+p;for(let k=e,L=n;k!==I;k+=p){const F=a?L:k,H=a?k:L;if(E===1===this.image.get(F,H)){if(E===2)return Ze.distance(k,L,e,n);E++}if(h+=d,h>0){if(L===s)break;L+=y,h-=l}}return E===2?Ze.distance(i+p,s,e,n):NaN}findAlignmentInRegion(e,n,i,s){const a=Math.floor(s*e),l=Math.max(0,n-a),d=Math.min(this.image.getWidth()-1,n+a);if(d-l<e*3)throw new $("Alignment top exceeds estimated module size.");const h=Math.max(0,i-a),p=Math.min(this.image.getHeight()-1,i+a);if(p-h<e*3)throw new $("Alignment bottom exceeds estimated module size.");return new li(this.image,l,h,d-l,p-h,e,this.resultPointCallback).find()}}class qn{constructor(){this.decoder=new $u}getDecoder(){return this.decoder}decode(e,n){let i,s;if(n!=null&&n.get(V.PURE_BARCODE)!==void 0){const h=qn.extractPureBits(e.getBlackMatrix());i=this.decoder.decodeBitMatrix(h,n),s=qn.NO_POINTS}else{const h=new kr(e.getBlackMatrix()).detect(n);i=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}i.getOther()instanceof os&&i.getOther().applyMirroredCorrection(s);const a=new Ee(i.getText(),i.getRawBytes(),void 0,s,Ce.QR_CODE,void 0),l=i.getByteSegments();l!==null&&a.putMetadata(Ue.BYTE_SEGMENTS,l);const d=i.getECLevel();return d!==null&&a.putMetadata(Ue.ERROR_CORRECTION_LEVEL,d),i.hasStructuredAppend()&&(a.putMetadata(Ue.STRUCTURED_APPEND_SEQUENCE,i.getStructuredAppendSequenceNumber()),a.putMetadata(Ue.STRUCTURED_APPEND_PARITY,i.getStructuredAppendParity())),a}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n===null||i===null)throw new $;const s=this.moduleSize(n,e);let a=n[1],l=i[1],d=n[0],h=i[0];if(d>=h||a>=l)throw new $;if(l-a!==h-d&&(h=d+(l-a),h>=e.getWidth()))throw new $;const p=Math.round((h-d+1)/s),y=Math.round((l-a+1)/s);if(p<=0||y<=0)throw new $;if(y!==p)throw new $;const E=Math.floor(s/2);a+=E,d+=E;const I=d+Math.floor((p-1)*s)-h;if(I>0){if(I>E)throw new $;d-=I}const k=a+Math.floor((y-1)*s)-l;if(k>0){if(k>E)throw new $;a-=k}const L=new Me(p,y);for(let F=0;F<y;F++){const H=a+Math.floor(F*s);for(let Y=0;Y<p;Y++)e.get(d+Math.floor(Y*s),H)&&L.set(Y,F)}return L}static moduleSize(e,n){const i=n.getHeight(),s=n.getWidth();let a=e[0],l=e[1],d=!0,h=0;for(;a<s&&l<i;){if(d!==n.get(a,l)){if(++h===5)break;d=!d}a++,l++}if(a===s||l===i)throw new $;return(a-e[0])/7}}qn.NO_POINTS=new Array;class De{PDF417Common(){}static getBitCountSum(e){return Ze.sum(e)}static toIntArray(e){if(e==null||!e.length)return De.EMPTY_INT_ARRAY;const n=new Int32Array(e.length);let i=0;for(const s of e)n[i++]=s;return n}static getCodeword(e){const n=Z.binarySearch(De.SYMBOL_TABLE,e&262143);return n<0?-1:(De.CODEWORD_TABLE[n]-1)%De.NUMBER_OF_CODEWORDS}}De.NUMBER_OF_CODEWORDS=929,De.MAX_CODEWORDS_IN_BARCODE=De.NUMBER_OF_CODEWORDS-1,De.MIN_ROWS_IN_BARCODE=3,De.MAX_ROWS_IN_BARCODE=90,De.MODULES_IN_CODEWORD=17,De.MODULES_IN_STOP_PATTERN=18,De.BARS_IN_MODULE=8,De.EMPTY_INT_ARRAY=new Int32Array([]),De.SYMBOL_TABLE=Int32Array.from([66142,66170,66206,66236,66290,66292,66350,66382,66396,66454,66470,66476,66594,66600,66614,66626,66628,66632,66640,66654,66662,66668,66682,66690,66718,66720,66748,66758,66776,66798,66802,66804,66820,66824,66832,66846,66848,66876,66880,66936,66950,66956,66968,66992,67006,67022,67036,67042,67044,67048,67062,67118,67150,67164,67214,67228,67256,67294,67322,67350,67366,67372,67398,67404,67416,67438,67474,67476,67490,67492,67496,67510,67618,67624,67650,67656,67664,67678,67686,67692,67706,67714,67716,67728,67742,67744,67772,67782,67788,67800,67822,67826,67828,67842,67848,67870,67872,67900,67904,67960,67974,67992,68016,68030,68046,68060,68066,68068,68072,68086,68104,68112,68126,68128,68156,68160,68216,68336,68358,68364,68376,68400,68414,68448,68476,68494,68508,68536,68546,68548,68552,68560,68574,68582,68588,68654,68686,68700,68706,68708,68712,68726,68750,68764,68792,68802,68804,68808,68816,68830,68838,68844,68858,68878,68892,68920,68976,68990,68994,68996,69e3,69008,69022,69024,69052,69062,69068,69080,69102,69106,69108,69142,69158,69164,69190,69208,69230,69254,69260,69272,69296,69310,69326,69340,69386,69394,69396,69410,69416,69430,69442,69444,69448,69456,69470,69478,69484,69554,69556,69666,69672,69698,69704,69712,69726,69754,69762,69764,69776,69790,69792,69820,69830,69836,69848,69870,69874,69876,69890,69918,69920,69948,69952,70008,70022,70040,70064,70078,70094,70108,70114,70116,70120,70134,70152,70174,70176,70264,70384,70412,70448,70462,70496,70524,70542,70556,70584,70594,70600,70608,70622,70630,70636,70664,70672,70686,70688,70716,70720,70776,70896,71136,71180,71192,71216,71230,71264,71292,71360,71416,71452,71480,71536,71550,71554,71556,71560,71568,71582,71584,71612,71622,71628,71640,71662,71726,71732,71758,71772,71778,71780,71784,71798,71822,71836,71864,71874,71880,71888,71902,71910,71916,71930,71950,71964,71992,72048,72062,72066,72068,72080,72094,72096,72124,72134,72140,72152,72174,72178,72180,72206,72220,72248,72304,72318,72416,72444,72456,72464,72478,72480,72508,72512,72568,72588,72600,72624,72638,72654,72668,72674,72676,72680,72694,72726,72742,72748,72774,72780,72792,72814,72838,72856,72880,72894,72910,72924,72930,72932,72936,72950,72966,72972,72984,73008,73022,73056,73084,73102,73116,73144,73156,73160,73168,73182,73190,73196,73210,73226,73234,73236,73250,73252,73256,73270,73282,73284,73296,73310,73318,73324,73346,73348,73352,73360,73374,73376,73404,73414,73420,73432,73454,73498,73518,73522,73524,73550,73564,73570,73572,73576,73590,73800,73822,73858,73860,73872,73886,73888,73916,73944,73970,73972,73992,74014,74016,74044,74048,74104,74118,74136,74160,74174,74210,74212,74216,74230,74244,74256,74270,74272,74360,74480,74502,74508,74544,74558,74592,74620,74638,74652,74680,74690,74696,74704,74726,74732,74782,74784,74812,74992,75232,75288,75326,75360,75388,75456,75512,75576,75632,75646,75650,75652,75664,75678,75680,75708,75718,75724,75736,75758,75808,75836,75840,75896,76016,76256,76736,76824,76848,76862,76896,76924,76992,77048,77296,77340,77368,77424,77438,77536,77564,77572,77576,77584,77600,77628,77632,77688,77702,77708,77720,77744,77758,77774,77788,77870,77902,77916,77922,77928,77966,77980,78008,78018,78024,78032,78046,78060,78074,78094,78136,78192,78206,78210,78212,78224,78238,78240,78268,78278,78284,78296,78322,78324,78350,78364,78448,78462,78560,78588,78600,78622,78624,78652,78656,78712,78726,78744,78768,78782,78798,78812,78818,78820,78824,78838,78862,78876,78904,78960,78974,79072,79100,79296,79352,79368,79376,79390,79392,79420,79424,79480,79600,79628,79640,79664,79678,79712,79740,79772,79800,79810,79812,79816,79824,79838,79846,79852,79894,79910,79916,79942,79948,79960,79982,79988,80006,80024,80048,80062,80078,80092,80098,80100,80104,80134,80140,80176,80190,80224,80252,80270,80284,80312,80328,80336,80350,80358,80364,80378,80390,80396,80408,80432,80446,80480,80508,80576,80632,80654,80668,80696,80752,80766,80776,80784,80798,80800,80828,80844,80856,80878,80882,80884,80914,80916,80930,80932,80936,80950,80962,80968,80976,80990,80998,81004,81026,81028,81040,81054,81056,81084,81094,81100,81112,81134,81154,81156,81160,81168,81182,81184,81212,81216,81272,81286,81292,81304,81328,81342,81358,81372,81380,81384,81398,81434,81454,81458,81460,81486,81500,81506,81508,81512,81526,81550,81564,81592,81602,81604,81608,81616,81630,81638,81644,81702,81708,81722,81734,81740,81752,81774,81778,81780,82050,82078,82080,82108,82180,82184,82192,82206,82208,82236,82240,82296,82316,82328,82352,82366,82402,82404,82408,82440,82448,82462,82464,82492,82496,82552,82672,82694,82700,82712,82736,82750,82784,82812,82830,82882,82884,82888,82896,82918,82924,82952,82960,82974,82976,83004,83008,83064,83184,83424,83468,83480,83504,83518,83552,83580,83648,83704,83740,83768,83824,83838,83842,83844,83848,83856,83872,83900,83910,83916,83928,83950,83984,84e3,84028,84032,84088,84208,84448,84928,85040,85054,85088,85116,85184,85240,85488,85560,85616,85630,85728,85756,85764,85768,85776,85790,85792,85820,85824,85880,85894,85900,85912,85936,85966,85980,86048,86080,86136,86256,86496,86976,88160,88188,88256,88312,88560,89056,89200,89214,89312,89340,89536,89592,89608,89616,89632,89664,89720,89840,89868,89880,89904,89952,89980,89998,90012,90040,90190,90204,90254,90268,90296,90306,90308,90312,90334,90382,90396,90424,90480,90494,90500,90504,90512,90526,90528,90556,90566,90572,90584,90610,90612,90638,90652,90680,90736,90750,90848,90876,90884,90888,90896,90910,90912,90940,90944,91e3,91014,91020,91032,91056,91070,91086,91100,91106,91108,91112,91126,91150,91164,91192,91248,91262,91360,91388,91584,91640,91664,91678,91680,91708,91712,91768,91888,91928,91952,91966,92e3,92028,92046,92060,92088,92098,92100,92104,92112,92126,92134,92140,92188,92216,92272,92384,92412,92608,92664,93168,93200,93214,93216,93244,93248,93304,93424,93664,93720,93744,93758,93792,93820,93888,93944,93980,94008,94064,94078,94084,94088,94096,94110,94112,94140,94150,94156,94168,94246,94252,94278,94284,94296,94318,94342,94348,94360,94384,94398,94414,94428,94440,94470,94476,94488,94512,94526,94560,94588,94606,94620,94648,94658,94660,94664,94672,94686,94694,94700,94714,94726,94732,94744,94768,94782,94816,94844,94912,94968,94990,95004,95032,95088,95102,95112,95120,95134,95136,95164,95180,95192,95214,95218,95220,95244,95256,95280,95294,95328,95356,95424,95480,95728,95758,95772,95800,95856,95870,95968,95996,96008,96016,96030,96032,96060,96064,96120,96152,96176,96190,96220,96226,96228,96232,96290,96292,96296,96310,96322,96324,96328,96336,96350,96358,96364,96386,96388,96392,96400,96414,96416,96444,96454,96460,96472,96494,96498,96500,96514,96516,96520,96528,96542,96544,96572,96576,96632,96646,96652,96664,96688,96702,96718,96732,96738,96740,96744,96758,96772,96776,96784,96798,96800,96828,96832,96888,97008,97030,97036,97048,97072,97086,97120,97148,97166,97180,97208,97220,97224,97232,97246,97254,97260,97326,97330,97332,97358,97372,97378,97380,97384,97398,97422,97436,97464,97474,97476,97480,97488,97502,97510,97516,97550,97564,97592,97648,97666,97668,97672,97680,97694,97696,97724,97734,97740,97752,97774,97830,97836,97850,97862,97868,97880,97902,97906,97908,97926,97932,97944,97968,97998,98012,98018,98020,98024,98038,98618,98674,98676,98838,98854,98874,98892,98904,98926,98930,98932,98968,99006,99042,99044,99048,99062,99166,99194,99246,99286,99350,99366,99372,99386,99398,99416,99438,99442,99444,99462,99504,99518,99534,99548,99554,99556,99560,99574,99590,99596,99608,99632,99646,99680,99708,99726,99740,99768,99778,99780,99784,99792,99806,99814,99820,99834,99858,99860,99874,99880,99894,99906,99920,99934,99962,99970,99972,99976,99984,99998,1e5,100028,100038,100044,100056,100078,100082,100084,100142,100174,100188,100246,100262,100268,100306,100308,100390,100396,100410,100422,100428,100440,100462,100466,100468,100486,100504,100528,100542,100558,100572,100578,100580,100584,100598,100620,100656,100670,100704,100732,100750,100792,100802,100808,100816,100830,100838,100844,100858,100888,100912,100926,100960,100988,101056,101112,101148,101176,101232,101246,101250,101252,101256,101264,101278,101280,101308,101318,101324,101336,101358,101362,101364,101410,101412,101416,101430,101442,101448,101456,101470,101478,101498,101506,101508,101520,101534,101536,101564,101580,101618,101620,101636,101640,101648,101662,101664,101692,101696,101752,101766,101784,101838,101858,101860,101864,101934,101938,101940,101966,101980,101986,101988,101992,102030,102044,102072,102082,102084,102088,102096,102138,102166,102182,102188,102214,102220,102232,102254,102282,102290,102292,102306,102308,102312,102326,102444,102458,102470,102476,102488,102514,102516,102534,102552,102576,102590,102606,102620,102626,102632,102646,102662,102668,102704,102718,102752,102780,102798,102812,102840,102850,102856,102864,102878,102886,102892,102906,102936,102974,103008,103036,103104,103160,103224,103280,103294,103298,103300,103312,103326,103328,103356,103366,103372,103384,103406,103410,103412,103472,103486,103520,103548,103616,103672,103920,103992,104048,104062,104160,104188,104194,104196,104200,104208,104224,104252,104256,104312,104326,104332,104344,104368,104382,104398,104412,104418,104420,104424,104482,104484,104514,104520,104528,104542,104550,104570,104578,104580,104592,104606,104608,104636,104652,104690,104692,104706,104712,104734,104736,104764,104768,104824,104838,104856,104910,104930,104932,104936,104968,104976,104990,104992,105020,105024,105080,105200,105240,105278,105312,105372,105410,105412,105416,105424,105446,105518,105524,105550,105564,105570,105572,105576,105614,105628,105656,105666,105672,105680,105702,105722,105742,105756,105784,105840,105854,105858,105860,105864,105872,105888,105932,105970,105972,106006,106022,106028,106054,106060,106072,106100,106118,106124,106136,106160,106174,106190,106210,106212,106216,106250,106258,106260,106274,106276,106280,106306,106308,106312,106320,106334,106348,106394,106414,106418,106420,106566,106572,106610,106612,106630,106636,106648,106672,106686,106722,106724,106728,106742,106758,106764,106776,106800,106814,106848,106876,106894,106908,106936,106946,106948,106952,106960,106974,106982,106988,107032,107056,107070,107104,107132,107200,107256,107292,107320,107376,107390,107394,107396,107400,107408,107422,107424,107452,107462,107468,107480,107502,107506,107508,107544,107568,107582,107616,107644,107712,107768,108016,108060,108088,108144,108158,108256,108284,108290,108292,108296,108304,108318,108320,108348,108352,108408,108422,108428,108440,108464,108478,108494,108508,108514,108516,108520,108592,108640,108668,108736,108792,109040,109536,109680,109694,109792,109820,110016,110072,110084,110088,110096,110112,110140,110144,110200,110320,110342,110348,110360,110384,110398,110432,110460,110478,110492,110520,110532,110536,110544,110558,110658,110686,110714,110722,110724,110728,110736,110750,110752,110780,110796,110834,110836,110850,110852,110856,110864,110878,110880,110908,110912,110968,110982,111e3,111054,111074,111076,111080,111108,111112,111120,111134,111136,111164,111168,111224,111344,111372,111422,111456,111516,111554,111556,111560,111568,111590,111632,111646,111648,111676,111680,111736,111856,112096,112152,112224,112252,112320,112440,112514,112516,112520,112528,112542,112544,112588,112686,112718,112732,112782,112796,112824,112834,112836,112840,112848,112870,112890,112910,112924,112952,113008,113022,113026,113028,113032,113040,113054,113056,113100,113138,113140,113166,113180,113208,113264,113278,113376,113404,113416,113424,113440,113468,113472,113560,113614,113634,113636,113640,113686,113702,113708,113734,113740,113752,113778,113780,113798,113804,113816,113840,113854,113870,113890,113892,113896,113926,113932,113944,113968,113982,114016,114044,114076,114114,114116,114120,114128,114150,114170,114194,114196,114210,114212,114216,114242,114244,114248,114256,114270,114278,114306,114308,114312,114320,114334,114336,114364,114380,114420,114458,114478,114482,114484,114510,114524,114530,114532,114536,114842,114866,114868,114970,114994,114996,115042,115044,115048,115062,115130,115226,115250,115252,115278,115292,115298,115300,115304,115318,115342,115394,115396,115400,115408,115422,115430,115436,115450,115478,115494,115514,115526,115532,115570,115572,115738,115758,115762,115764,115790,115804,115810,115812,115816,115830,115854,115868,115896,115906,115912,115920,115934,115942,115948,115962,115996,116024,116080,116094,116098,116100,116104,116112,116126,116128,116156,116166,116172,116184,116206,116210,116212,116246,116262,116268,116282,116294,116300,116312,116334,116338,116340,116358,116364,116376,116400,116414,116430,116444,116450,116452,116456,116498,116500,116514,116520,116534,116546,116548,116552,116560,116574,116582,116588,116602,116654,116694,116714,116762,116782,116786,116788,116814,116828,116834,116836,116840,116854,116878,116892,116920,116930,116936,116944,116958,116966,116972,116986,117006,117048,117104,117118,117122,117124,117136,117150,117152,117180,117190,117196,117208,117230,117234,117236,117304,117360,117374,117472,117500,117506,117508,117512,117520,117536,117564,117568,117624,117638,117644,117656,117680,117694,117710,117724,117730,117732,117736,117750,117782,117798,117804,117818,117830,117848,117874,117876,117894,117936,117950,117966,117986,117988,117992,118022,118028,118040,118064,118078,118112,118140,118172,118210,118212,118216,118224,118238,118246,118266,118306,118312,118338,118352,118366,118374,118394,118402,118404,118408,118416,118430,118432,118460,118476,118514,118516,118574,118578,118580,118606,118620,118626,118628,118632,118678,118694,118700,118730,118738,118740,118830,118834,118836,118862,118876,118882,118884,118888,118902,118926,118940,118968,118978,118980,118984,118992,119006,119014,119020,119034,119068,119096,119152,119166,119170,119172,119176,119184,119198,119200,119228,119238,119244,119256,119278,119282,119284,119324,119352,119408,119422,119520,119548,119554,119556,119560,119568,119582,119584,119612,119616,119672,119686,119692,119704,119728,119742,119758,119772,119778,119780,119784,119798,119920,119934,120032,120060,120256,120312,120324,120328,120336,120352,120384,120440,120560,120582,120588,120600,120624,120638,120672,120700,120718,120732,120760,120770,120772,120776,120784,120798,120806,120812,120870,120876,120890,120902,120908,120920,120946,120948,120966,120972,120984,121008,121022,121038,121058,121060,121064,121078,121100,121112,121136,121150,121184,121212,121244,121282,121284,121288,121296,121318,121338,121356,121368,121392,121406,121440,121468,121536,121592,121656,121730,121732,121736,121744,121758,121760,121804,121842,121844,121890,121922,121924,121928,121936,121950,121958,121978,121986,121988,121992,122e3,122014,122016,122044,122060,122098,122100,122116,122120,122128,122142,122144,122172,122176,122232,122246,122264,122318,122338,122340,122344,122414,122418,122420,122446,122460,122466,122468,122472,122510,122524,122552,122562,122564,122568,122576,122598,122618,122646,122662,122668,122694,122700,122712,122738,122740,122762,122770,122772,122786,122788,122792,123018,123026,123028,123042,123044,123048,123062,123098,123146,123154,123156,123170,123172,123176,123190,123202,123204,123208,123216,123238,123244,123258,123290,123314,123316,123402,123410,123412,123426,123428,123432,123446,123458,123464,123472,123486,123494,123500,123514,123522,123524,123528,123536,123552,123580,123590,123596,123608,123630,123634,123636,123674,123698,123700,123740,123746,123748,123752,123834,123914,123922,123924,123938,123944,123958,123970,123976,123984,123998,124006,124012,124026,124034,124036,124048,124062,124064,124092,124102,124108,124120,124142,124146,124148,124162,124164,124168,124176,124190,124192,124220,124224,124280,124294,124300,124312,124336,124350,124366,124380,124386,124388,124392,124406,124442,124462,124466,124468,124494,124508,124514,124520,124558,124572,124600,124610,124612,124616,124624,124646,124666,124694,124710,124716,124730,124742,124748,124760,124786,124788,124818,124820,124834,124836,124840,124854,124946,124948,124962,124964,124968,124982,124994,124996,125e3,125008,125022,125030,125036,125050,125058,125060,125064,125072,125086,125088,125116,125126,125132,125144,125166,125170,125172,125186,125188,125192,125200,125216,125244,125248,125304,125318,125324,125336,125360,125374,125390,125404,125410,125412,125416,125430,125444,125448,125456,125472,125504,125560,125680,125702,125708,125720,125744,125758,125792,125820,125838,125852,125880,125890,125892,125896,125904,125918,125926,125932,125978,125998,126002,126004,126030,126044,126050,126052,126056,126094,126108,126136,126146,126148,126152,126160,126182,126202,126222,126236,126264,126320,126334,126338,126340,126344,126352,126366,126368,126412,126450,126452,126486,126502,126508,126522,126534,126540,126552,126574,126578,126580,126598,126604,126616,126640,126654,126670,126684,126690,126692,126696,126738,126754,126756,126760,126774,126786,126788,126792,126800,126814,126822,126828,126842,126894,126898,126900,126934,127126,127142,127148,127162,127178,127186,127188,127254,127270,127276,127290,127302,127308,127320,127342,127346,127348,127370,127378,127380,127394,127396,127400,127450,127510,127526,127532,127546,127558,127576,127598,127602,127604,127622,127628,127640,127664,127678,127694,127708,127714,127716,127720,127734,127754,127762,127764,127778,127784,127810,127812,127816,127824,127838,127846,127866,127898,127918,127922,127924,128022,128038,128044,128058,128070,128076,128088,128110,128114,128116,128134,128140,128152,128176,128190,128206,128220,128226,128228,128232,128246,128262,128268,128280,128304,128318,128352,128380,128398,128412,128440,128450,128452,128456,128464,128478,128486,128492,128506,128522,128530,128532,128546,128548,128552,128566,128578,128580,128584,128592,128606,128614,128634,128642,128644,128648,128656,128670,128672,128700,128716,128754,128756,128794,128814,128818,128820,128846,128860,128866,128868,128872,128886,128918,128934,128940,128954,128978,128980,129178,129198,129202,129204,129238,129258,129306,129326,129330,129332,129358,129372,129378,129380,129384,129398,129430,129446,129452,129466,129482,129490,129492,129562,129582,129586,129588,129614,129628,129634,129636,129640,129654,129678,129692,129720,129730,129732,129736,129744,129758,129766,129772,129814,129830,129836,129850,129862,129868,129880,129902,129906,129908,129930,129938,129940,129954,129956,129960,129974,130010]),De.CODEWORD_TABLE=Int32Array.from([2627,1819,2622,2621,1813,1812,2729,2724,2723,2779,2774,2773,902,896,908,868,865,861,859,2511,873,871,1780,835,2493,825,2491,842,837,844,1764,1762,811,810,809,2483,807,2482,806,2480,815,814,813,812,2484,817,816,1745,1744,1742,1746,2655,2637,2635,2626,2625,2623,2628,1820,2752,2739,2737,2728,2727,2725,2730,2785,2783,2778,2777,2775,2780,787,781,747,739,736,2413,754,752,1719,692,689,681,2371,678,2369,700,697,694,703,1688,1686,642,638,2343,631,2341,627,2338,651,646,643,2345,654,652,1652,1650,1647,1654,601,599,2322,596,2321,594,2319,2317,611,610,608,606,2324,603,2323,615,614,612,1617,1616,1614,1612,616,1619,1618,2575,2538,2536,905,901,898,909,2509,2507,2504,870,867,864,860,2512,875,872,1781,2490,2489,2487,2485,1748,836,834,832,830,2494,827,2492,843,841,839,845,1765,1763,2701,2676,2674,2653,2648,2656,2634,2633,2631,2629,1821,2638,2636,2770,2763,2761,2750,2745,2753,2736,2735,2733,2731,1848,2740,2738,2786,2784,591,588,576,569,566,2296,1590,537,534,526,2276,522,2274,545,542,539,548,1572,1570,481,2245,466,2242,462,2239,492,485,482,2249,496,494,1534,1531,1528,1538,413,2196,406,2191,2188,425,419,2202,415,2199,432,430,427,1472,1467,1464,433,1476,1474,368,367,2160,365,2159,362,2157,2155,2152,378,377,375,2166,372,2165,369,2162,383,381,379,2168,1419,1418,1416,1414,385,1411,384,1423,1422,1420,1424,2461,802,2441,2439,790,786,783,794,2409,2406,2403,750,742,738,2414,756,753,1720,2367,2365,2362,2359,1663,693,691,684,2373,680,2370,702,699,696,704,1690,1687,2337,2336,2334,2332,1624,2329,1622,640,637,2344,634,2342,630,2340,650,648,645,2346,655,653,1653,1651,1649,1655,2612,2597,2595,2571,2568,2565,2576,2534,2529,2526,1787,2540,2537,907,904,900,910,2503,2502,2500,2498,1768,2495,1767,2510,2508,2506,869,866,863,2513,876,874,1782,2720,2713,2711,2697,2694,2691,2702,2672,2670,2664,1828,2678,2675,2647,2646,2644,2642,1823,2639,1822,2654,2652,2650,2657,2771,1855,2765,2762,1850,1849,2751,2749,2747,2754,353,2148,344,342,336,2142,332,2140,345,1375,1373,306,2130,299,2128,295,2125,319,314,311,2132,1354,1352,1349,1356,262,257,2101,253,2096,2093,274,273,267,2107,263,2104,280,278,275,1316,1311,1308,1320,1318,2052,202,2050,2044,2040,219,2063,212,2060,208,2055,224,221,2066,1260,1258,1252,231,1248,229,1266,1264,1261,1268,155,1998,153,1996,1994,1991,1988,165,164,2007,162,2006,159,2003,2e3,172,171,169,2012,166,2010,1186,1184,1182,1179,175,1176,173,1192,1191,1189,1187,176,1194,1193,2313,2307,2305,592,589,2294,2292,2289,578,572,568,2297,580,1591,2272,2267,2264,1547,538,536,529,2278,525,2275,547,544,541,1574,1571,2237,2235,2229,1493,2225,1489,478,2247,470,2244,465,2241,493,488,484,2250,498,495,1536,1533,1530,1539,2187,2186,2184,2182,1432,2179,1430,2176,1427,414,412,2197,409,2195,405,2193,2190,426,424,421,2203,418,2201,431,429,1473,1471,1469,1466,434,1477,1475,2478,2472,2470,2459,2457,2454,2462,803,2437,2432,2429,1726,2443,2440,792,789,785,2401,2399,2393,1702,2389,1699,2411,2408,2405,745,741,2415,758,755,1721,2358,2357,2355,2353,1661,2350,1660,2347,1657,2368,2366,2364,2361,1666,690,687,2374,683,2372,701,698,705,1691,1689,2619,2617,2610,2608,2605,2613,2593,2588,2585,1803,2599,2596,2563,2561,2555,1797,2551,1795,2573,2570,2567,2577,2525,2524,2522,2520,1786,2517,1785,2514,1783,2535,2533,2531,2528,1788,2541,2539,906,903,911,2721,1844,2715,2712,1838,1836,2699,2696,2693,2703,1827,1826,1824,2673,2671,2669,2666,1829,2679,2677,1858,1857,2772,1854,1853,1851,1856,2766,2764,143,1987,139,1986,135,133,131,1984,128,1983,125,1981,138,137,136,1985,1133,1132,1130,112,110,1974,107,1973,104,1971,1969,122,121,119,117,1977,114,1976,124,1115,1114,1112,1110,1117,1116,84,83,1953,81,1952,78,1950,1948,1945,94,93,91,1959,88,1958,85,1955,99,97,95,1961,1086,1085,1083,1081,1078,100,1090,1089,1087,1091,49,47,1917,44,1915,1913,1910,1907,59,1926,56,1925,53,1922,1919,66,64,1931,61,1929,1042,1040,1038,71,1035,70,1032,68,1048,1047,1045,1043,1050,1049,12,10,1869,1867,1864,1861,21,1880,19,1877,1874,1871,28,1888,25,1886,22,1883,982,980,977,974,32,30,991,989,987,984,34,995,994,992,2151,2150,2147,2146,2144,356,355,354,2149,2139,2138,2136,2134,1359,343,341,338,2143,335,2141,348,347,346,1376,1374,2124,2123,2121,2119,1326,2116,1324,310,308,305,2131,302,2129,298,2127,320,318,316,313,2133,322,321,1355,1353,1351,1357,2092,2091,2089,2087,1276,2084,1274,2081,1271,259,2102,256,2100,252,2098,2095,272,269,2108,266,2106,281,279,277,1317,1315,1313,1310,282,1321,1319,2039,2037,2035,2032,1203,2029,1200,1197,207,2053,205,2051,201,2049,2046,2043,220,218,2064,215,2062,211,2059,228,226,223,2069,1259,1257,1254,232,1251,230,1267,1265,1263,2316,2315,2312,2311,2309,2314,2304,2303,2301,2299,1593,2308,2306,590,2288,2287,2285,2283,1578,2280,1577,2295,2293,2291,579,577,574,571,2298,582,581,1592,2263,2262,2260,2258,1545,2255,1544,2252,1541,2273,2271,2269,2266,1550,535,532,2279,528,2277,546,543,549,1575,1573,2224,2222,2220,1486,2217,1485,2214,1482,1479,2238,2236,2234,2231,1496,2228,1492,480,477,2248,473,2246,469,2243,490,487,2251,497,1537,1535,1532,2477,2476,2474,2479,2469,2468,2466,2464,1730,2473,2471,2453,2452,2450,2448,1729,2445,1728,2460,2458,2456,2463,805,804,2428,2427,2425,2423,1725,2420,1724,2417,1722,2438,2436,2434,2431,1727,2444,2442,793,791,788,795,2388,2386,2384,1697,2381,1696,2378,1694,1692,2402,2400,2398,2395,1703,2392,1701,2412,2410,2407,751,748,744,2416,759,757,1807,2620,2618,1806,1805,2611,2609,2607,2614,1802,1801,1799,2594,2592,2590,2587,1804,2600,2598,1794,1793,1791,1789,2564,2562,2560,2557,1798,2554,1796,2574,2572,2569,2578,1847,1846,2722,1843,1842,1840,1845,2716,2714,1835,1834,1832,1830,1839,1837,2700,2698,2695,2704,1817,1811,1810,897,862,1777,829,826,838,1760,1758,808,2481,1741,1740,1738,1743,2624,1818,2726,2776,782,740,737,1715,686,679,695,1682,1680,639,628,2339,647,644,1645,1643,1640,1648,602,600,597,595,2320,593,2318,609,607,604,1611,1610,1608,1606,613,1615,1613,2328,926,924,892,886,899,857,850,2505,1778,824,823,821,819,2488,818,2486,833,831,828,840,1761,1759,2649,2632,2630,2746,2734,2732,2782,2781,570,567,1587,531,527,523,540,1566,1564,476,467,463,2240,486,483,1524,1521,1518,1529,411,403,2192,399,2189,423,416,1462,1457,1454,428,1468,1465,2210,366,363,2158,360,2156,357,2153,376,373,370,2163,1410,1409,1407,1405,382,1402,380,1417,1415,1412,1421,2175,2174,777,774,771,784,732,725,722,2404,743,1716,676,674,668,2363,665,2360,685,1684,1681,626,624,622,2335,620,2333,617,2330,641,635,649,1646,1644,1642,2566,928,925,2530,2527,894,891,888,2501,2499,2496,858,856,854,851,1779,2692,2668,2665,2645,2643,2640,2651,2768,2759,2757,2744,2743,2741,2748,352,1382,340,337,333,1371,1369,307,300,296,2126,315,312,1347,1342,1350,261,258,250,2097,246,2094,271,268,264,1306,1301,1298,276,1312,1309,2115,203,2048,195,2045,191,2041,213,209,2056,1246,1244,1238,225,1234,222,1256,1253,1249,1262,2080,2079,154,1997,150,1995,147,1992,1989,163,160,2004,156,2001,1175,1174,1172,1170,1167,170,1164,167,1185,1183,1180,1177,174,1190,1188,2025,2024,2022,587,586,564,559,556,2290,573,1588,520,518,512,2268,508,2265,530,1568,1565,461,457,2233,450,2230,446,2226,479,471,489,1526,1523,1520,397,395,2185,392,2183,389,2180,2177,410,2194,402,422,1463,1461,1459,1456,1470,2455,799,2433,2430,779,776,773,2397,2394,2390,734,728,724,746,1717,2356,2354,2351,2348,1658,677,675,673,670,667,688,1685,1683,2606,2589,2586,2559,2556,2552,927,2523,2521,2518,2515,1784,2532,895,893,890,2718,2709,2707,2689,2687,2684,2663,2662,2660,2658,1825,2667,2769,1852,2760,2758,142,141,1139,1138,134,132,129,126,1982,1129,1128,1126,1131,113,111,108,105,1972,101,1970,120,118,115,1109,1108,1106,1104,123,1113,1111,82,79,1951,75,1949,72,1946,92,89,86,1956,1077,1076,1074,1072,98,1069,96,1084,1082,1079,1088,1968,1967,48,45,1916,42,1914,39,1911,1908,60,57,54,1923,50,1920,1031,1030,1028,1026,67,1023,65,1020,62,1041,1039,1036,1033,69,1046,1044,1944,1943,1941,11,9,1868,7,1865,1862,1859,20,1878,16,1875,13,1872,970,968,966,963,29,960,26,23,983,981,978,975,33,971,31,990,988,985,1906,1904,1902,993,351,2145,1383,331,330,328,326,2137,323,2135,339,1372,1370,294,293,291,289,2122,286,2120,283,2117,309,303,317,1348,1346,1344,245,244,242,2090,239,2088,236,2085,2082,260,2099,249,270,1307,1305,1303,1300,1314,189,2038,186,2036,183,2033,2030,2026,206,198,2047,194,216,1247,1245,1243,1240,227,1237,1255,2310,2302,2300,2286,2284,2281,565,563,561,558,575,1589,2261,2259,2256,2253,1542,521,519,517,514,2270,511,533,1569,1567,2223,2221,2218,2215,1483,2211,1480,459,456,453,2232,449,474,491,1527,1525,1522,2475,2467,2465,2451,2449,2446,801,800,2426,2424,2421,2418,1723,2435,780,778,775,2387,2385,2382,2379,1695,2375,1693,2396,735,733,730,727,749,1718,2616,2615,2604,2603,2601,2584,2583,2581,2579,1800,2591,2550,2549,2547,2545,1792,2542,1790,2558,929,2719,1841,2710,2708,1833,1831,2690,2688,2686,1815,1809,1808,1774,1756,1754,1737,1736,1734,1739,1816,1711,1676,1674,633,629,1638,1636,1633,1641,598,1605,1604,1602,1600,605,1609,1607,2327,887,853,1775,822,820,1757,1755,1584,524,1560,1558,468,464,1514,1511,1508,1519,408,404,400,1452,1447,1444,417,1458,1455,2208,364,361,358,2154,1401,1400,1398,1396,374,1393,371,1408,1406,1403,1413,2173,2172,772,726,723,1712,672,669,666,682,1678,1675,625,623,621,618,2331,636,632,1639,1637,1635,920,918,884,880,889,849,848,847,846,2497,855,852,1776,2641,2742,2787,1380,334,1367,1365,301,297,1340,1338,1335,1343,255,251,247,1296,1291,1288,265,1302,1299,2113,204,196,192,2042,1232,1230,1224,214,1220,210,1242,1239,1235,1250,2077,2075,151,148,1993,144,1990,1163,1162,1160,1158,1155,161,1152,157,1173,1171,1168,1165,168,1181,1178,2021,2020,2018,2023,585,560,557,1585,516,509,1562,1559,458,447,2227,472,1516,1513,1510,398,396,393,390,2181,386,2178,407,1453,1451,1449,1446,420,1460,2209,769,764,720,712,2391,729,1713,664,663,661,659,2352,656,2349,671,1679,1677,2553,922,919,2519,2516,885,883,881,2685,2661,2659,2767,2756,2755,140,1137,1136,130,127,1125,1124,1122,1127,109,106,102,1103,1102,1100,1098,116,1107,1105,1980,80,76,73,1947,1068,1067,1065,1063,90,1060,87,1075,1073,1070,1080,1966,1965,46,43,40,1912,36,1909,1019,1018,1016,1014,58,1011,55,1008,51,1029,1027,1024,1021,63,1037,1034,1940,1939,1937,1942,8,1866,4,1863,1,1860,956,954,952,949,946,17,14,969,967,964,961,27,957,24,979,976,972,1901,1900,1898,1896,986,1905,1903,350,349,1381,329,327,324,1368,1366,292,290,287,284,2118,304,1341,1339,1337,1345,243,240,237,2086,233,2083,254,1297,1295,1293,1290,1304,2114,190,187,184,2034,180,2031,177,2027,199,1233,1231,1229,1226,217,1223,1241,2078,2076,584,555,554,552,550,2282,562,1586,507,506,504,502,2257,499,2254,515,1563,1561,445,443,441,2219,438,2216,435,2212,460,454,475,1517,1515,1512,2447,798,797,2422,2419,770,768,766,2383,2380,2376,721,719,717,714,731,1714,2602,2582,2580,2548,2546,2543,923,921,2717,2706,2705,2683,2682,2680,1771,1752,1750,1733,1732,1731,1735,1814,1707,1670,1668,1631,1629,1626,1634,1599,1598,1596,1594,1603,1601,2326,1772,1753,1751,1581,1554,1552,1504,1501,1498,1509,1442,1437,1434,401,1448,1445,2206,1392,1391,1389,1387,1384,359,1399,1397,1394,1404,2171,2170,1708,1672,1669,619,1632,1630,1628,1773,1378,1363,1361,1333,1328,1336,1286,1281,1278,248,1292,1289,2111,1218,1216,1210,197,1206,193,1228,1225,1221,1236,2073,2071,1151,1150,1148,1146,152,1143,149,1140,145,1161,1159,1156,1153,158,1169,1166,2017,2016,2014,2019,1582,510,1556,1553,452,448,1506,1500,394,391,387,1443,1441,1439,1436,1450,2207,765,716,713,1709,662,660,657,1673,1671,916,914,879,878,877,882,1135,1134,1121,1120,1118,1123,1097,1096,1094,1092,103,1101,1099,1979,1059,1058,1056,1054,77,1051,74,1066,1064,1061,1071,1964,1963,1007,1006,1004,1002,999,41,996,37,1017,1015,1012,1009,52,1025,1022,1936,1935,1933,1938,942,940,938,935,932,5,2,955,953,950,947,18,943,15,965,962,958,1895,1894,1892,1890,973,1899,1897,1379,325,1364,1362,288,285,1334,1332,1330,241,238,234,1287,1285,1283,1280,1294,2112,188,185,181,178,2028,1219,1217,1215,1212,200,1209,1227,2074,2072,583,553,551,1583,505,503,500,513,1557,1555,444,442,439,436,2213,455,451,1507,1505,1502,796,763,762,760,767,711,710,708,706,2377,718,715,1710,2544,917,915,2681,1627,1597,1595,2325,1769,1749,1747,1499,1438,1435,2204,1390,1388,1385,1395,2169,2167,1704,1665,1662,1625,1623,1620,1770,1329,1282,1279,2109,1214,1207,1222,2068,2065,1149,1147,1144,1141,146,1157,1154,2013,2011,2008,2015,1579,1549,1546,1495,1487,1433,1431,1428,1425,388,1440,2205,1705,658,1667,1664,1119,1095,1093,1978,1057,1055,1052,1062,1962,1960,1005,1003,1e3,997,38,1013,1010,1932,1930,1927,1934,941,939,936,933,6,930,3,951,948,944,1889,1887,1884,1881,959,1893,1891,35,1377,1360,1358,1327,1325,1322,1331,1277,1275,1272,1269,235,1284,2110,1205,1204,1201,1198,182,1195,179,1213,2070,2067,1580,501,1551,1548,440,437,1497,1494,1490,1503,761,709,707,1706,913,912,2198,1386,2164,2161,1621,1766,2103,1208,2058,2054,1145,1142,2005,2002,1999,2009,1488,1429,1426,2200,1698,1659,1656,1975,1053,1957,1954,1001,998,1924,1921,1918,1928,937,934,931,1879,1876,1873,1870,945,1885,1882,1323,1273,1270,2105,1202,1199,1196,1211,2061,2057,1576,1543,1540,1484,1481,1478,1491,1700]);class Wu{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class ze{static detectMultiple(e,n,i){let s=e.getBlackMatrix(),a=ze.detect(i,s);return a.length||(s=s.clone(),s.rotate180(),a=ze.detect(i,s)),new Wu(s,a)}static detect(e,n){const i=new Array;let s=0,a=0,l=!1;for(;s<n.getHeight();){const d=ze.findVertices(n,s,a);if(d[0]==null&&d[3]==null){if(!l)break;l=!1,a=0;for(const h of i)h[1]!=null&&(s=Math.trunc(Math.max(s,h[1].getY()))),h[3]!=null&&(s=Math.max(s,Math.trunc(h[3].getY())));s+=ze.ROW_STEP;continue}if(l=!0,i.push(d),!e)break;d[2]!=null?(a=Math.trunc(d[2].getX()),s=Math.trunc(d[2].getY())):(a=Math.trunc(d[4].getX()),s=Math.trunc(d[4].getY()))}return i}static findVertices(e,n,i){const s=e.getHeight(),a=e.getWidth(),l=new Array(8);return ze.copyToResult(l,ze.findRowsWithPattern(e,s,a,n,i,ze.START_PATTERN),ze.INDEXES_START_PATTERN),l[4]!=null&&(i=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),ze.copyToResult(l,ze.findRowsWithPattern(e,s,a,n,i,ze.STOP_PATTERN),ze.INDEXES_STOP_PATTERN),l}static copyToResult(e,n,i){for(let s=0;s<i.length;s++)e[i[s]]=n[s]}static findRowsWithPattern(e,n,i,s,a,l){const d=new Array(4);let h=!1;const p=new Int32Array(l.length);for(;s<n;s+=ze.ROW_STEP){let E=ze.findGuardPattern(e,a,s,i,!1,l,p);if(E!=null){for(;s>0;){const I=ze.findGuardPattern(e,a,--s,i,!1,l,p);if(I!=null)E=I;else{s++;break}}d[0]=new ve(E[0],s),d[1]=new ve(E[1],s),h=!0;break}}let y=s+1;if(h){let E=0,I=Int32Array.from([Math.trunc(d[0].getX()),Math.trunc(d[1].getX())]);for(;y<n;y++){const k=ze.findGuardPattern(e,I[0],y,i,!1,l,p);if(k!=null&&Math.abs(I[0]-k[0])<ze.MAX_PATTERN_DRIFT&&Math.abs(I[1]-k[1])<ze.MAX_PATTERN_DRIFT)I=k,E=0;else{if(E>ze.SKIPPED_ROW_COUNT_MAX)break;E++}}y-=E+1,d[2]=new ve(I[0],y),d[3]=new ve(I[1],y)}return y-s<ze.BARCODE_MIN_HEIGHT&&Z.fill(d,null),d}static findGuardPattern(e,n,i,s,a,l,d){Z.fillWithin(d,0,d.length,0);let h=n,p=0;for(;e.get(h,i)&&h>0&&p++<ze.MAX_PIXEL_DRIFT;)h--;let y=h,E=0,I=l.length;for(let k=a;y<s;y++)if(e.get(y,i)!==k)d[E]++;else{if(E===I-1){if(ze.patternMatchVariance(d,l,ze.MAX_INDIVIDUAL_VARIANCE)<ze.MAX_AVG_VARIANCE)return new Int32Array([h,y]);h+=d[0]+d[1],D.arraycopy(d,2,d,0,E-1),d[E-1]=0,d[E]=0,E--}else E++;d[E]=1,k=!k}return E===I-1&&ze.patternMatchVariance(d,l,ze.MAX_INDIVIDUAL_VARIANCE)<ze.MAX_AVG_VARIANCE?new Int32Array([h,y-1]):null}static patternMatchVariance(e,n,i){let s=e.length,a=0,l=0;for(let p=0;p<s;p++)a+=e[p],l+=n[p];if(a<l)return 1/0;let d=a/l;i*=d;let h=0;for(let p=0;p<s;p++){let y=e[p],E=n[p]*d,I=y>E?y-E:E-y;if(I>i)return 1/0;h+=I}return h/a}}ze.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),ze.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),ze.MAX_AVG_VARIANCE=.42,ze.MAX_INDIVIDUAL_VARIANCE=.8,ze.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),ze.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),ze.MAX_PIXEL_DRIFT=3,ze.MAX_PATTERN_DRIFT=5,ze.SKIPPED_ROW_COUNT_MAX=25,ze.ROW_STEP=5,ze.BARCODE_MIN_HEIGHT=10;class Vt{constructor(e,n){if(n.length===0)throw new v;this.field=e;let i=n.length;if(i>1&&n[0]===0){let s=1;for(;s<i&&n[s]===0;)s++;s===i?this.coefficients=new Int32Array([0]):(this.coefficients=new Int32Array(i-s),D.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);if(e===1){let s=0;for(let a of this.coefficients)s=this.field.add(s,a);return s}let n=this.coefficients[0],i=this.coefficients.length;for(let s=1;s<i;s++)n=this.field.add(this.field.multiply(e,n),this.coefficients[s]);return n}add(e){if(!this.field.equals(e.field))throw new v("ModulusPolys do not have same ModulusGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,i=e.coefficients;if(n.length>i.length){let l=n;n=i,i=l}let s=new Int32Array(i.length),a=i.length-n.length;D.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=this.field.add(n[l-a],i[l]);return new Vt(this.field,s)}subtract(e){if(!this.field.equals(e.field))throw new v("ModulusPolys do not have same ModulusGF field");return e.isZero()?this:this.add(e.negative())}multiply(e){return e instanceof Vt?this.multiplyOther(e):this.multiplyScalar(e)}multiplyOther(e){if(!this.field.equals(e.field))throw new v("ModulusPolys do not have same ModulusGF field");if(this.isZero()||e.isZero())return new Vt(this.field,new Int32Array([0]));let n=this.coefficients,i=n.length,s=e.coefficients,a=s.length,l=new Int32Array(i+a-1);for(let d=0;d<i;d++){let h=n[d];for(let p=0;p<a;p++)l[d+p]=this.field.add(l[d+p],this.field.multiply(h,s[p]))}return new Vt(this.field,l)}negative(){let e=this.coefficients.length,n=new Int32Array(e);for(let i=0;i<e;i++)n[i]=this.field.subtract(0,this.coefficients[i]);return new Vt(this.field,n)}multiplyScalar(e){if(e===0)return new Vt(this.field,new Int32Array([0]));if(e===1)return this;let n=this.coefficients.length,i=new Int32Array(n);for(let s=0;s<n;s++)i[s]=this.field.multiply(this.coefficients[s],e);return new Vt(this.field,i)}multiplyByMonomial(e,n){if(e<0)throw new v;if(n===0)return new Vt(this.field,new Int32Array([0]));let i=this.coefficients.length,s=new Int32Array(i+e);for(let a=0;a<i;a++)s[a]=this.field.multiply(this.coefficients[a],n);return new Vt(this.field,s)}toString(){let e=new xe;for(let n=this.getDegree();n>=0;n--){let i=this.getCoefficient(n);i!==0&&(i<0?(e.append(" - "),i=-i):e.length()>0&&e.append(" + "),(n===0||i!==1)&&e.append(i),n!==0&&(n===1?e.append("x"):(e.append("x^"),e.append(n))))}return e.toString()}}class ju{add(e,n){return(e+n)%this.modulus}subtract(e,n){return(this.modulus+e-n)%this.modulus}exp(e){return this.expTable[e]}log(e){if(e===0)throw new v;return this.logTable[e]}inverse(e){if(e===0)throw new yt;return this.expTable[this.modulus-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.modulus-1)]}getSize(){return this.modulus}equals(e){return e===this}}class Xi extends ju{constructor(e,n){super(),this.modulus=e,this.expTable=new Int32Array(e),this.logTable=new Int32Array(e);let i=1;for(let s=0;s<e;s++)this.expTable[s]=i,i=i*n%e;for(let s=0;s<e-1;s++)this.logTable[this.expTable[s]]=s;this.zero=new Vt(this,new Int32Array([0])),this.one=new Vt(this,new Int32Array([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new v;if(n===0)return this.zero;let i=new Int32Array(e+1);return i[0]=n,new Vt(this,i)}}Xi.PDF417_GF=new Xi(De.NUMBER_OF_CODEWORDS,3);class ss{constructor(){this.field=Xi.PDF417_GF}decode(e,n,i){let s=new Vt(this.field,e),a=new Int32Array(n),l=!1;for(let L=n;L>0;L--){let F=s.evaluateAt(this.field.exp(L));a[n-L]=F,F!==0&&(l=!0)}if(!l)return 0;let d=this.field.getOne();if(i!=null)for(const L of i){let F=this.field.exp(e.length-1-L),H=new Vt(this.field,new Int32Array([this.field.subtract(0,F),1]));d=d.multiply(H)}let h=new Vt(this.field,a),p=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),y=p[0],E=p[1],I=this.findErrorLocations(y),k=this.findErrorMagnitudes(E,y,I);for(let L=0;L<I.length;L++){let F=e.length-1-this.field.log(I[L]);if(F<0)throw O.getChecksumInstance();e[F]=this.field.subtract(e[F],k[L])}return I.length}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){let I=e;e=n,n=I}let s=e,a=n,l=this.field.getZero(),d=this.field.getOne();for(;a.getDegree()>=Math.round(i/2);){let I=s,k=l;if(s=a,l=d,s.isZero())throw O.getChecksumInstance();a=I;let L=this.field.getZero(),F=s.getCoefficient(s.getDegree()),H=this.field.inverse(F);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let Y=a.getDegree()-s.getDegree(),le=this.field.multiply(a.getCoefficient(a.getDegree()),H);L=L.add(this.field.buildMonomial(Y,le)),a=a.subtract(s.multiplyByMonomial(Y,le))}d=L.multiply(l).subtract(k).negative()}let h=d.getCoefficient(0);if(h===0)throw O.getChecksumInstance();let p=this.field.inverse(h),y=d.multiply(p),E=a.multiply(p);return[y,E]}findErrorLocations(e){let n=e.getDegree(),i=new Int32Array(n),s=0;for(let a=1;a<this.field.getSize()&&s<n;a++)e.evaluateAt(a)===0&&(i[s]=this.field.inverse(a),s++);if(s!==n)throw O.getChecksumInstance();return i}findErrorMagnitudes(e,n,i){let s=n.getDegree(),a=new Int32Array(s);for(let p=1;p<=s;p++)a[s-p]=this.field.multiply(p,n.getCoefficient(p));let l=new Vt(this.field,a),d=i.length,h=new Int32Array(d);for(let p=0;p<d;p++){let y=this.field.inverse(i[p]),E=this.field.subtract(0,e.evaluateAt(y)),I=this.field.inverse(l.evaluateAt(y));h[p]=this.field.multiply(E,I)}return h}}class sr{constructor(e,n,i,s,a){e instanceof sr?this.constructor_2(e):this.constructor_1(e,n,i,s,a)}constructor_1(e,n,i,s,a){const l=n==null||i==null,d=s==null||a==null;if(l&&d)throw new $;l?(n=new ve(0,s.getY()),i=new ve(0,a.getY())):d&&(s=new ve(e.getWidth()-1,n.getY()),a=new ve(e.getWidth()-1,i.getY())),this.image=e,this.topLeft=n,this.bottomLeft=i,this.topRight=s,this.bottomRight=a,this.minX=Math.trunc(Math.min(n.getX(),i.getX())),this.maxX=Math.trunc(Math.max(s.getX(),a.getX())),this.minY=Math.trunc(Math.min(n.getY(),s.getY())),this.maxY=Math.trunc(Math.max(i.getY(),a.getY()))}constructor_2(e){this.image=e.image,this.topLeft=e.getTopLeft(),this.bottomLeft=e.getBottomLeft(),this.topRight=e.getTopRight(),this.bottomRight=e.getBottomRight(),this.minX=e.getMinX(),this.maxX=e.getMaxX(),this.minY=e.getMinY(),this.maxY=e.getMaxY()}static merge(e,n){return e==null?n:n==null?e:new sr(e.image,e.topLeft,e.bottomLeft,n.topRight,n.bottomRight)}addMissingRows(e,n,i){let s=this.topLeft,a=this.bottomLeft,l=this.topRight,d=this.bottomRight;if(e>0){let h=i?this.topLeft:this.topRight,p=Math.trunc(h.getY()-e);p<0&&(p=0);let y=new ve(h.getX(),p);i?s=y:l=y}if(n>0){let h=i?this.bottomLeft:this.bottomRight,p=Math.trunc(h.getY()+n);p>=this.image.getHeight()&&(p=this.image.getHeight()-1);let y=new ve(h.getX(),p);i?a=y:d=y}return new sr(this.image,s,a,l,d)}getMinX(){return this.minX}getMaxX(){return this.maxX}getMinY(){return this.minY}getMaxY(){return this.maxY}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}getBottomLeft(){return this.bottomLeft}getBottomRight(){return this.bottomRight}}class Gu{constructor(e,n,i,s){this.columnCount=e,this.errorCorrectionLevel=s,this.rowCountUpperPart=n,this.rowCountLowerPart=i,this.rowCount=n+i}getColumnCount(){return this.columnCount}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getRowCount(){return this.rowCount}getRowCountUpperPart(){return this.rowCountUpperPart}getRowCountLowerPart(){return this.rowCountLowerPart}}class Rr{constructor(){this.buffer=""}static form(e,n){let i=-1;function s(l,d,h,p,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,k;switch(E){case"s":k=n[i];break;case"c":k=n[i][0];break;case"f":k=parseFloat(n[i]).toFixed(l);break;case"p":k=parseFloat(n[i]).toPrecision(l);break;case"e":k=parseFloat(n[i]).toExponential(l);break;case"x":k=parseInt(n[i]).toString(I||16);break;case"d":k=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}k=typeof k=="object"?JSON.stringify(k):(+k).toString(I);let L=parseInt(h),F=h&&h[0]+""=="0"?"0":" ";for(;k.length<L;)k=d!==void 0?k+F:F+k;return k}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=Rr.form(e,n)}toString(){return this.buffer}}class Mr{constructor(e){this.boundingBox=new sr(e),this.codewords=new Array(e.getMaxY()-e.getMinY()+1)}getCodewordNearby(e){let n=this.getCodeword(e);if(n!=null)return n;for(let i=1;i<Mr.MAX_NEARBY_DISTANCE;i++){let s=this.imageRowToCodewordIndex(e)-i;if(s>=0&&(n=this.codewords[s],n!=null)||(s=this.imageRowToCodewordIndex(e)+i,s<this.codewords.length&&(n=this.codewords[s],n!=null)))return n}return null}imageRowToCodewordIndex(e){return e-this.boundingBox.getMinY()}setCodeword(e,n){this.codewords[this.imageRowToCodewordIndex(e)]=n}getCodeword(e){return this.codewords[this.imageRowToCodewordIndex(e)]}getBoundingBox(){return this.boundingBox}getCodewords(){return this.codewords}toString(){const e=new Rr;let n=0;for(const i of this.codewords){if(i==null){e.format("%3d: | %n",n++);continue}e.format("%3d: %3d|%3d%n",n++,i.getRowNumber(),i.getValue())}return e.toString()}}Mr.MAX_NEARBY_DISTANCE=5;class Dr{constructor(){this.values=new Map}setValue(e){e=Math.trunc(e);let n=this.values.get(e);n==null&&(n=0),n++,this.values.set(e,n)}getValue(){let e=-1,n=new Array;for(const[i,s]of this.values.entries()){const a={getKey:()=>i,getValue:()=>s};a.getValue()>e?(e=a.getValue(),n=[],n.push(a.getKey())):a.getValue()===e&&n.push(a.getKey())}return De.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class as extends Mr{constructor(e,n){super(e),this._isLeft=n}setRowNumbers(){for(let e of this.getCodewords())e?.setRowNumberAsRowIndicatorColumn()}adjustCompleteIndicatorColumnRowNumbers(e){let n=this.getCodewords();this.setRowNumbers(),this.removeIncorrectCodewords(n,e);let i=this.getBoundingBox(),s=this._isLeft?i.getTopLeft():i.getTopRight(),a=this._isLeft?i.getBottomLeft():i.getBottomRight(),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.imageRowToCodewordIndex(Math.trunc(a.getY())),h=-1,p=1,y=0;for(let E=l;E<d;E++){if(n[E]==null)continue;let I=n[E],k=I.getRowNumber()-h;if(k===0)y++;else if(k===1)p=Math.max(p,y),y=1,h=I.getRowNumber();else if(k<0||I.getRowNumber()>=e.getRowCount()||k>E)n[E]=null;else{let L;p>2?L=(p-2)*k:L=k;let F=L>=E;for(let H=1;H<=L&&!F;H++)F=n[E-H]!=null;F?n[E]=null:(h=I.getRowNumber(),y=1)}}}getRowHeights(){let e=this.getBarcodeMetadata();if(e==null)return null;this.adjustIncompleteIndicatorColumnRowNumbers(e);let n=new Int32Array(e.getRowCount());for(let i of this.getCodewords())if(i!=null){let s=i.getRowNumber();if(s>=n.length)continue;n[s]++}return n}adjustIncompleteIndicatorColumnRowNumbers(e){let n=this.getBoundingBox(),i=this._isLeft?n.getTopLeft():n.getTopRight(),s=this._isLeft?n.getBottomLeft():n.getBottomRight(),a=this.imageRowToCodewordIndex(Math.trunc(i.getY())),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.getCodewords(),h=-1;for(let p=a;p<l;p++){if(d[p]==null)continue;let y=d[p];y.setRowNumberAsRowIndicatorColumn();let E=y.getRowNumber()-h;E===0||(E===1?h=y.getRowNumber():y.getRowNumber()>=e.getRowCount()?d[p]=null:h=y.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Dr,i=new Dr,s=new Dr,a=new Dr;for(let d of e){if(d==null)continue;d.setRowNumberAsRowIndicatorColumn();let h=d.getValue()%30,p=d.getRowNumber();switch(this._isLeft||(p+=2),p%3){case 0:i.setValue(h*3+1);break;case 1:a.setValue(h/3),s.setValue(h%3);break;case 2:n.setValue(h+1);break}}if(n.getValue().length===0||i.getValue().length===0||s.getValue().length===0||a.getValue().length===0||n.getValue()[0]<1||i.getValue()[0]+s.getValue()[0]<De.MIN_ROWS_IN_BARCODE||i.getValue()[0]+s.getValue()[0]>De.MAX_ROWS_IN_BARCODE)return null;let l=new Gu(n.getValue()[0],i.getValue()[0],s.getValue()[0],a.getValue()[0]);return this.removeIncorrectCodewords(e,l),l}removeIncorrectCodewords(e,n){for(let i=0;i<e.length;i++){let s=e[i];if(e[i]==null)continue;let a=s.getValue()%30,l=s.getRowNumber();if(l>n.getRowCount()){e[i]=null;continue}switch(this._isLeft||(l+=2),l%3){case 0:a*3+1!==n.getRowCountUpperPart()&&(e[i]=null);break;case 1:(Math.trunc(a/3)!==n.getErrorCorrectionLevel()||a%3!==n.getRowCountLowerPart())&&(e[i]=null);break;case 2:a+1!==n.getColumnCount()&&(e[i]=null);break}}}isLeft(){return this._isLeft}toString(){return"IsLeft: "+this._isLeft+`
63
- `+super.toString()}}class Pr{constructor(e,n){this.ADJUST_ROW_NUMBER_SKIP=2,this.barcodeMetadata=e,this.barcodeColumnCount=e.getColumnCount(),this.boundingBox=n,this.detectionResultColumns=new Array(this.barcodeColumnCount+2)}getDetectionResultColumns(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]),this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);let e=De.MAX_CODEWORDS_IN_BARCODE,n;do n=e,e=this.adjustRowNumbersAndGetCount();while(e>0&&e<n);return this.detectionResultColumns}adjustIndicatorColumnRowNumbers(e){e?.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata)}adjustRowNumbersAndGetCount(){let e=this.adjustRowNumbersByRow();if(e===0)return 0;for(let n=1;n<this.barcodeColumnCount+1;n++){let i=this.detectionResultColumns[n].getCodewords();for(let s=0;s<i.length;s++)i[s]!=null&&(i[s].hasValidRowNumber()||this.adjustRowNumbers(n,s,i))}return e}adjustRowNumbersByRow(){return this.adjustRowNumbersFromBothRI(),this.adjustRowNumbersFromLRI()+this.adjustRowNumbersFromRRI()}adjustRowNumbersFromBothRI(){if(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null)return;let e=this.detectionResultColumns[0].getCodewords(),n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<e.length;i++)if(e[i]!=null&&n[i]!=null&&e[i].getRowNumber()===n[i].getRowNumber())for(let s=1;s<=this.barcodeColumnCount;s++){let a=this.detectionResultColumns[s].getCodewords()[i];a!=null&&(a.setRowNumber(e[i].getRowNumber()),a.hasValidRowNumber()||(this.detectionResultColumns[s].getCodewords()[i]=null))}}adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null)return 0;let e=0,n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=this.barcodeColumnCount+1;l>0&&a<this.ADJUST_ROW_NUMBER_SKIP;l--){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null)return 0;let e=0,n=this.detectionResultColumns[0].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=1;l<this.barcodeColumnCount+1&&a<this.ADJUST_ROW_NUMBER_SKIP;l++){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}static adjustRowNumberIfValid(e,n,i){return i==null||i.hasValidRowNumber()||(i.isValidRowNumber(e)?(i.setRowNumber(e),n=0):++n),n}adjustRowNumbers(e,n,i){if(!this.detectionResultColumns[e-1])return;let s=i[n],a=this.detectionResultColumns[e-1].getCodewords(),l=a;this.detectionResultColumns[e+1]!=null&&(l=this.detectionResultColumns[e+1].getCodewords());let d=new Array(14);d[2]=a[n],d[3]=l[n],n>0&&(d[0]=i[n-1],d[4]=a[n-1],d[5]=l[n-1]),n>1&&(d[8]=i[n-2],d[10]=a[n-2],d[11]=l[n-2]),n<i.length-1&&(d[1]=i[n+1],d[6]=a[n+1],d[7]=l[n+1]),n<i.length-2&&(d[9]=i[n+2],d[12]=a[n+2],d[13]=l[n+2]);for(let h of d)if(Pr.adjustRowNumber(s,h))return}static adjustRowNumber(e,n){return n==null?!1:n.hasValidRowNumber()&&n.getBucket()===e.getBucket()?(e.setRowNumber(n.getRowNumber()),!0):!1}getBarcodeColumnCount(){return this.barcodeColumnCount}getBarcodeRowCount(){return this.barcodeMetadata.getRowCount()}getBarcodeECLevel(){return this.barcodeMetadata.getErrorCorrectionLevel()}setBoundingBox(e){this.boundingBox=e}getBoundingBox(){return this.boundingBox}setDetectionResultColumn(e,n){this.detectionResultColumns[e]=n}getDetectionResultColumn(e){return this.detectionResultColumns[e]}toString(){let e=this.detectionResultColumns[0];e==null&&(e=this.detectionResultColumns[this.barcodeColumnCount+1]);let n=new Rr;for(let i=0;i<e.getCodewords().length;i++){n.format("CW %3d:",i);for(let s=0;s<this.barcodeColumnCount+2;s++){if(this.detectionResultColumns[s]==null){n.format(" | ");continue}let a=this.detectionResultColumns[s].getCodewords()[i];if(a==null){n.format(" | ");continue}n.format(" %3d|%3d",a.getRowNumber(),a.getValue())}n.format("%n")}return n.toString()}}class Br{constructor(e,n,i,s){this.rowNumber=Br.BARCODE_ROW_UNKNOWN,this.startX=Math.trunc(e),this.endX=Math.trunc(n),this.bucket=Math.trunc(i),this.value=Math.trunc(s)}hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber)}isValidRowNumber(e){return e!==Br.BARCODE_ROW_UNKNOWN&&this.bucket===e%3*3}setRowNumberAsRowIndicatorColumn(){this.rowNumber=Math.trunc(Math.trunc(this.value/30)*3+Math.trunc(this.bucket/3))}getWidth(){return this.endX-this.startX}getStartX(){return this.startX}getEndX(){return this.endX}getBucket(){return this.bucket}getValue(){return this.value}getRowNumber(){return this.rowNumber}setRowNumber(e){this.rowNumber=e}toString(){return this.rowNumber+"|"+this.value}}Br.BARCODE_ROW_UNKNOWN=-1;class tn{static initialize(){for(let e=0;e<De.SYMBOL_TABLE.length;e++){let n=De.SYMBOL_TABLE[e],i=n&1;for(let s=0;s<De.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===i;)a+=1,n>>=1;i=n&1,tn.RATIOS_TABLE[e]||(tn.RATIOS_TABLE[e]=new Array(De.BARS_IN_MODULE)),tn.RATIOS_TABLE[e][De.BARS_IN_MODULE-s-1]=Math.fround(a/De.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=tn.getDecodedCodewordValue(tn.sampleBitCounts(e));return n!==-1?n:tn.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=Ze.sum(e),i=new Int32Array(De.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<De.MODULES_IN_CODEWORD;l++){let d=n/(2*De.MODULES_IN_CODEWORD)+l*n/De.MODULES_IN_CODEWORD;a+e[s]<=d&&(a+=e[s],s++),i[s]++}return i}static getDecodedCodewordValue(e){let n=tn.getBitValue(e);return De.getCodeword(n)===-1?-1:n}static getBitValue(e){let n=0;for(let i=0;i<e.length;i++)for(let s=0;s<e[i];s++)n=n<<1|(i%2===0?1:0);return Math.trunc(n)}static getClosestDecodedValue(e){let n=Ze.sum(e),i=new Array(De.BARS_IN_MODULE);if(n>1)for(let l=0;l<i.length;l++)i[l]=Math.fround(e[l]/n);let s=Sn.MAX_VALUE,a=-1;this.bSymbolTableReady||tn.initialize();for(let l=0;l<tn.RATIOS_TABLE.length;l++){let d=0,h=tn.RATIOS_TABLE[l];for(let p=0;p<De.BARS_IN_MODULE;p++){let y=Math.fround(h[p]-i[p]);if(d+=Math.fround(y*y),d>=s)break}d<s&&(s=d,a=De.SYMBOL_TABLE[l])}return a}}tn.bSymbolTableReady=!1,tn.RATIOS_TABLE=new Array(De.SYMBOL_TABLE.length).map(b=>new Array(De.BARS_IN_MODULE));class ls{constructor(){this.segmentCount=-1,this.fileSize=-1,this.timestamp=-1,this.checksum=-1}getSegmentIndex(){return this.segmentIndex}setSegmentIndex(e){this.segmentIndex=e}getFileId(){return this.fileId}setFileId(e){this.fileId=e}getOptionalData(){return this.optionalData}setOptionalData(e){this.optionalData=e}isLastSegment(){return this.lastSegment}setLastSegment(e){this.lastSegment=e}getSegmentCount(){return this.segmentCount}setSegmentCount(e){this.segmentCount=e}getSender(){return this.sender||null}setSender(e){this.sender=e}getAddressee(){return this.addressee||null}setAddressee(e){this.addressee=e}getFileName(){return this.fileName}setFileName(e){this.fileName=e}getFileSize(){return this.fileSize}setFileSize(e){this.fileSize=e}getChecksum(){return this.checksum}setChecksum(e){this.checksum=e}getTimestamp(){return this.timestamp}setTimestamp(e){this.timestamp=e}}class cs{static parseLong(e,n=void 0){return parseInt(e,n)}}class us extends x{}us.kind="NullPointerException";class Xu{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,i){if(e==null)throw new us;if(n<0||n>e.length||i<0||n+i>e.length||n+i<0)throw new B;if(i===0)return;for(let s=0;s<i;s++)this.write(e[n+s])}flush(){}close(){}}class qu extends x{}class Yu extends Xu{constructor(e=32){if(super(),this.count=0,e<0)throw new v("Negative initial size: "+e);this.buf=new Uint8Array(e)}ensureCapacity(e){e-this.buf.length>0&&this.grow(e)}grow(e){let i=this.buf.length<<1;if(i-e<0&&(i=e),i<0){if(e<0)throw new qu;i=z.MAX_VALUE}this.buf=Z.copyOfUint8Array(this.buf,i)}write(e){this.ensureCapacity(this.count+1),this.buf[this.count]=e,this.count+=1}writeBytesOffset(e,n,i){if(n<0||n>e.length||i<0||n+i-e.length>0)throw new B;this.ensureCapacity(this.count+i),D.arraycopy(e,n,this.buf,this.count,i),this.count+=i}writeTo(e){e.writeBytesOffset(this.buf,0,this.count)}reset(){this.count=0}toByteArray(){return Z.copyOfUint8Array(this.buf,this.count)}size(){return this.count}toString(e){return e?typeof e=="string"?this.toString_string(e):this.toString_number(e):this.toString_void()}toString_void(){return new String(this.buf).toString()}toString_string(e){return new String(this.buf).toString()}toString_number(e){return new String(this.buf).toString()}close(){}}var it;(function(b){b[b.ALPHA=0]="ALPHA",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.PUNCT=3]="PUNCT",b[b.ALPHA_SHIFT=4]="ALPHA_SHIFT",b[b.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(it||(it={}));function ds(){if(typeof window<"u")return window.BigInt||null;if(typeof bi<"u")return bi.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let ci;function Yn(b){if(typeof ci>"u"&&(ci=ds()),ci===null)throw new Error("BigInt is not supported!");return ci(b)}function Ku(){let b=[];b[0]=Yn(1);let e=Yn(900);b[1]=e;for(let n=2;n<16;n++)b[n]=b[n-1]*e;return b}class q{static decode(e,n){let i=new xe(""),s=S.ISO8859_1;i.enableDecoding(s);let a=1,l=e[a++],d=new ls;for(;a<e[0];){switch(l){case q.TEXT_COMPACTION_MODE_LATCH:a=q.textCompaction(e,a,i);break;case q.BYTE_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:a=q.byteCompaction(l,e,s,a,i);break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:i.append(e[a++]);break;case q.NUMERIC_COMPACTION_MODE_LATCH:a=q.numericCompaction(e,a,i);break;case q.ECI_CHARSET:S.getCharacterSetECIByValue(e[a++]);break;case q.ECI_GENERAL_PURPOSE:a+=2;break;case q.ECI_USER_DEFINED:a++;break;case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:a=q.decodeMacroBlock(e,a,d);break;case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:throw new U;default:a--,a=q.textCompaction(e,a,i);break}if(a<e.length)l=e[a++];else throw U.getFormatInstance()}if(i.length()===0)throw U.getFormatInstance();let h=new Ht(null,i.toString(),null,n);return h.setOther(d),h}static decodeMacroBlock(e,n,i){if(n+q.NUMBER_OF_SEQUENCE_CODEWORDS>e[0])throw U.getFormatInstance();let s=new Int32Array(q.NUMBER_OF_SEQUENCE_CODEWORDS);for(let d=0;d<q.NUMBER_OF_SEQUENCE_CODEWORDS;d++,n++)s[d]=e[n];i.setSegmentIndex(z.parseInt(q.decodeBase900toBase10(s,q.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new xe;n=q.textCompaction(e,n,a),i.setFileId(a.toString());let l=-1;for(e[n]===q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<e[0];)switch(e[n]){case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,e[n]){case q.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let d=new xe;n=q.textCompaction(e,n+1,d),i.setFileName(d.toString());break;case q.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new xe;n=q.textCompaction(e,n+1,h),i.setSender(h.toString());break;case q.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new xe;n=q.textCompaction(e,n+1,p),i.setAddressee(p.toString());break;case q.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new xe;n=q.numericCompaction(e,n+1,y),i.setSegmentCount(z.parseInt(y.toString()));break;case q.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let E=new xe;n=q.numericCompaction(e,n+1,E),i.setTimestamp(cs.parseLong(E.toString()));break;case q.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new xe;n=q.numericCompaction(e,n+1,I),i.setChecksum(z.parseInt(I.toString()));break;case q.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let k=new xe;n=q.numericCompaction(e,n+1,k),i.setFileSize(cs.parseLong(k.toString()));break;default:throw U.getFormatInstance()}break;case q.MACRO_PDF417_TERMINATOR:n++,i.setLastSegment(!0);break;default:throw U.getFormatInstance()}if(l!==-1){let d=n-l;i.isLastSegment()&&d--,i.setOptionalData(Z.copyOfRange(e,l,l+d))}return n}static textCompaction(e,n,i){let s=new Int32Array((e[0]-n)*2),a=new Int32Array((e[0]-n)*2),l=0,d=!1;for(;n<e[0]&&!d;){let h=e[n++];if(h<q.TEXT_COMPACTION_MODE_LATCH)s[l]=h/30,s[l+1]=h%30,l+=2;else switch(h){case q.TEXT_COMPACTION_MODE_LATCH:s[l++]=q.TEXT_COMPACTION_MODE_LATCH;break;case q.BYTE_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.NUMERIC_COMPACTION_MODE_LATCH:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:n--,d=!0;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s[l]=q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,h=e[n++],a[l]=h,l++;break}}return q.decodeTextCompaction(s,a,l,i),n}static decodeTextCompaction(e,n,i,s){let a=it.ALPHA,l=it.ALPHA,d=0;for(;d<i;){let h=e[d],p="";switch(a){case it.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case q.LL:a=it.LOWER;break;case q.ML:a=it.MIXED;break;case q.PS:l=a,a=it.PUNCT_SHIFT;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case q.AS:l=a,a=it.ALPHA_SHIFT;break;case q.ML:a=it.MIXED;break;case q.PS:l=a,a=it.PUNCT_SHIFT;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.MIXED:if(h<q.PL)p=q.MIXED_CHARS[h];else switch(h){case q.PL:a=it.PUNCT;break;case 26:p=" ";break;case q.LL:a=it.LOWER;break;case q.AL:a=it.ALPHA;break;case q.PS:l=a,a=it.PUNCT_SHIFT;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT:if(h<q.PAL)p=q.PUNCT_CHARS[h];else switch(h){case q.PAL:a=it.ALPHA;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.ALPHA_SHIFT:if(a=l,h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT_SHIFT:if(a=l,h<q.PAL)p=q.PUNCT_CHARS[h];else switch(h){case q.PAL:a=it.ALPHA;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break}p!==""&&s.append(p),d++}}static byteCompaction(e,n,i,s,a){let l=new Yu,d=0,h=0,p=!1;switch(e){case q.BYTE_COMPACTION_MODE_LATCH:let y=new Int32Array(6),E=n[s++];for(;s<n[0]&&!p;)switch(y[d++]=E,h=900*h+E,E=n[s++],E){case q.TEXT_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH:case q.NUMERIC_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:s--,p=!0;break;default:if(d%5===0&&d>0){for(let I=0;I<6;++I)l.write(Number(Yn(h)>>Yn(8*(5-I))));h=0,d=0}break}s===n[0]&&E<q.TEXT_COMPACTION_MODE_LATCH&&(y[d++]=E);for(let I=0;I<d;I++)l.write(y[I]);break;case q.BYTE_COMPACTION_MODE_LATCH_6:for(;s<n[0]&&!p;){let I=n[s++];if(I<q.TEXT_COMPACTION_MODE_LATCH)d++,h=900*h+I;else switch(I){case q.TEXT_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH:case q.NUMERIC_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:s--,p=!0;break}if(d%5===0&&d>0){for(let k=0;k<6;++k)l.write(Number(Yn(h)>>Yn(8*(5-k))));h=0,d=0}}break}return a.append(ye.decode(l.toByteArray(),i)),s}static numericCompaction(e,n,i){let s=0,a=!1,l=new Int32Array(q.MAX_NUMERIC_CODEWORDS);for(;n<e[0]&&!a;){let d=e[n++];if(n===e[0]&&(a=!0),d<q.TEXT_COMPACTION_MODE_LATCH)l[s]=d,s++;else switch(d){case q.TEXT_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:n--,a=!0;break}(s%q.MAX_NUMERIC_CODEWORDS===0||d===q.NUMERIC_COMPACTION_MODE_LATCH||a)&&s>0&&(i.append(q.decodeBase900toBase10(l,s)),s=0)}return n}static decodeBase900toBase10(e,n){let i=Yn(0);for(let a=0;a<n;a++)i+=q.EXP900[n-a-1]*Yn(e[a]);let s=i.toString();if(s.charAt(0)!=="1")throw new U;return s.substring(1)}}q.TEXT_COMPACTION_MODE_LATCH=900,q.BYTE_COMPACTION_MODE_LATCH=901,q.NUMERIC_COMPACTION_MODE_LATCH=902,q.BYTE_COMPACTION_MODE_LATCH_6=924,q.ECI_USER_DEFINED=925,q.ECI_GENERAL_PURPOSE=926,q.ECI_CHARSET=927,q.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,q.MACRO_PDF417_TERMINATOR=922,q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,q.MAX_NUMERIC_CODEWORDS=15,q.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,q.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,q.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,q.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,q.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,q.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,q.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,q.PL=25,q.LL=27,q.AS=27,q.ML=28,q.AL=28,q.PS=29,q.PAL=29,q.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,:
64
- -.$/"|*()?{}'`,q.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",q.EXP900=ds()?Ku():[],q.NUMBER_OF_SEQUENCE_CODEWORDS=2;class Ve{constructor(){}static decode(e,n,i,s,a,l,d){let h=new sr(e,n,i,s,a),p=null,y=null,E;for(let L=!0;;L=!1){if(n!=null&&(p=Ve.getRowIndicatorColumn(e,h,n,!0,l,d)),s!=null&&(y=Ve.getRowIndicatorColumn(e,h,s,!1,l,d)),E=Ve.merge(p,y),E==null)throw $.getNotFoundInstance();let F=E.getBoundingBox();if(L&&F!=null&&(F.getMinY()<h.getMinY()||F.getMaxY()>h.getMaxY()))h=F;else break}E.setBoundingBox(h);let I=E.getBarcodeColumnCount()+1;E.setDetectionResultColumn(0,p),E.setDetectionResultColumn(I,y);let k=p!=null;for(let L=1;L<=I;L++){let F=k?L:I-L;if(E.getDetectionResultColumn(F)!==void 0)continue;let H;F===0||F===I?H=new as(h,F===0):H=new Mr(h),E.setDetectionResultColumn(F,H);let Y=-1,le=Y;for(let ce=h.getMinY();ce<=h.getMaxY();ce++){if(Y=Ve.getStartColumn(E,F,ce,k),Y<0||Y>h.getMaxX()){if(le===-1)continue;Y=le}let ae=Ve.detectCodeword(e,h.getMinX(),h.getMaxX(),k,Y,ce,l,d);ae!=null&&(H.setCodeword(ce,ae),le=Y,l=Math.min(l,ae.getWidth()),d=Math.max(d,ae.getWidth()))}}return Ve.createDecoderResult(E)}static merge(e,n){if(e==null&&n==null)return null;let i=Ve.getBarcodeMetadata(e,n);if(i==null)return null;let s=sr.merge(Ve.adjustBoundingBox(e),Ve.adjustBoundingBox(n));return new Pr(i,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let i=Ve.getMax(n),s=0;for(let d of n)if(s+=i-d,d>0)break;let a=e.getCodewords();for(let d=0;s>0&&a[d]==null;d++)s--;let l=0;for(let d=n.length-1;d>=0&&(l+=i-n[d],!(n[d]>0));d--);for(let d=a.length-1;l>0&&a[d]==null;d--)l--;return e.getBoundingBox().addMissingRows(s,l,e.isLeft())}static getMax(e){let n=-1;for(let i of e)n=Math.max(n,i);return n}static getBarcodeMetadata(e,n){let i;if(e==null||(i=e.getBarcodeMetadata())==null)return n==null?null:n.getBarcodeMetadata();let s;return n==null||(s=n.getBarcodeMetadata())==null?i:i.getColumnCount()!==s.getColumnCount()&&i.getErrorCorrectionLevel()!==s.getErrorCorrectionLevel()&&i.getRowCount()!==s.getRowCount()?null:i}static getRowIndicatorColumn(e,n,i,s,a,l){let d=new as(n,s);for(let h=0;h<2;h++){let p=h===0?1:-1,y=Math.trunc(Math.trunc(i.getX()));for(let E=Math.trunc(Math.trunc(i.getY()));E<=n.getMaxY()&&E>=n.getMinY();E+=p){let I=Ve.detectCodeword(e,0,e.getWidth(),s,y,E,a,l);I!=null&&(d.setCodeword(E,I),s?y=I.getStartX():y=I.getEndX())}}return d}static adjustCodewordCount(e,n){let i=n[0][1],s=i.getValue(),a=e.getBarcodeColumnCount()*e.getBarcodeRowCount()-Ve.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>De.MAX_CODEWORDS_IN_BARCODE)throw $.getNotFoundInstance();i.setValue(a)}else s[0]!==a&&i.setValue(a)}static createDecoderResult(e){let n=Ve.createBarcodeMatrix(e);Ve.adjustCodewordCount(e,n);let i=new Array,s=new Int32Array(e.getBarcodeRowCount()*e.getBarcodeColumnCount()),a=[],l=new Array;for(let h=0;h<e.getBarcodeRowCount();h++)for(let p=0;p<e.getBarcodeColumnCount();p++){let y=n[h][p+1].getValue(),E=h*e.getBarcodeColumnCount()+p;y.length===0?i.push(E):y.length===1?s[E]=y[0]:(l.push(E),a.push(y))}let d=new Array(a.length);for(let h=0;h<d.length;h++)d[h]=a[h];return Ve.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,De.toIntArray(i),De.toIntArray(l),d)}static createDecoderResultFromAmbiguousValues(e,n,i,s,a){let l=new Int32Array(s.length),d=100;for(;d-- >0;){for(let h=0;h<l.length;h++)n[s[h]]=a[h][l[h]];try{return Ve.decodeCodewords(n,e,i)}catch(h){if(!(h instanceof O))throw h}if(l.length===0)throw O.getChecksumInstance();for(let h=0;h<l.length;h++)if(l[h]<a[h].length-1){l[h]++;break}else if(l[h]=0,h===l.length-1)throw O.getChecksumInstance()}throw O.getChecksumInstance()}static createBarcodeMatrix(e){let n=Array.from({length:e.getBarcodeRowCount()},()=>new Array(e.getBarcodeColumnCount()+2));for(let s=0;s<n.length;s++)for(let a=0;a<n[s].length;a++)n[s][a]=new Dr;let i=0;for(let s of e.getDetectionResultColumns()){if(s!=null){for(let a of s.getCodewords())if(a!=null){let l=a.getRowNumber();if(l>=0){if(l>=n.length)continue;n[l][i].setValue(a.getValue())}}}i++}return n}static isValidBarcodeColumn(e,n){return n>=0&&n<=e.getBarcodeColumnCount()+1}static getStartColumn(e,n,i,s){let a=s?1:-1,l=null;if(Ve.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodeword(i)),l!=null)return s?l.getEndX():l.getStartX();if(l=e.getDetectionResultColumn(n).getCodewordNearby(i),l!=null)return s?l.getStartX():l.getEndX();if(Ve.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(i)),l!=null)return s?l.getEndX():l.getStartX();let d=0;for(;Ve.isValidBarcodeColumn(e,n-a);){n-=a;for(let h of e.getDetectionResultColumn(n).getCodewords())if(h!=null)return(s?h.getEndX():h.getStartX())+a*d*(h.getEndX()-h.getStartX());d++}return s?e.getBoundingBox().getMinX():e.getBoundingBox().getMaxX()}static detectCodeword(e,n,i,s,a,l,d,h){a=Ve.adjustCodewordStartColumn(e,n,i,s,a,l);let p=Ve.getModuleBitCount(e,n,i,s,a,l);if(p==null)return null;let y,E=Ze.sum(p);if(s)y=a+E;else{for(let L=0;L<p.length/2;L++){let F=p[L];p[L]=p[p.length-1-L],p[p.length-1-L]=F}y=a,a=y-E}if(!Ve.checkCodewordSkew(E,d,h))return null;let I=tn.getDecodedValue(p),k=De.getCodeword(I);return k===-1?null:new Br(a,y,Ve.getCodewordBucketNumber(I),k)}static getModuleBitCount(e,n,i,s,a,l){let d=a,h=new Int32Array(8),p=0,y=s?1:-1,E=s;for(;(s?d<i:d>=n)&&p<h.length;)e.get(d,l)===E?(h[p]++,d+=y):(p++,E=!E);return p===h.length||d===(s?i:n)&&p===h.length-1?h:null}static getNumberOfECCodeWords(e){return 2<<e}static adjustCodewordStartColumn(e,n,i,s,a,l){let d=a,h=s?-1:1;for(let p=0;p<2;p++){for(;(s?d>=n:d<i)&&s===e.get(d,l);){if(Math.abs(a-d)>Ve.CODEWORD_SKEW_SIZE)return a;d+=h}h=-h,s=!s}return d}static checkCodewordSkew(e,n,i){return n-Ve.CODEWORD_SKEW_SIZE<=e&&e<=i+Ve.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,i){if(e.length===0)throw U.getFormatInstance();let s=1<<n+1,a=Ve.correctErrors(e,i,s);Ve.verifyCodewordCount(e,s);let l=q.decode(e,""+n);return l.setErrorsCorrected(a),l.setErasures(i.length),l}static correctErrors(e,n,i){if(n!=null&&n.length>i/2+Ve.MAX_ERRORS||i<0||i>Ve.MAX_EC_CODEWORDS)throw O.getChecksumInstance();return Ve.errorCorrection.decode(e,i,n)}static verifyCodewordCount(e,n){if(e.length<4)throw U.getFormatInstance();let i=e[0];if(i>e.length)throw U.getFormatInstance();if(i===0)if(n<e.length)e[0]=e.length-n;else throw U.getFormatInstance()}static getBitCountForCodeword(e){let n=new Int32Array(8),i=0,s=n.length-1;for(;!((e&1)!==i&&(i=e&1,s--,s<0));)n[s]++,e>>=1;return n}static getCodewordBucketNumber(e){return e instanceof Int32Array?this.getCodewordBucketNumber_Int32Array(e):this.getCodewordBucketNumber_number(e)}static getCodewordBucketNumber_number(e){return Ve.getCodewordBucketNumber(Ve.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new Rr;for(let i=0;i<e.length;i++){n.format("Row %2d: ",i);for(let s=0;s<e[i].length;s++){let a=e[i][s];a.getValue().length===0?n.format(" ",null):n.format("%4d(%2d)",a.getValue()[0],a.getConfidence(a.getValue()[0]))}n.format("%n")}return n.toString()}}Ve.CODEWORD_SKEW_SIZE=2,Ve.MAX_ERRORS=3,Ve.MAX_EC_CODEWORDS=512,Ve.errorCorrection=new ss;class Zt{decode(e,n=null){let i=Zt.decode(e,n,!1);if(i==null||i.length===0||i[0]==null)throw $.getNotFoundInstance();return i[0]}decodeMultiple(e,n=null){try{return Zt.decode(e,n,!0)}catch(i){throw i instanceof U||i instanceof O?$.getNotFoundInstance():i}}static decode(e,n,i){const s=new Array,a=ze.detectMultiple(e,n,i);for(const l of a.getPoints()){const d=Ve.decode(a.getBits(),l[4],l[5],l[6],l[7],Zt.getMinCodewordWidth(l),Zt.getMaxCodewordWidth(l)),h=new Ee(d.getText(),d.getRawBytes(),void 0,l,Ce.PDF_417);h.putMetadata(Ue.ERROR_CORRECTION_LEVEL,d.getECLevel());const p=d.getOther();p!=null&&h.putMetadata(Ue.PDF417_EXTRA_METADATA,p),s.push(h)}return s.map(l=>l)}static getMaxWidth(e,n){return e==null||n==null?0:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMinWidth(e,n){return e==null||n==null?z.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(Zt.getMaxWidth(e[0],e[4]),Zt.getMaxWidth(e[6],e[2])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN),Math.max(Zt.getMaxWidth(e[1],e[5]),Zt.getMaxWidth(e[7],e[3])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(Zt.getMinWidth(e[0],e[4]),Zt.getMinWidth(e[6],e[2])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN),Math.min(Zt.getMinWidth(e[1],e[5]),Zt.getMinWidth(e[7],e[3])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN)))}reset(){}}class ui extends x{}ui.kind="ReaderException";class fs{constructor(e,n){this.verbose=e===!0,n&&this.setHints(n)}decode(e,n){return n&&this.setHints(n),this.decodeInternal(e)}decodeWithState(e){return(this.readers===null||this.readers===void 0)&&this.setHints(null),this.decodeInternal(e)}setHints(e){this.hints=e;const n=!c(e)&&e.get(V.TRY_HARDER)===!0,i=c(e)?null:e.get(V.POSSIBLE_FORMATS),s=new Array;if(!c(i)){const a=i.some(l=>l===Ce.UPC_A||l===Ce.UPC_E||l===Ce.EAN_13||l===Ce.EAN_8||l===Ce.CODABAR||l===Ce.CODE_39||l===Ce.CODE_93||l===Ce.CODE_128||l===Ce.ITF||l===Ce.RSS_14||l===Ce.RSS_EXPANDED);a&&!n&&s.push(new vr(e,this.verbose)),i.includes(Ce.QR_CODE)&&s.push(new qn),i.includes(Ce.DATA_MATRIX)&&s.push(new Xn),i.includes(Ce.AZTEC)&&s.push(new lt),i.includes(Ce.PDF_417)&&s.push(new Zt),a&&n&&s.push(new vr(e,this.verbose))}s.length===0&&(n||s.push(new vr(e,this.verbose)),s.push(new qn),s.push(new Xn),s.push(new lt),s.push(new Zt),n&&s.push(new vr(e,this.verbose))),this.readers=s}reset(){if(this.readers!==null)for(const e of this.readers)e.reset()}decodeInternal(e){if(this.readers===null)throw new ui("No readers where selected, nothing can be read.");for(const n of this.readers)try{return n.decode(e,this.hints)}catch(i){if(i instanceof ui)continue}throw new $("No MultiFormat Readers were able to detect the code.")}}class Ju extends vt{constructor(e=null,n=500){const i=new fs;i.setHints(e),super(i,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class Qu extends vt{constructor(e=500){super(new Zt,e)}}class ed extends vt{constructor(e=500){super(new qn,e)}}var qi;(function(b){b[b.ERROR_CORRECTION=0]="ERROR_CORRECTION",b[b.CHARACTER_SET=1]="CHARACTER_SET",b[b.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",b[b.MIN_SIZE=3]="MIN_SIZE",b[b.MAX_SIZE=4]="MAX_SIZE",b[b.MARGIN=5]="MARGIN",b[b.PDF417_COMPACT=6]="PDF417_COMPACT",b[b.PDF417_COMPACTION=7]="PDF417_COMPACTION",b[b.PDF417_DIMENSIONS=8]="PDF417_DIMENSIONS",b[b.AZTEC_LAYERS=9]="AZTEC_LAYERS",b[b.QR_VERSION=10]="QR_VERSION"})(qi||(qi={}));var Dt=qi;class Yi{constructor(e){this.field=e,this.cachedGenerators=[],this.cachedGenerators.push(new Oe(e,Int32Array.from([1])))}buildGenerator(e){const n=this.cachedGenerators;if(e>=n.length){let i=n[n.length-1];const s=this.field;for(let a=n.length;a<=e;a++){const l=i.multiply(new Oe(s,Int32Array.from([1,s.exp(a-1+s.getGeneratorBase())])));n.push(l),i=l}}return n[e]}encode(e,n){if(n===0)throw new v("No error correction bytes");const i=e.length-n;if(i<=0)throw new v("No data bytes provided");const s=this.buildGenerator(n),a=new Int32Array(i);D.arraycopy(e,0,a,0,i);let l=new Oe(this.field,a);l=l.multiplyByMonomial(n,1);const h=l.divide(s)[1].getCoefficients(),p=n-h.length;for(let y=0;y<p;y++)e[i+y]=0;D.arraycopy(h,0,e,i+p,h.length)}}class At{constructor(){}static applyMaskPenaltyRule1(e){return At.applyMaskPenaltyRule1Internal(e,!0)+At.applyMaskPenaltyRule1Internal(e,!1)}static applyMaskPenaltyRule2(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a-1;l++){const d=i[l];for(let h=0;h<s-1;h++){const p=d[h];p===d[h+1]&&p===i[l+1][h]&&p===i[l+1][h+1]&&n++}}return At.N2*n}static applyMaskPenaltyRule3(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a;l++)for(let d=0;d<s;d++){const h=i[l];d+6<s&&h[d]===1&&h[d+1]===0&&h[d+2]===1&&h[d+3]===1&&h[d+4]===1&&h[d+5]===0&&h[d+6]===1&&(At.isWhiteHorizontal(h,d-4,d)||At.isWhiteHorizontal(h,d+7,d+11))&&n++,l+6<a&&i[l][d]===1&&i[l+1][d]===0&&i[l+2][d]===1&&i[l+3][d]===1&&i[l+4][d]===1&&i[l+5][d]===0&&i[l+6][d]===1&&(At.isWhiteVertical(i,d,l-4,l)||At.isWhiteVertical(i,d,l+7,l+11))&&n++}return n*At.N3}static isWhiteHorizontal(e,n,i){n=Math.max(n,0),i=Math.min(i,e.length);for(let s=n;s<i;s++)if(e[s]===1)return!1;return!0}static isWhiteVertical(e,n,i,s){i=Math.max(i,0),s=Math.min(s,e.length);for(let a=i;a<s;a++)if(e[a][n]===1)return!1;return!0}static applyMaskPenaltyRule4(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let h=0;h<a;h++){const p=i[h];for(let y=0;y<s;y++)p[y]===1&&n++}const l=e.getHeight()*e.getWidth();return Math.floor(Math.abs(n*2-l)*10/l)*At.N4}static getDataMaskBit(e,n,i){let s,a;switch(e){case 0:s=i+n&1;break;case 1:s=i&1;break;case 2:s=n%3;break;case 3:s=(i+n)%3;break;case 4:s=Math.floor(i/2)+Math.floor(n/3)&1;break;case 5:a=i*n,s=(a&1)+a%3;break;case 6:a=i*n,s=(a&1)+a%3&1;break;case 7:a=i*n,s=a%3+(i+n&1)&1;break;default:throw new v("Invalid mask pattern: "+e)}return s===0}static applyMaskPenaltyRule1Internal(e,n){let i=0;const s=n?e.getHeight():e.getWidth(),a=n?e.getWidth():e.getHeight(),l=e.getArray();for(let d=0;d<s;d++){let h=0,p=-1;for(let y=0;y<a;y++){const E=n?l[d][y]:l[y][d];E===p?h++:(h>=5&&(i+=At.N1+(h-5)),h=1,p=E)}h>=5&&(i+=At.N1+(h-5))}return i}}At.N1=3,At.N2=3,At.N3=40,At.N4=10;class di{constructor(e,n){this.width=e,this.height=n;const i=new Array(n);for(let s=0;s!==n;s++)i[s]=new Uint8Array(e);this.bytes=i}getHeight(){return this.height}getWidth(){return this.width}get(e,n){return this.bytes[n][e]}getArray(){return this.bytes}setNumber(e,n,i){this.bytes[n][e]=i}setBoolean(e,n,i){this.bytes[n][e]=i?1:0}clear(e){for(const n of this.bytes)Z.fill(n,e)}equals(e){if(!(e instanceof di))return!1;const n=e;if(this.width!==n.width||this.height!==n.height)return!1;for(let i=0,s=this.height;i<s;++i){const a=this.bytes[i],l=n.bytes[i];for(let d=0,h=this.width;d<h;++d)if(a[d]!==l[d])return!1}return!0}toString(){const e=new xe;for(let n=0,i=this.height;n<i;++n){const s=this.bytes[n];for(let a=0,l=this.width;a<l;++a)switch(s[a]){case 0:e.append(" 0");break;case 1:e.append(" 1");break;default:e.append(" ");break}e.append(`
65
- `)}return e.toString()}}class ar{constructor(){this.maskPattern=-1}getMode(){return this.mode}getECLevel(){return this.ecLevel}getVersion(){return this.version}getMaskPattern(){return this.maskPattern}getMatrix(){return this.matrix}toString(){const e=new xe;return e.append(`<<
60
+ `}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const xi={model:"deepseek-ai/DeepSeek-V3",maxSteps:30,extraTools:{}},Xa={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function gx(t,r){if(!r&&!t)return;if(!t)return r;if(!r)return t;const i={...r};for(const[c,d]of Object.entries(t))d&&typeof d=="object"&&!Array.isArray(d)?i[c]={...i[c]||{},...d}:i[c]=d;return i}class xx extends Kn.BaseModelProvider{transport;agent;promptManager;llmConfig={...xi,...Xa};isGenuiEnabled;debugStream=!1;emit;constructor(r,i,c,d){super(r);let f;c&&"llm"in c?f={...xi,...c}:f={...xi,...Xa,...c||{}},this.llmConfig=f;const x={llmConfig:f.llm?{llm:f.llm}:{...f}};this.agent=new Jn.AgentModelProvider(x),this.promptManager=new mx,this.promptManager.setStatic(i),this.emit=d}updateLLMConfig({model:r,baseURL:i,genuiUrl:c,apiKey:d,providerType:f,useReActMode:m,llm:x,providerOptions:v,headers:g}){if(x)this.agent.llm=x,this.llmConfig.model=r,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;else if(f&&i&&d){const E=this.isGenuiEnabled?.value&&c||i;this.llmConfig.model=r,this.llmConfig.apiKey=d,this.llmConfig.baseURL=i,this.llmConfig.providerType=f,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;let A;if(f==="deepseek")A=kc;else if(f==="openai")A=Ou;else if(typeof f=="function")A=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=A({apiKey:d,baseURL:E,...g?{headers:g}:{}})}this.llmConfig.providerOptions=v,this.llmConfig.headers=g}cleanGetSkillContentToolResult(r){const i=r[r.length-1];if(i.role==="tool"&&i.content.length>0){const c=i.content[i.content.length-1];c.type==="tool-result"&&c.toolName==="get_skill_content"&&(c.output.value.content="查询到技能内容已添加到系统提示词中。")}}cleanupOldSnapshotsInMessages(r){if(!r||r.length===0)return r;const c=this.agent.useReActMode===!0?"user":"tool",d=r[r.length-1];if(!d||d.role!==c||!this.isSnapshotContent(d.content))return r;const f=[...r];for(let m=f.length-2;m>=0;m--){const x=f[m];x.role===c&&this.isSnapshotContent(x.content)&&this.replaceSnapshotWithPlaceholder(x)}return f}removeSnapshotData(r){if(!r)return r;const i=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of i){const m=r.indexOf(f);if(m!==-1){c=m;break}}if(c!==-1){const f=r.substring(0,c).trim();return f?`${f} 📸 [历史快照已清理]`:"📸 历史快照已清理"}const d=["已成功获取页面无障碍树快照","takeSnapshot","snapshotId_counter"];for(const f of d)if(r.startsWith(f))return"📸 历史快照已清理";return r}replaceSnapshotWithPlaceholder(r){if(Array.isArray(r.content)){const i=r.content[0];if(i?.output?.value?.content){const c=i.output.value.content;Array.isArray(c)&&(i.output.value.content=c.map(d=>d.type==="image"||d.type==="image_url"?null:d.type==="text"&&d.text&&this.isSnapshotContent(d.text)?{type:"text",text:this.removeSnapshotData(d.text)}:d).filter(d=>d!==null)),i.output.value.screenshot&&delete i.output.value.screenshot}else r.content=r.content.filter(c=>c.type!=="image"&&c.type!=="image_url")}else typeof r.content=="string"&&this.isSnapshotContent(r.content)&&(r.content=this.removeSnapshotData(r.content))}isSnapshotContent(r){if(!r)return!1;const i=["无障碍树快照","takeSnapshot","snapshotId_counter","UID 格式","快照 ID","操作后的页面快照","已成功获取页面无障碍树快照","快照内容:"];if(typeof r=="string")return i.some(c=>r.includes(c));if(Array.isArray(r))for(const c of r){const d=c?.output?.value?.content?.[0]?.text;if(d&&i.some(f=>d.includes(f))||c.type==="text"&&c.text&&i.some(f=>c.text.includes(f))||c.type==="image"||c.type==="image_url")return!0}return!1}async chatStream(r,i){let c=r.messages[r.messages.length-1];if(!c)return;const d={model:this.llmConfig.model,system:this.promptManager.getSystemPrompt(),abortSignal:r.options?.signal,toolChoice:"auto",tools:this.llmConfig.extraTools||{},maxSteps:this.llmConfig.maxSteps,providerOptions:gx(this.llmConfig.providerOptions,fx),prepareStep:({messages:T})=>{this.cleanGetSkillContentToolResult(T);const S=this.cleanupOldSnapshotsInMessages(T),P=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(ee=>{P.push(...Object.keys(ee||{}))});const M=Array.from(new Set(P)).filter(ee=>!this.agent.ignoreToolnames.includes(ee));return{system:this.promptManager.getSystemPrompt(),messages:S,activeTools:M}},onStepFinish:T=>{if(T.finishReason==="tool-calls"&&T.content.length>0){const S=T.content[T.content.length-1];if(S.toolName==="get_skill_content"&&S.type==="tool-result"){const P=S.output.content;this.promptManager.appendTemp(P)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp(""),this.emit?.("chat-stream-finish")}},f={role:"user",content:c.content},x=[...(T=>T.map(S=>({role:S.role,content:S.content})))(this.agent.responseMessages),f];d.messages=x;const v=await this.agent.chatStream(d),g=new qp,A=await new hx({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{g.resolve(),i.onDone()})}}).traverse(v),D={role:"assistant",content:"",uiContent:[]};return _.watch(A,T=>{if(!T)i.onData(D);else{const P=T.steps.map(M=>M.contents).flat().map(M=>{if(M.type==="text")return px(M.text);if(M.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:M.text,thinkId:M.id};if(M.type==="tool")return{type:"tool",id:M.id,name:M.toolName,content:JSON.stringify({input:M.inputStr,output:M.output}),status:M.error?"failed":M.running?"running":"success"}});if(T?.error){const M={type:"markdown",content:`**错误**:${T.error.responseBody||T.error.message||"未知错误"}`};P.push(M)}(T.steps.length>=1||T?.error)&&i.onData({...D,uiContent:P.flat(),usage:T.totalUsage||null})}},{deep:!0}),g.promise}chat(r){throw new Error("Method not implemented.")}}const yx=({systemPrompt:t,llmConfig:r,emit:i})=>{const c=new xx({provider:"custom"},t,r,i),d=new Kn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:m,getCurrentConversation:x,switchConversation:v,deleteConversation:g,updateTitle:E,state:A}=Kn.useConversation({client:d,autoSave:!0,events:{onLoaded(){},onReceiveData(Z,B,L){L(),B.value[B.value.length-1].role==="assistant"&&B.value.pop(),i("before-ai-render",Z),B.value.push(Z)}}}),{messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,messages:M,addMessage:ee,send:$}=f,F=_.ref(),re=async(Z,B,L)=>{if(L){const{shouldBlock:z}=await L(Z);if(z)return!1}T.value=Z;const W=x();if(W&&W.title==="新会话"&&E(W.id,T.value.slice(0,15)),B&&B.length>0){const z=[{type:"text",text:T.value},...B],we=[];T.value&&we.push({type:"text",content:T.value});for(const me of B)me.type==="image"&&me.image&&we.push({type:"image",content:me.image});const G={role:"user",content:z,uiContent:we};M.value.push(G),T.value="",$()}else{const z={role:"user",content:T.value,uiContent:[{type:"text",content:T.value}]};M.value.push(z),T.value="",$()}return!0};return _.onMounted(()=>{F.value?.focus()}),_.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:d,messageManager:f,addMessage:ee,send:$,conversationState:A,messages:M,messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,senderRef:F,handleSendMessage:re,createConversation:m,switchConversation:v,deleteConversation:g,getCurrentConversation:x}};function wx(){}const Pn=Object.assign,ts=typeof window<"u",Zo=t=>t!==null&&typeof t=="object",tr=t=>t!=null,Pi=t=>typeof t=="function",_x=t=>Zo(t)&&Pi(t.then)&&Pi(t.catch),ku=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),vx=()=>ts?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Ya(t,r){const i=r.split(".");let c=t;return i.forEach(d=>{var f;c=Zo(c)&&(f=c[d])!=null?f:""}),c}function Cx(t,r,i){return r.reduce((c,d)=>(c[d]=t[d],c),{})}const Po=null,un=[Number,String],pr={type:Boolean,default:!0},bx=t=>({type:Number,default:t}),dn=t=>({type:String,default:t});var ns=typeof window<"u";function Ru(t){let r;_.onMounted(()=>{t(),_.nextTick(()=>{r=!0})}),_.onActivated(()=>{r&&t()})}function Mu(t,r,i={}){if(!ns)return;const{target:c=window,passive:d=!1,capture:f=!1}=i;let m=!1,x;const v=A=>{if(m)return;const D=_.unref(A);D&&!x&&(D.addEventListener(t,r,{capture:f,passive:d}),x=!0)},g=A=>{if(m)return;const D=_.unref(A);D&&x&&(D.removeEventListener(t,r,f),x=!1)};_.onUnmounted(()=>g(c)),_.onDeactivated(()=>g(c)),Ru(()=>v(c));let E;return _.isRef(c)&&(E=_.watch(c,(A,D)=>{g(D),v(A)})),()=>{E?.(),g(c),m=!0}}var Eo,yi;function Ax(){if(!Eo&&(Eo=_.ref(0),yi=_.ref(0),ns)){const t=()=>{Eo.value=window.innerWidth,yi.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:Eo,height:yi}}var Ex=/scroll|auto|overlay/i,Ix=ns?window:void 0;function Sx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Ka(t,r=Ix){let i=t;for(;i&&i!==r&&Sx(i);){const{overflowY:c}=window.getComputedStyle(i);if(Ex.test(c))return i;i=i.parentNode}return r}vx();const Tx=t=>t.stopPropagation();function Du(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Tx(t)}Ax();function vn(t){if(tr(t))return ku(t)?`${t}px`:String(t)}function Nx(t){if(tr(t)){if(Array.isArray(t))return{width:vn(t[0]),height:vn(t[1])};const r=vn(t);return{width:r,height:r}}}function Ox(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const kx=/-(\w)/g,Pu=t=>t.replace(kx,(r,i)=>i.toUpperCase()),Rx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Mx}=Object.prototype;function Dx(t,r,i){const c=r[i];tr(c)&&(!Mx.call(t,i)||!Zo(c)?t[i]=c:t[i]=Bu(Object(t[i]),c))}function Bu(t,r){return Object.keys(r).forEach(i=>{Dx(t,r,i)}),t}var Px={name:"姓名",tel:"电话",save:"保存",clear:"清空",undo:"撤销",cancel:"取消",confirm:"确认",delete:"删除",loading:"加载中...",noCoupon:"暂无优惠券",nameEmpty:"请填写姓名",addContact:"添加联系人",telInvalid:"请填写正确的电话",vanCalendar:{end:"结束",start:"开始",title:"日期选择",weekdays:["日","一","二","三","四","五","六"],monthTitle:(t,r)=>`${t}年${r}月`,rangePrompt:t=>`最多选择 ${t} 天`},vanCascader:{select:"请选择"},vanPagination:{prev:"上一页",next:"下一页"},vanPullRefresh:{pulling:"下拉即可刷新...",loosing:"释放即可刷新..."},vanSubmitBar:{label:"合计:"},vanCoupon:{unlimited:"无门槛",discount:t=>`${t}折`,condition:t=>`满${t}元可用`},vanCouponCell:{title:"优惠券",count:t=>`${t}张可用`},vanCouponList:{exchange:"兑换",close:"不使用",enable:"可用",disabled:"不可用",placeholder:"输入优惠码"},vanAddressEdit:{area:"地区",areaEmpty:"请选择地区",addressEmpty:"请填写详细地址",addressDetail:"详细地址",defaultAddress:"设为默认收货地址"},vanAddressList:{add:"新增地址"}};const Ja=_.ref("zh-CN"),Qa=_.reactive({"zh-CN":Px}),Bx={messages(){return Qa[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Bu(Qa,t)}};var Lx=Bx;function Fx(t){const r=Pu(t)+".";return(i,...c)=>{const d=Lx.messages(),f=Ya(d,r+i)||Ya(d,i);return Pi(f)?f(...c):f}}function Bi(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((i,c)=>i+Bi(t,c),""):Object.keys(r).reduce((i,c)=>i+(r[c]?Bi(t,c):""),""):""}function Ux(t){return(r,i)=>(r&&typeof r!="string"&&(i=r,r=""),r=r?`${t}__${r}`:t,`${r}${Bi(r,i)}`)}function yr(t){const r=`van-${t}`;return[r,Ux(r),Fx(r)]}const zx="van-haptics-feedback",el=5;function Vx(t,{args:r=[],done:i,canceled:c,error:d}){if(t){const f=t.apply(null,r);_x(f)?f.then(m=>{m?i():c&&c()}).catch(d||wx):f?i():c&&c()}else i()}function lo(t){return t.install=r=>{const{name:i}=t;i&&(r.component(i,t),r.component(Pu(`-${i}`),t))},t}const Zx=Symbol();function Lu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[$x,tl]=yr("badge"),jx={dot:Boolean,max:un,tag:dn("div"),color:String,offset:Array,content:un,showZero:pr,position:dn("top-right")};var Hx=_.defineComponent({name:$x,props:jx,setup(t,{slots:r}){const i=()=>{if(r.content)return!0;const{content:x,showZero:v}=t;return tr(x)&&x!==""&&(v||x!==0&&x!=="0")},c=()=>{const{dot:x,max:v,content:g}=t;if(!x&&i())return r.content?r.content():tr(v)&&ku(g)&&+g>+v?`${v}+`:g},d=x=>x.startsWith("-")?x.replace("-",""):`-${x}`,f=_.computed(()=>{const x={background:t.color};if(t.offset){const[v,g]=t.offset,{position:E}=t,[A,D]=E.split("-");r.default?(typeof g=="number"?x[A]=vn(A==="top"?g:-g):x[A]=A==="top"?vn(g):d(g),typeof v=="number"?x[D]=vn(D==="left"?v:-v):x[D]=D==="left"?vn(v):d(v)):(x.marginTop=vn(g),x.marginLeft=vn(v))}return x}),m=()=>{if(i()||t.dot)return _.createVNode("div",{class:tl([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:x}=t;return _.createVNode(x,{class:tl("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const Wx=lo(Hx);let Fu=2e3;const Gx=()=>++Fu,qx=t=>{Fu=t},[Uu,Xx]=yr("config-provider"),zu=Symbol(Uu),Yx={tag:dn("div"),theme:dn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:dn("local"),iconPrefix:String};function Kx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function Jx(t){const r={};return Object.keys(t).forEach(i=>{const c=Kx(Rx(i));r[`--van-${c}`]=t[i]}),r}function Io(t={},r={}){Object.keys(t).forEach(i=>{t[i]!==r[i]&&document.documentElement.style.setProperty(i,t[i])}),Object.keys(r).forEach(i=>{t[i]||document.documentElement.style.removeProperty(i)})}_.defineComponent({name:Uu,props:Yx,setup(t,{slots:r}){const i=_.computed(()=>Jx(Pn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(ts){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},d=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};_.watch(()=>t.theme,(f,m)=>{m&&d(m),c()},{immediate:!0}),_.onActivated(c),_.onDeactivated(d),_.onBeforeUnmount(d),_.watch(i,(f,m)=>{t.themeVarsScope==="global"&&Io(f,m)}),_.watch(()=>t.themeVarsScope,(f,m)=>{m==="global"&&Io({},i.value),f==="global"&&Io(i.value,{})}),t.themeVarsScope==="global"&&Io(i.value,{})}return _.provide(zu,t),_.watchEffect(()=>{t.zIndex!==void 0&&qx(t.zIndex)}),()=>_.createVNode(t.tag,{class:Xx(),style:t.themeVarsScope==="local"?i.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[Qx,nl]=yr("icon"),ey=t=>t?.includes("/"),ty={dot:Boolean,tag:dn("i"),name:String,size:un,badge:un,color:String,badgeProps:Object,classPrefix:String};var ny=_.defineComponent({name:Qx,props:ty,setup(t,{slots:r}){const i=_.inject(zu,null),c=_.computed(()=>t.classPrefix||i?.iconPrefix||nl());return()=>{const{tag:d,dot:f,name:m,size:x,badge:v,color:g}=t,E=ey(m);return _.createVNode(Wx,_.mergeProps({dot:f,tag:d,class:[c.value,E?"":`${c.value}-${m}`],style:{color:g,fontSize:vn(x)},content:v},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),E&&_.createVNode("img",{class:nl("image"),src:m},null)]}})}}});const rs=lo(ny),[ry,Kr]=yr("loading"),oy=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Kr("line",String(r+1))},null)),iy=_.createVNode("svg",{class:Kr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),sy={size:un,type:dn("circular"),color:String,vertical:Boolean,textSize:un,textColor:String};var ay=_.defineComponent({name:ry,props:sy,setup(t,{slots:r}){const i=_.computed(()=>Pn({color:t.color},Nx(t.size))),c=()=>{const f=t.type==="spinner"?oy:iy;return _.createVNode("span",{class:Kr("spinner",t.type),style:i.value},[r.icon?r.icon():f])},d=()=>{var f;if(r.default)return _.createVNode("span",{class:Kr("text"),style:{fontSize:vn(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:m}=t;return _.createVNode("div",{class:Kr([f,{vertical:m}]),"aria-live":"polite","aria-busy":!0},[c(),d()])}}});const ly=lo(ay),cy={show:Boolean,zIndex:un,overlay:pr,duration:un,teleport:[String,Object],lockScroll:pr,lazyRender:pr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Po,transitionAppear:Boolean,closeOnClickOverlay:pr};function uy(t,r){return t>r?"horizontal":r>t?"vertical":""}function dy(){const t=_.ref(0),r=_.ref(0),i=_.ref(0),c=_.ref(0),d=_.ref(0),f=_.ref(0),m=_.ref(""),x=_.ref(!0),v=()=>m.value==="vertical",g=()=>m.value==="horizontal",E=()=>{i.value=0,c.value=0,d.value=0,f.value=0,m.value="",x.value=!0};return{move:(T=>{const S=T.touches[0];i.value=(S.clientX<0?0:S.clientX)-t.value,c.value=S.clientY-r.value,d.value=Math.abs(i.value),f.value=Math.abs(c.value);const P=10;(!m.value||d.value<P&&f.value<P)&&(m.value=uy(d.value,f.value)),x.value&&(d.value>el||f.value>el)&&(x.value=!1)}),start:(T=>{E(),t.value=T.touches[0].clientX,r.value=T.touches[0].clientY}),reset:E,startX:t,startY:r,deltaX:i,deltaY:c,offsetX:d,offsetY:f,direction:m,isVertical:v,isHorizontal:g,isTap:x}}let Hr=0;const rl="van-overflow-hidden";function fy(t,r){const i=dy(),c="01",d="10",f=E=>{i.move(E);const A=i.deltaY.value>0?d:c;let D=Ka(E.target,t.value);for(;D.scrollHeight<=D.offsetHeight&&D!==t.value&&D.parentElement;)D=Ka(D.parentElement,t.value);const{scrollHeight:T,offsetHeight:S,scrollTop:P}=D;let M="11";P===0?M=S>=T?"00":"01":P+S>=T&&(M="10"),M!=="11"&&i.isVertical()&&!(parseInt(M,2)&parseInt(A,2))&&Du(E)},m=()=>{document.addEventListener("touchstart",i.start),document.addEventListener("touchmove",f,{passive:!1}),Hr||document.body.classList.add(rl),Hr++},x=()=>{Hr&&(document.removeEventListener("touchstart",i.start),document.removeEventListener("touchmove",f),Hr--,Hr||document.body.classList.remove(rl))},v=()=>r()&&m(),g=()=>r()&&x();Ru(v),_.onDeactivated(g),_.onBeforeUnmount(g),_.watch(r,E=>{E?m():x()})}function Vu(t){const r=_.ref(!1);return _.watch(t,i=>{i&&(r.value=i)},{immediate:!0}),i=>()=>r.value?i():null}const ol=()=>{var t;const{scopeId:r}=((t=_.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[hy,py]=yr("overlay"),my={show:Boolean,zIndex:un,duration:un,className:Po,lockScroll:pr,lazyRender:pr,customStyle:Object,teleport:[String,Object]};var gy=_.defineComponent({name:hy,inheritAttrs:!1,props:my,setup(t,{attrs:r,slots:i}){const c=_.ref(),d=Vu(()=>t.show||!t.lazyRender),f=x=>{t.lockScroll&&Du(x)},m=d(()=>{var x;const v=Pn(Ox(t.zIndex),t.customStyle);return tr(t.duration)&&(v.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:v,class:[py(),t.className]},r),[(x=i.default)==null?void 0:x.call(i)]),[[_.vShow,t.show]])});return Mu("touchmove",f,{target:c}),()=>{const x=_.createVNode(_.Transition,{name:"van-fade",appear:!0},{default:m});return t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[x]}):x}}});const xy=lo(gy),yy=Pn({},cy,{round:Boolean,position:dn("center"),closeIcon:dn("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:dn("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[wy,il]=yr("popup");var _y=_.defineComponent({name:wy,inheritAttrs:!1,props:yy,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:i,slots:c}){let d,f;const m=_.ref(),x=_.ref(),v=Vu(()=>t.show||!t.lazyRender),g=_.computed(()=>{const B={zIndex:m.value};if(tr(t.duration)){const L=t.position==="center"?"animationDuration":"transitionDuration";B[L]=`${t.duration}s`}return B}),E=()=>{d||(d=!0,m.value=t.zIndex!==void 0?+t.zIndex:Gx(),r("open"))},A=()=>{d&&Vx(t.beforeClose,{done(){d=!1,r("close"),r("update:show",!1)}})},D=B=>{r("clickOverlay",B),t.closeOnClickOverlay&&A()},T=()=>{if(t.overlay){const B=Pn({show:t.show,class:t.overlayClass,zIndex:m.value,duration:t.duration,customStyle:t.overlayStyle,role:t.closeOnClickOverlay?"button":void 0,tabindex:t.closeOnClickOverlay?0:void 0},t.overlayProps);return _.createVNode(xy,_.mergeProps(B,ol(),{onClick:D}),{default:c["overlay-content"]})}},S=B=>{r("clickCloseIcon",B),A()},P=()=>{if(t.closeable)return _.createVNode(rs,{role:"button",tabindex:0,name:t.closeIcon,class:[il("close-icon",t.closeIconPosition),zx],classPrefix:t.iconPrefix,onClick:S},null)};let M;const ee=()=>{M&&clearTimeout(M),M=setTimeout(()=>{r("opened")})},$=()=>r("closed"),F=B=>r("keydown",B),re=v(()=>{var B;const{destroyOnClose:L,round:W,position:z,safeAreaInsetTop:we,safeAreaInsetBottom:G,show:me}=t;if(!(!me&&L))return _.withDirectives(_.createVNode("div",_.mergeProps({ref:x,style:g.value,role:"dialog",tabindex:0,class:[il({round:W,[z]:z}),{"van-safe-area-top":we,"van-safe-area-bottom":G}],onKeydown:F},i,ol()),[(B=c.default)==null?void 0:B.call(c),P()]),[[_.vShow,me]])}),Z=()=>{const{position:B,transition:L,transitionAppear:W}=t,z=B==="center"?"van-fade":`van-popup-slide-${B}`;return _.createVNode(_.Transition,{name:L||z,appear:W,onAfterEnter:ee,onAfterLeave:$},{default:re})};return _.watch(()=>t.show,B=>{B&&!d&&(E(),i.tabindex===0&&_.nextTick(()=>{var L;(L=x.value)==null||L.focus()})),!B&&d&&(d=!1,r("close"))}),Lu({popupRef:x}),fy(x,()=>t.show&&t.lockScroll),Mu("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),_.onMounted(()=>{t.show&&E()}),_.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),_.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),_.provide(Zx,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[T(),Z()]}):_.createVNode(_.Fragment,null,[T(),Z()])}});const vy=lo(_y);let Wr=0;function Cy(t){t?(Wr||document.body.classList.add("van-toast--unclickable"),Wr++):Wr&&(Wr--,Wr||document.body.classList.remove("van-toast--unclickable"))}const[by,Or]=yr("toast"),Ay=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Ey={icon:String,show:Boolean,type:dn("text"),overlay:Boolean,message:un,iconSize:un,duration:bx(2e3),position:dn("middle"),teleport:[String,Object],wordBreak:String,className:Po,iconPrefix:String,transition:dn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Po,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:un};var Iy=_.defineComponent({name:by,props:Ey,emits:["update:show"],setup(t,{emit:r,slots:i}){let c,d=!1;const f=()=>{const A=t.show&&t.forbidClick;d!==A&&(d=A,Cy(d))},m=A=>r("update:show",A),x=()=>{t.closeOnClick&&m(!1)},v=()=>clearTimeout(c),g=()=>{const{icon:A,type:D,iconSize:T,iconPrefix:S,loadingType:P}=t;if(A||D==="success"||D==="fail")return _.createVNode(rs,{name:A||D,size:T,class:Or("icon"),classPrefix:S},null);if(D==="loading")return _.createVNode(ly,{class:Or("loading"),size:T,type:P},null)},E=()=>{const{type:A,message:D}=t;if(i.message)return _.createVNode("div",{class:Or("text")},[i.message()]);if(tr(D)&&D!=="")return A==="html"?_.createVNode("div",{key:0,class:Or("text"),innerHTML:String(D)},null):_.createVNode("div",{class:Or("text")},[D])};return _.watch(()=>[t.show,t.forbidClick],f),_.watch(()=>[t.show,t.type,t.message,t.duration],()=>{v(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),_.onMounted(f),_.onUnmounted(f),()=>_.createVNode(vy,_.mergeProps({class:[Or([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:x,onClosed:v,"onUpdate:show":m},Cx(t,Ay)),{default:()=>[g(),E()]})}});function Sy(){const t=_.reactive({show:!1}),r=d=>{t.show=d},i=d=>{Pn(t,d,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return Lu({open:i,close:c,toggle:r}),{open:i,close:c,state:t,toggle:r}}function Ty(t){const r=_.createApp(t),i=document.createElement("div");return document.body.appendChild(i),{instance:r.mount(i),unmount(){r.unmount(),document.body.removeChild(i)}}}const Ny={icon:"",type:"text",message:"",className:"",overlay:!1,onClose:void 0,onOpened:void 0,duration:2e3,teleport:"body",iconSize:void 0,iconPrefix:void 0,position:"middle",transition:"van-fade",forbidClick:!1,loadingType:void 0,overlayClass:"",overlayStyle:void 0,closeOnClick:!1,closeOnClickOverlay:!1};let So=[],Oy=!1,sl=Pn({},Ny);const ky=new Map;function Zu(t){return Zo(t)?t:{message:t}}function Ry(){const{instance:t}=Ty({setup(){const r=_.ref(""),{open:i,state:c,close:d,toggle:f}=Sy(),m=()=>{},x=()=>{const v={onClosed:m,"onUpdate:show":f};return _.createVNode(Iy,_.mergeProps(c,v),null)};return _.watch(r,v=>{c.message=v}),_.getCurrentInstance().render=x,{open:i,close:d,message:r}}});return t}function My(){if(!So.length||Oy){const t=Ry();So.push(t)}return So[So.length-1]}function it(t={}){if(!ts)return{};const r=My(),i=Zu(t);return r.open(Pn({},sl,ky.get(i.type||sl.type),i)),r}const Dy=t=>r=>it(Pn({type:t},Zu(r))),$u=Dy("loading"),Py=t=>{try{const r=JSON.parse(t),i=[];if(!r.mcpServers||typeof r.mcpServers!="object")throw new Error("JSON 格式错误:缺少 mcpServers 字段");for(const[c,d]of Object.entries(r.mcpServers)){const f=By(d);f&&i.push({name:c,config:f})}return i}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},By=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:i,sessionId:c,headers:d}=t;return r==="streamableHttp"||r==="sse"?{type:r,url:i,headers:d,useAISdkClient:!0}:{type:"streamableHttp",url:i,headers:d,useAISdkClient:!0}},Ly=(t,r,i)=>{const c=async(f,m,x,v,g)=>{if(await t.insertMcpServer(f,m)){const A=t.mcpTools[f];if(A){const T={id:`plugin-${f.replace("mcp-server-","")}`,name:x,icon:g||i,description:v||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(S=>({id:S,name:S,description:A[S].description,enabled:!0})),originMcpConfig:_.markRaw(m)};return r.value.push(T),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{$u("添加工具中...");try{if(f==="code"){if(typeof m!="string"){it("添加工具失败:code 类型需要 JSON 字符串格式");return}const $=Py(m);if($.length===0){it("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let F=0,re=0;for(const{name:Z,config:B}of $){const L=`mcp-server-${Z}`;await c(L,B,Z)?F++:re++}await t.closeAll(),re===0?it(`成功添加 ${F} 个工具`):F>0?it(`成功添加 ${F} 个工具,${re} 个失败`):it("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){it("添加工具失败:数据格式不正确");return}const{description:x,headers:v,name:g,thumbnail:E,type:A,url:D}=m;if(!g||!D||!A){it("添加工具失败:缺少必要参数(名称、URL或类型)");return}const S=`mcp-server-${`custom-${g}-${Date.now()}`}`;let P;if(typeof v=="string"&&v.trim())try{P=JSON.parse(v)}catch($){console.warn("Failed to parse headers JSON:",$)}else typeof v=="object"&&(P=v);await c(S,{type:A,url:D,headers:P,useAISdkClient:!0},g,x,E)?(await t.closeAll(),it("添加工具完成")):it("重复添加工具或无法获取工具列表")}catch(x){console.error("handleCustomAdd error:",x),it(`添加工具失败:${x instanceof Error?x.message:"未知错误"}`)}}}};function Fy(t,r,i){const c=_.ref([]),d=_.ref([]),f=_.ref(!1),m=Z=>t.mcpServers[Z]?.type==="local",x=(Z,B)=>{B?t.ignoreToolnames=t.ignoreToolnames.filter(L=>L!==Z):t.ignoreToolnames.includes(Z)||t.ignoreToolnames.push(Z)},v=(Z,B)=>{r.value||(r.value={});const L={...r.value};Z===null?Object.keys(L).forEach(W=>{L[W]=B}):L[Z]=B,r.value=L},g=Z=>{const B=d.value.find(L=>L.id===Z);B&&(B.addState="idle")},E=Z=>{const B=t.mcpTools[Z];if(!B)return[];const L=m(Z),W=r.value||{};return Object.keys(B).map(z=>{const we=Object.prototype.hasOwnProperty.call(W,z),G=L&&we?W[z]:!0;return x(z,G),{id:z,name:z,description:B[z].description,enabled:G}})},A=()=>{c.value.forEach(B=>{const L=new Map(B.tools.map(z=>[z.id,z.enabled])),W=E(B.id).map(z=>{const we=L.has(z.id)?!!L.get(z.id):z.enabled;return x(z.id,we),{...z,enabled:we}});B.tools=W});const Z=new Set(c.value.flatMap(B=>B.tools.map(L=>L.id)));t.ignoreToolnames=t.ignoreToolnames.filter(B=>Z.has(B))},D=async Z=>{const B=Z.pluginId;if(!await t.insertMcpServer(B,Z.mcpServer))return!1;if(!t.mcpTools[B])return await t.removeMcpServer(B),!1;const z=E(B);if(z.length===0&&Z.mcpServer?.type!=="builtin")return await t.removeMcpServer(B),!1;const we=c.value.find(me=>me.id===Z.pluginId);if(we)return we.tools=z,we.originMcpConfig=_.markRaw(Z.mcpServer),!0;const G={id:Z.pluginId,name:Z.name,icon:Z.icon||i,description:Z.description,enabled:!0,expanded:!1,tools:z,originMcpConfig:_.markRaw(Z.mcpServer)};return c.value.push(G),!0};return{installedPlugins:c,marketPlugins:d,pluginVisible:f,loadMcpServerToPlugin:async(Z,B)=>{let L=B.name,W=B.description;if(!L||!W){if("type"in B&&B.type==="local")L=L||"本地工具",W=W||"本地工具列表";else if("type"in B&&B.type==="builtin")L=L||"浏览器内置工具",W=W||"通过 document.modelContext 暴露的浏览器原生 MCP 工具";else if("url"in B)try{const z=new URL(B.url);L=L||z.origin,W=W||z.searchParams.get("sessionId")||("sessionId"in B?B.sessionId:"")||""}catch(z){console.error("[usePlugin] Failed to parse MCP server URL:",B.url,z),L=L||"未知插件",W=W||""}}await D({pluginId:Z,name:L||"",description:W||"",mcpServer:B})},togglePlugin:(Z,B)=>{const L=m(Z.id);Z.tools.forEach(W=>{W.enabled=B,x(W.id,B),L&&v(W.id,B)})},toggleTool:(Z,B,L)=>{const W=m(Z.id);Z.tools.forEach(z=>{z.id===B&&(z.enabled=L)}),x(B,L),W&&v(B,L)},deletePlugin:async Z=>{const B=c.value.find(W=>W.id===Z.id);if(!B)return;c.value=c.value.filter(W=>W.id!==B.id),g(B.id);const L=Z.id;await t.removeMcpServer(L)},addPluginCore:D,addPluginFromMarket:async Z=>{Z.addState="loading";const B={type:Z.type,url:Z.url,headers:Z.headers,useAISdkClient:!0},L=await D({pluginId:Z.id,name:Z.name,description:Z.description||"",icon:Z.icon,mcpServer:B});Z.addState=L?"added":"idle"},addPluginFromScan:async(Z,B)=>{const L={type:"streamableHttp",url:`${B}mcp?sessionId=${Z}`};let W="未知插件";try{W=new URL(`${B}mcp?sessionId=${Z}`).origin}catch(z){console.error("[usePlugin] Failed to parse scan URL:",z)}return await D({pluginId:`plugin-${Z}`,name:W,description:Z,mcpServer:L})},handleClientDisconnected:async Z=>{const B=Z,L=c.value.find(W=>W.id===B);return await t.removeMcpServer(Z),L?(c.value=c.value.filter(W=>W.id!==B),g(B),L):null},searchPlugin:(Z,B)=>Z.trim()===""||B.name.toLowerCase().includes(Z.toLowerCase()),syncInstalledPluginTools:A}}function Uy(t){const{onToolCatalogChanged:r}=t,i=typeof window<"u"&&window!==window.top,c=D=>D===window||i&&D===window.parent;let d=!1,f=!1,m=!1;const x=async()=>{if(!(!r||d)){if(f){m=!0;return}f=!0;try{do{m=!1;try{await r()}catch(D){console.warn("[useRouteBasedTools] refresh tool catalog failed:",D)}}while(m&&!d)}finally{f=!1}}},v=D=>{!c(D.source)||D.data?.type!==Jn.MSG_TOOL_REGISTERED&&D.data?.type!==Jn.MSG_TOOL_UNREGISTERED||x()};let g=!1;const E=()=>{g||(d=!1,g=!0,window.addEventListener("message",v),i&&window.parent&&window.parent.postMessage({type:Jn.MSG_REMOTER_READY},"*"))},A=()=>{g&&(d=!0,m=!1,g=!1,window.removeEventListener("message",v))};_.onMounted(()=>{E()}),_.onUnmounted(()=>{A()})}function zy(t){const{skillsRef:r,customAgentProvider:i}=t,c=_.shallowRef([]);_.watchEffect(async()=>{const x=r?.value;c.value=x?await Jn.getSkillOverviews(x):[]});const d=_.computed(()=>{const x=c.value;return x.length>0?Jn.formatSkillsForSystemPrompt(x):""}),f=_.computed(()=>{const x=r?.value;return x?Jn.createSkillTools(x):{}});return _.watchEffect(()=>{if(i.promptManager.setSkillMeta(d.value),i.llmConfig){const x=i.llmConfig.extraTools??{};i.llmConfig.extraTools={...x,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:d,skillTools:f,skillOverviews:c}}const Vy=["title"],Zy=_.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,i=_.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return{cachedInputTokens:[E/x*100+"%",E],inputTokens:[(f-E)/x*100+"%",f],reasoningTokens:[A/x*100+"%",A],outputTokens:[(m-A)/x*100+"%",m]}}),d=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${x}`,`cachedInputTokens: ${E}`,`reasoningTokens: ${A}`].join(`
61
+ `)});return(f,m)=>i.value?_.createCommentVNode("",!0):(_.openBlock(),_.createElementBlock("div",{key:0,class:"token-usage-wrap",title:d.value},[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(c.value,(x,v)=>(_.openBlock(),_.createElementBlock("div",{key:v,class:_.normalizeClass(v),style:_.normalizeStyle({width:x[0]})},null,6))),128))],8,Vy))}}),nr=(t,r)=>{const i=t.__vccOpts||t;for(const[c,d]of r)i[c]=d;return i},$y=nr(Zy,[["__scopeId","data-v-000098b4"]]),jy={width:"100.000000",height:"100.000000",viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"};function Hy(t,r){return _.openBlock(),_.createElementBlock("svg",jy,[...r[0]||(r[0]=[_.createStaticVNode('<desc> Created with Pixso. </desc><defs><radialGradient gradientTransform="translate(32.4474 65.1156) rotate(128.932) scale(22.991 20.6919)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3090_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient><linearGradient x1="30.999874" y1="85.000229" x2="30.499891" y2="70.500214" id="paint_linear_9_3092_0" gradientUnits="userSpaceOnUse"><stop stop-color="#000000" stop-opacity="0.000000"></stop><stop offset="1.000000" stop-color="#000000"></stop></linearGradient><radialGradient gradientTransform="translate(26.9999 24.7118) rotate(38.3655) scale(77.7996 109.496)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3094_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient></defs><rect id="NEXT-LOGO-无背景渐变-右" width="100.000000" height="99.999939" transform="matrix(-1 0 0 1 100 0)" fill="#FFFFFF" fill-opacity="0"></rect>',3),_.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[_.createElementVNode("rect",{id:"画板 1773",width:"99.999962",height:"99.999947",transform:"matrix(-1 0 0 1 100 6.10352e-05)",fill:"#000000","fill-opacity":"1.000000"})],-1),_.createStaticVNode('<g mask="url(#mask9_3088)"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_radial_9_3090_0)" fill-opacity="1.000000" fill-rule="evenodd"></path><g opacity="0.100000" style="mix-blend-mode:normal;"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_linear_9_3092_0)" fill-opacity="1.000000" fill-rule="evenodd"></path></g><rect id="矩形 5" x="12.000000" y="19.000183" rx="26.999992" width="75.999977" height="53.999985" fill="url(#paint_radial_9_3094_0)" fill-opacity="1.000000"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" fill="#000000" fill-opacity="0"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" stroke="#000000" stroke-opacity="0" stroke-width="1.000000"></rect><path id="path" d="M45.39 59.06C44.22 60.05 42.9 60.66 41.43 60.89C39.95 61.12 38.57 61.04 37.28 60.65C36 60.26 34.04 58.58 34.04 58.58C34.04 58.58 29.02 54.73 29.02 45.61C29.02 36.5 33.5 32.5 33.5 32.5C33.5 32.5 34.72 31.31 36.5 31C38.29 30.68 39.43 30.98 40.66 31.33C50.89 34.23 62.38 34.33 72.58 31.33C73.81 30.98 74.91 30.93 75.89 31.17C76.87 31.42 77.71 31.89 78.42 32.59C81.65 35.81 82.87 41.06 83 45.61C83.12 50.09 81.97 55.24 78.94 58.54C78.04 59.52 76.98 60.22 75.78 60.63C74.58 61.04 73.32 61.12 71.99 60.89C70.66 60.66 69.48 60.05 68.46 59.06C68.01 58.62 67.39 58.07 66.57 57.4C65.76 56.73 64.83 56.08 63.79 55.44C62.75 54.8 61.62 54.25 60.39 53.8C59.16 53.35 57.91 53.13 56.62 53.13C55.36 53.13 54.16 53.36 53 53.83C51.85 54.29 50.79 54.84 49.82 55.48C48.86 56.12 48 56.78 47.26 57.45C46.51 58.11 45.89 58.65 45.39 59.06Z" fill="#FFFFFF" fill-opacity="1.000000" fill-rule="nonzero"></path><rect id="矩形 841" rx="2.000000" width="3.999999" height="11.999996" transform="matrix(-0.999983 0.00577157 0.00577157 0.999983 76.1109 38.0356)" fill="#1476FF" fill-opacity="1.000000"></rect><path id="合并" d="M42.96 38C43.77 37.97 44.55 38.42 44.92 39.19L48.73 47.11C49.22 48.13 48.79 49.34 47.75 49.81C46.72 50.28 45.48 49.83 44.99 48.8L42.96 44.59L40.94 48.81C40.45 49.83 39.21 50.28 38.18 49.81C37.14 49.34 36.7 48.13 37.2 47.11L41 39.19C41.37 38.42 42.16 37.98 42.96 38Z" fill="#1476FF" fill-opacity="1.000000" fill-rule="evenodd"></path></g>',1)])])}const ju={render:Hy};function Wy(t){const{messages:r,messageState:i,inputMessage:c,handleSendMessage:d}=t,f=_.h(ju,{style:{width:"48px",height:"48px"}}),m=_.ref({}),x=_.computed(()=>Kn.GeneratingStatus.includes(i.status)),v=_.computed(()=>r.value.findLastIndex(T=>T.role==="assistant")),g=T=>T===void 0?"复制":m.value[T]?"复制成功":"复制",E=async T=>{const P=r.value[T].uiContent.map(M=>M.content).join(`
62
+ `);try{await navigator.clipboard.writeText(P),T!==void 0&&(m.value[T]=!0,setTimeout(()=>{m.value[T]=!1},3e3))}catch(M){console.error("复制失败:",M),it("复制失败,请重试")}},A=async T=>{const S=r.value.findLastIndex((M,ee)=>M.role==="user"&&ee<=T);if(S===-1){console.warn("未找到可重新生成的用户消息"),it("无法重新生成消息");return}const P=r.value[S];if(r.value=r.value.slice(0,S),Array.isArray(P.content)){const ee=P.content.find(F=>F.type==="text")?.text||"",$=P.content.filter(F=>F.type!=="text");c.value=ee,await d(ee,$.length>0?$:void 0)}else c.value=P.content,await d(P.content)},D={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:T})=>{const S=v.value===T;return x.value&&S?"":_.h("div",{class:["assistant-actions",{"latest-assistant":S,"historical-assistant":!S}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[_.h(Vt.IconButton,{icon:Mr.IconRefresh,size:24,onClick:()=>A(T)}),_.h(Id,{effect:"light",content:g(T),placement:"right",visibleArrow:!1},()=>_.h(Vt.IconButton,{icon:Mr.IconCopy,size:24,onClick:()=>E(T)})),r.value[T].usage?_.h($y,{usage:r.value[T].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:D,copyingStates:m,isProcessing:x,latestAssistantMessageIndex:v,copyTooltipContent:g,copyMessageToClipboard:E,regenerateMessage:A}}function Gy(t){const{createConversation:r,switchConversation:i,deleteConversation:c,getCurrentConversation:d,abortRequest:f,conversationState:m,customAgentProvider:x}=t,v=_.ref(!1),g=()=>{_.nextTick(()=>{const S=document.querySelector("div.tr-bubble-list");S&&S.scrollTo({top:S.scrollHeight,behavior:"smooth"})})};return{showHistory:v,handleCreateConversation:()=>{f();const S=[];x.agent.responseMessages=S,r();const P=d();P.aiSdkMessages=S},handleHistorySelect:S=>{f(),i(S.id);const P=d();x.agent.responseMessages=P.aiSdkMessages,v.value=!1,g()},handleHistoryUpdateTitle:(S,P)=>{P.title=S},handleHistoryDelete:(S,P)=>{if(S.id==="delete"){if(m.currentId===P.id){it("不允许删除当前会话");return}c(P.id)}},scrollToBottom:g}}function qy(t){const{sessionId:r,agentRoot:i,mode:c,qrCodeUrl:d,remoteUrl:f,menuItems:m,AILogoUrl:x,show:v,addPluginFromScan:g,inputMessage:E}=t;let A=null,D=!1;const T=async $=>{if($u("添加工具中..."),$){const F=await g($,i.value);it(F?"添加工具完成":"重复添加工具或添加失败")}else it("添加工具失败")},S=async $=>{if(/^\/[A-Za-z0-9-]{6,}$/.test($)){try{const F=await fetch(`${i.value}client?sessionId=${$.slice(1)}`);if(!F.ok)throw new Error(`HTTP ${F.status}`);const Z=(await F.json())?.data?.sessionId;Z?await T(Z):it("添加工具失败,请检查识别码是否正确"),E.value=""}catch(F){console.error("识别码处理失败:",F),it("添加工具失败,请检查识别码是否正确"),E.value=""}return!0}return!1},P=()=>{const $=F=>{A&&(A.destroy(),A=null),A=Jn.createRemoter({sessionId:F||void 0,qrCodeUrl:d,remoteUrl:f,menuItems:m?.value,logoUrl:x,onShowAIChat:()=>v.value=!0}),v.value&&A.hide()};_.watch(r,F=>{if(c!=="remoter")return;const re=!!F;A?!D&&re&&($(F),D=!0):($(F),D=re)},{immediate:!0}),m&&_.watch(m,()=>{c==="remoter"&&A&&$(r.value)},{deep:!0}),_.watch(v,F=>{A&&(F?A.hide():A.show())},{immediate:!0})},M=()=>{_.watch(r,$=>{$&&T($)})};return{handleScanSuccess:T,handleSessionIdInput:S,initialize:()=>{r.value&&T(r.value),c==="remoter"&&P(),M()},initializeRemoter:P,watchSessionIdChanges:M}}function Xy(t){return new Promise((r,i)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=i,c.readAsDataURL(t)})}function Yy(t){return t.type.startsWith("image/")}function Ky(t,r){const i=r*1024*1024;return t.size<=i}async function Jy(t){if(t.length===0)return[];const r=[];for(const i of t)if(i.rawFile)try{const c=await Xy(i.rawFile);Yy(i.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),it({type:"fail",message:"文件处理失败"})}return r}function Qy(t={}){const r=_.ref([]),i=async d=>{if(!d||d.length===0)return;c();const f=_.unref(t.maxFileSize)||10,m=_.unref(t.supportedTypes)||["image/"];for(const x of d){if(!m.some(g=>x.type.startsWith(g))){it({type:"fail",message:`不支持的文件类型: ${x.type}`});continue}if(!Ky(x,f)){it({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:x,url:URL.createObjectURL(x)})}},c=()=>{r.value.forEach(d=>{d.url&&URL.revokeObjectURL(d.url)}),r.value=[]};return{attachments:r,handleFilesSelected:i,clearAttachments:c}}function ew(t){const{selectedModel:r,selectedModelId:i}=t,c=_.computed(()=>r.value?.multimodal?.supportImages??!1),d=_.computed(()=>r.value?.multimodal?.maxFileSize||10),f=_.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:m,handleFilesSelected:x,clearAttachments:v}=Qy({maxFileSize:d,supportedTypes:f});return _.watch(i,()=>{if(m.value.length>0&&r.value){const T=r.value.multimodal?.maxFileSize||10,S=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(M=>{if(!M.rawFile||!S.some(F=>M.rawFile.type.startsWith(F)))return!0;const $=T*1024*1024;return M.rawFile.size>$}).length>0&&(v(),it("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:T=>{x(T)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(it("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await Jy(m.value),cleanupAttachments:()=>{m.value.length>0&&v()},clearAttachments:v}}var Ce;(function(t){t[t.QR_CODE=0]="QR_CODE",t[t.AZTEC=1]="AZTEC",t[t.CODABAR=2]="CODABAR",t[t.CODE_39=3]="CODE_39",t[t.CODE_93=4]="CODE_93",t[t.CODE_128=5]="CODE_128",t[t.DATA_MATRIX=6]="DATA_MATRIX",t[t.MAXICODE=7]="MAXICODE",t[t.ITF=8]="ITF",t[t.EAN_13=9]="EAN_13",t[t.EAN_8=10]="EAN_8",t[t.PDF_417=11]="PDF_417",t[t.RSS_14=12]="RSS_14",t[t.RSS_EXPANDED=13]="RSS_EXPANDED",t[t.UPC_A=14]="UPC_A",t[t.UPC_E=15]="UPC_E",t[t.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(Ce||(Ce={}));var al=new Map([[Ce.QR_CODE,"QR_CODE"],[Ce.AZTEC,"AZTEC"],[Ce.CODABAR,"CODABAR"],[Ce.CODE_39,"CODE_39"],[Ce.CODE_93,"CODE_93"],[Ce.CODE_128,"CODE_128"],[Ce.DATA_MATRIX,"DATA_MATRIX"],[Ce.MAXICODE,"MAXICODE"],[Ce.ITF,"ITF"],[Ce.EAN_13,"EAN_13"],[Ce.EAN_8,"EAN_8"],[Ce.PDF_417,"PDF_417"],[Ce.RSS_14,"RSS_14"],[Ce.RSS_EXPANDED,"RSS_EXPANDED"],[Ce.UPC_A,"UPC_A"],[Ce.UPC_E,"UPC_E"],[Ce.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),ll;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(ll||(ll={}));function tw(t){return Object.values(Ce).includes(t)}var oo;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(oo||(oo={}));var nw=(function(){function t(){}return t.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",t.SCAN_DEFAULT_FPS=2,t.DEFAULT_DISABLE_FLIP=!1,t.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,t.DEFAULT_SUPPORTED_SCAN_TYPE=[oo.SCAN_TYPE_CAMERA,oo.SCAN_TYPE_FILE],t})(),Hu=(function(){function t(r,i){this.format=r,this.formatName=i}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!al.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,al.get(r))},t})(),cl=(function(){function t(){}return t.createFromText=function(r){var i={text:r};return{decodedText:r,result:i}},t.createFromQrcodeResult=function(r){return{decodedText:r.text,result:r}},t})(),Li;(function(t){t[t.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",t[t.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",t[t.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(Li||(Li={}));var rw=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Li.UNKWOWN_ERROR}},t})(),ow=(function(){function t(r){this.verbose=r}return t.prototype.log=function(r){this.verbose&&console.log(r)},t.prototype.warn=function(r){this.verbose&&console.warn(r)},t.prototype.logError=function(r,i){(this.verbose||i===!0)&&console.error(r)},t.prototype.logErrors=function(r){if(r.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(r)},t})();function zn(t){return typeof t>"u"||t===null}var Rr=(function(){function t(){}return t.codeParseError=function(r){return"QR code parse error, error = ".concat(r)},t.errorGettingUserMedia=function(r){return"Error getting userMedia, error = ".concat(r)},t.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},t.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},t.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},t.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},t.scannerPaused=function(){return"Scanner paused"},t})(),Wu=(function(){function t(){}return t.isMediaStreamConstraintsValid=function(r,i){if(typeof r!="object"){var c=typeof r;return i.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(c,"."),!0),!1}for(var d=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],f=new Set(d),m=Object.keys(r),x=0,v=m;x<v.length;x++){var g=v[x];if(f.has(g))return i.logError("".concat(g," is not supported videoConstaints."),!0),!1}return!0},t})(),To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function iw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qr={exports:{}},sw=qr.exports,ul;function aw(){return ul||(ul=1,(function(t,r){(function(i,c){c(r)})(sw,(function(i){function c(C){return C==null}var d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,e){C.__proto__=e}||function(C,e){for(var n in e)e.hasOwnProperty(n)&&(C[n]=e[n])};function f(C,e){d(C,e);function n(){this.constructor=C}C.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(C,e){var n=Object.setPrototypeOf;n?n(C,e):C.__proto__=e}function x(C,e){e===void 0&&(e=C.constructor);var n=Error.captureStackTrace;n&&n(C,e)}var v=(function(C){f(e,C);function e(n){var o=this.constructor,s=C.call(this,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1}),m(s,o.prototype),x(s),s}return e})(Error);class g extends v{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}g.kind="Exception";class E extends g{}E.kind="ArgumentException";class A extends g{}A.kind="IllegalArgumentException";class D{constructor(e){if(this.binarizer=e,e===null)throw new A("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,o,s){const a=this.binarizer.getLuminanceSource().crop(e,n,o,s);return new D(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new D(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new D(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class T extends g{static getChecksumInstance(){return new T}}T.kind="ChecksumException";class S{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class P{static arraycopy(e,n,o,s,a){for(;a--;)o[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class M extends g{}M.kind="IndexOutOfBoundsException";class ee extends M{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}ee.kind="ArrayIndexOutOfBoundsException";class ${static fill(e,n){for(let o=0,s=e.length;o<s;o++)e[o]=n}static fillWithin(e,n,o,s){$.rangeCheck(e.length,n,o);for(let a=n;a<o;a++)e[a]=s}static rangeCheck(e,n,o){if(n>o)throw new A("fromIndex("+n+") > toIndex("+o+")");if(n<0)throw new ee(n);if(o>e)throw new ee(o)}static asList(...e){return e}static create(e,n,o){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(o))}static createInt32Array(e,n,o){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(o))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let o=0,s=e.length;o<s;o++)if(e[o]!==n[o])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const o of e)n=31*n+o;return n}static fillUint8Array(e,n){for(let o=0;o!==e.length;o++)e[o]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const o=new Uint8Array(n);return o.set(e),o}return e.slice(0,n)}static copyOfRange(e,n,o){const s=o-n,a=new Int32Array(s);return P.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,o){o===void 0&&(o=$.numberComparator);let s=0,a=e.length-1;for(;s<=a;){const l=a+s>>1,u=o(n,e[l]);if(u>0)s=l+1;else if(u<0)a=l-1;else return l}return-s-1}static numberComparator(e,n){return e-n}}class F{static numberOfTrailingZeros(e){let n;if(e===0)return 32;let o=31;return n=e<<16,n!==0&&(o-=16,e=n),n=e<<8,n!==0&&(o-=8,e=n),n=e<<4,n!==0&&(o-=4,e=n),n=e<<2,n!==0&&(o-=2,e=n),o-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let n=1;return e>>>16||(n+=16,e<<=16),e>>>24||(n+=8,e<<=8),e>>>28||(n+=4,e<<=4),e>>>30||(n+=2,e<<=2),n-=e>>>31,n}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,n){return Math.trunc(e/n)}static parseInt(e,n=void 0){return parseInt(e,n)}}F.MIN_VALUE_32_BITS=-2147483648,F.MAX_VALUE=Number.MAX_SAFE_INTEGER;class re{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=re.makeArray(e):this.bits=n)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const n=re.makeArray(e);P.arraycopy(this.bits,0,n,0,this.bits.length),this.bits=n}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const n=this.size;if(e>=n)return n;const o=this.bits;let s=Math.floor(e/32),a=o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}getNextUnset(e){const n=this.size;if(e>=n)return n;const o=this.bits;let s=Math.floor(e/32),a=~o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=~o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}setBulk(e,n){this.bits[Math.floor(e/32)]=n}setRange(e,n){if(n<e||e<0||n>this.size)throw new A;if(n===e)return;n--;const o=Math.floor(e/32),s=Math.floor(n/32),a=this.bits;for(let l=o;l<=s;l++){const u=l>o?0:e&31,p=(2<<(l<s?31:n&31))-(1<<u);a[l]|=p}}clear(){const e=this.bits.length,n=this.bits;for(let o=0;o<e;o++)n[o]=0}isRange(e,n,o){if(n<e||e<0||n>this.size)throw new A;if(n===e)return!0;n--;const s=Math.floor(e/32),a=Math.floor(n/32),l=this.bits;for(let u=s;u<=a;u++){const h=u>s?0:e&31,y=(2<<(u<a?31:n&31))-(1<<h)&4294967295;if((l[u]&y)!==(o?y:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,n){if(n<0||n>32)throw new A("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(let o=n;o>0;o--)this.appendBit((e>>o-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let o=0;o<n;o++)this.appendBit(e.get(o))}xor(e){if(this.size!==e.size)throw new A("Sizes don't match");const n=this.bits;for(let o=0,s=n.length;o<s;o++)n[o]^=e.bits[o]}toBytes(e,n,o,s){for(let a=0;a<s;a++){let l=0;for(let u=0;u<8;u++)this.get(e)&&(l|=1<<7-u),e++;n[o+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),o=n+1,s=this.bits;for(let a=0;a<o;a++){let l=s[a];l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,e[n-a]=l}if(this.size!==o*32){const a=o*32-this.size;let l=e[0]>>>a;for(let u=1;u<o;u++){const h=e[u];l|=h<<32-a,e[u-1]=l,l=h>>>a}e[o-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof re))return!1;const n=e;return this.size===n.size&&$.equals(this.bits,n.bits)}hashCode(){return 31*this.size+$.hashCode(this.bits)}toString(){let e="";for(let n=0,o=this.size;n<o;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new re(this.size,this.bits.slice())}}var Z;(function(C){C[C.OTHER=0]="OTHER",C[C.PURE_BARCODE=1]="PURE_BARCODE",C[C.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",C[C.TRY_HARDER=3]="TRY_HARDER",C[C.CHARACTER_SET=4]="CHARACTER_SET",C[C.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",C[C.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",C[C.ASSUME_GS1=7]="ASSUME_GS1",C[C.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",C[C.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",C[C.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(Z||(Z={}));var B=Z;class L extends g{static getFormatInstance(){return new L}}L.kind="FormatException";var W;(function(C){C[C.Cp437=0]="Cp437",C[C.ISO8859_1=1]="ISO8859_1",C[C.ISO8859_2=2]="ISO8859_2",C[C.ISO8859_3=3]="ISO8859_3",C[C.ISO8859_4=4]="ISO8859_4",C[C.ISO8859_5=5]="ISO8859_5",C[C.ISO8859_6=6]="ISO8859_6",C[C.ISO8859_7=7]="ISO8859_7",C[C.ISO8859_8=8]="ISO8859_8",C[C.ISO8859_9=9]="ISO8859_9",C[C.ISO8859_10=10]="ISO8859_10",C[C.ISO8859_11=11]="ISO8859_11",C[C.ISO8859_13=12]="ISO8859_13",C[C.ISO8859_14=13]="ISO8859_14",C[C.ISO8859_15=14]="ISO8859_15",C[C.ISO8859_16=15]="ISO8859_16",C[C.SJIS=16]="SJIS",C[C.Cp1250=17]="Cp1250",C[C.Cp1251=18]="Cp1251",C[C.Cp1252=19]="Cp1252",C[C.Cp1256=20]="Cp1256",C[C.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",C[C.UTF8=22]="UTF8",C[C.ASCII=23]="ASCII",C[C.Big5=24]="Big5",C[C.GB18030=25]="GB18030",C[C.EUC_KR=26]="EUC_KR"})(W||(W={}));class z{constructor(e,n,o,...s){this.valueIdentifier=e,this.name=o,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,z.VALUE_IDENTIFIER_TO_ECI.set(e,this),z.NAME_TO_ECI.set(o,this);const a=this.values;for(let l=0,u=a.length;l!==u;l++){const h=a[l];z.VALUES_TO_ECI.set(h,this)}for(const l of s)z.NAME_TO_ECI.set(l,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new L("incorect value");const n=z.VALUES_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}static getCharacterSetECIByName(e){const n=z.NAME_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}equals(e){if(!(e instanceof z))return!1;const n=e;return this.getName()===n.getName()}}z.VALUE_IDENTIFIER_TO_ECI=new Map,z.VALUES_TO_ECI=new Map,z.NAME_TO_ECI=new Map,z.Cp437=new z(W.Cp437,Int32Array.from([0,2]),"Cp437"),z.ISO8859_1=new z(W.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),z.ISO8859_2=new z(W.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),z.ISO8859_3=new z(W.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),z.ISO8859_4=new z(W.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),z.ISO8859_5=new z(W.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),z.ISO8859_6=new z(W.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),z.ISO8859_7=new z(W.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),z.ISO8859_8=new z(W.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),z.ISO8859_9=new z(W.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),z.ISO8859_10=new z(W.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),z.ISO8859_11=new z(W.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),z.ISO8859_13=new z(W.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),z.ISO8859_14=new z(W.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),z.ISO8859_15=new z(W.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),z.ISO8859_16=new z(W.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),z.SJIS=new z(W.SJIS,20,"SJIS","Shift_JIS"),z.Cp1250=new z(W.Cp1250,21,"Cp1250","windows-1250"),z.Cp1251=new z(W.Cp1251,22,"Cp1251","windows-1251"),z.Cp1252=new z(W.Cp1252,23,"Cp1252","windows-1252"),z.Cp1256=new z(W.Cp1256,24,"Cp1256","windows-1256"),z.UnicodeBigUnmarked=new z(W.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),z.UTF8=new z(W.UTF8,26,"UTF8","UTF-8"),z.ASCII=new z(W.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),z.Big5=new z(W.Big5,28,"Big5"),z.GB18030=new z(W.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),z.EUC_KR=new z(W.EUC_KR,30,"EUC_KR","EUC-KR");class we extends g{}we.kind="UnsupportedOperationException";class G{static decode(e,n){const o=this.encodingName(n);return this.customDecoder?this.customDecoder(e,o):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(o)?this.decodeFallback(e,o):new TextDecoder(o).decode(e)}static shouldDecodeOnFallback(e){return!G.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const o=this.encodingName(n);return this.customEncoder?this.customEncoder(e,o):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof z?e:z.getCharacterSetECIByName(e)}static decodeFallback(e,n){const o=this.encodingCharacterSet(n);if(G.isDecodeFallbackSupported(o)){let s="";for(let a=0,l=e.length;a<l;a++){let u=e[a].toString(16);u.length<2&&(u="0"+u),s+="%"+u}return decodeURIComponent(s)}if(o.equals(z.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new we(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(z.UTF8)||e.equals(z.ISO8859_1)||e.equals(z.ASCII)}static encodeFallback(e){const o=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<o.length;a++)s.push(o[a].charCodeAt(0));return new Uint8Array(s)}}class me{static castAsNonUtf8Char(e,n=null){const o=n?n.getName():this.ISO88591;return G.decode(new Uint8Array([e]),o)}static guessEncoding(e,n){if(n!=null&&n.get(B.CHARACTER_SET)!==void 0)return n.get(B.CHARACTER_SET).toString();const o=e.length;let s=!0,a=!0,l=!0,u=0,h=0,p=0,y=0,b=0,I=0,R=0,U=0,V=0,H=0,Q=0;const he=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let pe=0;pe<o&&(s||a||l);pe++){const ce=e[pe]&255;l&&(u>0?(ce&128)===0?l=!1:u--:(ce&128)!==0&&((ce&64)===0?l=!1:(u++,(ce&32)===0?h++:(u++,(ce&16)===0?p++:(u++,(ce&8)===0?y++:l=!1))))),s&&(ce>127&&ce<160?s=!1:ce>159&&(ce<192||ce===215||ce===247)&&Q++),a&&(b>0?ce<64||ce===127||ce>252?a=!1:b--:ce===128||ce===160||ce>239?a=!1:ce>160&&ce<224?(I++,U=0,R++,R>V&&(V=R)):ce>127?(b++,R=0,U++,U>H&&(H=U)):(R=0,U=0))}return l&&u>0&&(l=!1),a&&b>0&&(a=!1),l&&(he||h+p+y>0)?me.UTF8:a&&(me.ASSUME_SHIFT_JIS||V>=3||H>=3)?me.SHIFT_JIS:s&&a?V===2&&I===2||Q*10>=o?me.SHIFT_JIS:me.ISO88591:s?me.ISO88591:a?me.SHIFT_JIS:l?me.UTF8:me.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let o=-1;function s(l,u,h,p,y,b){if(l==="%%")return"%";if(n[++o]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(b){case"s":R=n[o];break;case"c":R=n[o][0];break;case"f":R=parseFloat(n[o]).toFixed(l);break;case"p":R=parseFloat(n[o]).toPrecision(l);break;case"e":R=parseFloat(n[o]).toExponential(l);break;case"x":R=parseInt(n[o]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[o],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let U=parseInt(h),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<U;)R=u!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return G.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}me.SHIFT_JIS=z.SJIS.getName(),me.GB2312="GB2312",me.ISO88591=z.ISO8859_1.getName(),me.EUC_JP="EUC_JP",me.UTF8=z.UTF8.getName(),me.PLATFORM_DEFAULT_ENCODING=me.UTF8,me.ASSUME_SHIFT_JIS=!1;class fe{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=me.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,n,o){for(let s=n;n<n+o;s++)this.append(e[s]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+1)}substring(e,n){return this.value.substring(e,n)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+n.length)}}class te{constructor(e,n,o,s){if(this.width=e,this.height=n,this.rowSize=o,this.bits=s,n==null&&(n=e),this.height=n,e<1||n<1)throw new A("Both dimensions must be greater than 0");o==null&&(o=Math.floor((e+31)/32)),this.rowSize=o,s==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const n=e.length,o=e[0].length,s=new te(o,n);for(let a=0;a<n;a++){const l=e[a];for(let u=0;u<o;u++)l[u]&&s.set(u,a)}return s}static parseFromString(e,n,o){if(e===null)throw new A("stringRepresentation cannot be null");const s=new Array(e.length);let a=0,l=0,u=-1,h=0,p=0;for(;p<e.length;)if(e.charAt(p)===`
63
+ `||e.charAt(p)==="\r"){if(a>l){if(u===-1)u=a-l;else if(a-l!==u)throw new A("row lengths do not match");l=a,h++}p++}else if(e.substring(p,p+n.length)===n)p+=n.length,s[a]=!0,a++;else if(e.substring(p,p+o.length)===o)p+=o.length,s[a]=!1,a++;else throw new A("illegal character encountered: "+e.substring(p));if(a>l){if(u===-1)u=a-l;else if(a-l!==u)throw new A("row lengths do not match");h++}const y=new te(u,h);for(let b=0;b<a;b++)s[b]&&y.set(Math.floor(b%u),Math.floor(b/u));return y}get(e,n){const o=n*this.rowSize+Math.floor(e/32);return(this.bits[o]>>>(e&31)&1)!==0}set(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]|=1<<(e&31)&4294967295}unset(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]&=~(1<<(e&31)&4294967295)}flip(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]^=1<<(e&31)&4294967295}xor(e){if(this.width!==e.getWidth()||this.height!==e.getHeight()||this.rowSize!==e.getRowSize())throw new A("input matrix dimensions do not match");const n=new re(Math.floor(this.width/32)+1),o=this.rowSize,s=this.bits;for(let a=0,l=this.height;a<l;a++){const u=a*o,h=e.getRow(a,n).getBitArray();for(let p=0;p<o;p++)s[u+p]^=h[p]}}clear(){const e=this.bits,n=e.length;for(let o=0;o<n;o++)e[o]=0}setRegion(e,n,o,s){if(n<0||e<0)throw new A("Left and top must be nonnegative");if(s<1||o<1)throw new A("Height and width must be at least 1");const a=e+o,l=n+s;if(l>this.height||a>this.width)throw new A("The region must fit inside the matrix");const u=this.rowSize,h=this.bits;for(let p=n;p<l;p++){const y=p*u;for(let b=e;b<a;b++)h[y+Math.floor(b/32)]|=1<<(b&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new re(this.width):n.clear();const o=this.rowSize,s=this.bits,a=e*o;for(let l=0;l<o;l++)n.setBulk(l*32,s[a+l]);return n}setRow(e,n){P.arraycopy(n.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),n=this.getHeight();let o=new re(e),s=new re(e);for(let a=0,l=Math.floor((n+1)/2);a<l;a++)o=this.getRow(a,o),s=this.getRow(n-1-a,s),o.reverse(),s.reverse(),this.setRow(a,s),this.setRow(n-1-a,o)}getEnclosingRectangle(){const e=this.width,n=this.height,o=this.rowSize,s=this.bits;let a=e,l=n,u=-1,h=-1;for(let p=0;p<n;p++)for(let y=0;y<o;y++){const b=s[p*o+y];if(b!==0){if(p<l&&(l=p),p>h&&(h=p),y*32<a){let I=0;for(;(b<<31-I&4294967295)===0;)I++;y*32+I<a&&(a=y*32+I)}if(y*32+31>u){let I=31;for(;!(b>>>I);)I--;y*32+I>u&&(u=y*32+I)}}}return u<a||h<l?null:Int32Array.from([a,l,u-a+1,h-l+1])}getTopLeftOnBit(){const e=this.rowSize,n=this.bits;let o=0;for(;o<n.length&&n[o]===0;)o++;if(o===n.length)return null;const s=o/e;let a=o%e*32;const l=n[o];let u=0;for(;(l<<31-u&4294967295)===0;)u++;return a+=u,Int32Array.from([a,s])}getBottomRightOnBit(){const e=this.rowSize,n=this.bits;let o=n.length-1;for(;o>=0&&n[o]===0;)o--;if(o<0)return null;const s=Math.floor(o/e);let a=Math.floor(o%e)*32;const l=n[o];let u=31;for(;!(l>>>u);)u--;return a+=u,Int32Array.from([a,s])}getWidth(){return this.width}getHeight(){return this.height}getRowSize(){return this.rowSize}equals(e){if(!(e instanceof te))return!1;const n=e;return this.width===n.width&&this.height===n.height&&this.rowSize===n.rowSize&&$.equals(this.bits,n.bits)}hashCode(){let e=this.width;return e=31*e+this.width,e=31*e+this.height,e=31*e+this.rowSize,e=31*e+$.hashCode(this.bits),e}toString(e="X ",n=" ",o=`
64
+ `){return this.buildToString(e,n,o)}buildToString(e,n,o){let s=new fe;for(let a=0,l=this.height;a<l;a++){for(let u=0,h=this.width;u<h;u++)s.append(this.get(u,a)?e:n);s.append(o)}return s.toString()}clone(){return new te(this.width,this.height,this.rowSize,this.bits.slice())}}class q extends g{static getNotFoundInstance(){return new q}}q.kind="NotFoundException";class ke extends S{constructor(e){super(e),this.luminances=ke.EMPTY,this.buckets=new Int32Array(ke.LUMINANCE_BUCKETS)}getBlackRow(e,n){const o=this.getLuminanceSource(),s=o.getWidth();n==null||n.getSize()<s?n=new re(s):n.clear(),this.initArrays(s);const a=o.getRow(e,this.luminances),l=this.buckets;for(let h=0;h<s;h++)l[(a[h]&255)>>ke.LUMINANCE_SHIFT]++;const u=ke.estimateBlackPoint(l);if(s<3)for(let h=0;h<s;h++)(a[h]&255)<u&&n.set(h);else{let h=a[0]&255,p=a[1]&255;for(let y=1;y<s-1;y++){const b=a[y+1]&255;(p*4-h-b)/2<u&&n.set(y),h=p,p=b}}return n}getBlackMatrix(){const e=this.getLuminanceSource(),n=e.getWidth(),o=e.getHeight(),s=new te(n,o);this.initArrays(n);const a=this.buckets;for(let h=1;h<5;h++){const p=Math.floor(o*h/5),y=e.getRow(p,this.luminances),b=Math.floor(n*4/5);for(let I=Math.floor(n/5);I<b;I++){const R=y[I]&255;a[R>>ke.LUMINANCE_SHIFT]++}}const l=ke.estimateBlackPoint(a),u=e.getMatrix();for(let h=0;h<o;h++){const p=h*n;for(let y=0;y<n;y++)(u[p+y]&255)<l&&s.set(y,h)}return s}createBinarizer(e){return new ke(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const n=this.buckets;for(let o=0;o<ke.LUMINANCE_BUCKETS;o++)n[o]=0}static estimateBlackPoint(e){const n=e.length;let o=0,s=0,a=0;for(let y=0;y<n;y++)e[y]>a&&(s=y,a=e[y]),e[y]>o&&(o=e[y]);let l=0,u=0;for(let y=0;y<n;y++){const b=y-s,I=e[y]*b*b;I>u&&(l=y,u=I)}if(s>l){const y=s;s=l,l=y}if(l-s<=n/16)throw new q;let h=l-1,p=-1;for(let y=l-1;y>s;y--){const b=y-s,I=b*b*(l-y)*(o-e[y]);I>p&&(h=y,p=I)}return h<<ke.LUMINANCE_SHIFT}}ke.LUMINANCE_BITS=5,ke.LUMINANCE_SHIFT=8-ke.LUMINANCE_BITS,ke.LUMINANCE_BUCKETS=1<<ke.LUMINANCE_BITS,ke.EMPTY=Uint8ClampedArray.from([0]);class le extends ke{constructor(e){super(e),this.matrix=null}getBlackMatrix(){if(this.matrix!==null)return this.matrix;const e=this.getLuminanceSource(),n=e.getWidth(),o=e.getHeight();if(n>=le.MINIMUM_DIMENSION&&o>=le.MINIMUM_DIMENSION){const s=e.getMatrix();let a=n>>le.BLOCK_SIZE_POWER;(n&le.BLOCK_SIZE_MASK)!==0&&a++;let l=o>>le.BLOCK_SIZE_POWER;(o&le.BLOCK_SIZE_MASK)!==0&&l++;const u=le.calculateBlackPoints(s,a,l,n,o),h=new te(n,o);le.calculateThresholdForBlock(s,a,l,n,o,u,h),this.matrix=h}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new le(e)}static calculateThresholdForBlock(e,n,o,s,a,l,u){const h=a-le.BLOCK_SIZE,p=s-le.BLOCK_SIZE;for(let y=0;y<o;y++){let b=y<<le.BLOCK_SIZE_POWER;b>h&&(b=h);const I=le.cap(y,2,o-3);for(let R=0;R<n;R++){let U=R<<le.BLOCK_SIZE_POWER;U>p&&(U=p);const V=le.cap(R,2,n-3);let H=0;for(let he=-2;he<=2;he++){const pe=l[I+he];H+=pe[V-2]+pe[V-1]+pe[V]+pe[V+1]+pe[V+2]}const Q=H/25;le.thresholdBlock(e,U,b,Q,s,u)}}}static cap(e,n,o){return e<n?n:e>o?o:e}static thresholdBlock(e,n,o,s,a,l){for(let u=0,h=o*a+n;u<le.BLOCK_SIZE;u++,h+=a)for(let p=0;p<le.BLOCK_SIZE;p++)(e[h+p]&255)<=s&&l.set(n+p,o+u)}static calculateBlackPoints(e,n,o,s,a){const l=a-le.BLOCK_SIZE,u=s-le.BLOCK_SIZE,h=new Array(o);for(let p=0;p<o;p++){h[p]=new Int32Array(n);let y=p<<le.BLOCK_SIZE_POWER;y>l&&(y=l);for(let b=0;b<n;b++){let I=b<<le.BLOCK_SIZE_POWER;I>u&&(I=u);let R=0,U=255,V=0;for(let Q=0,he=y*s+I;Q<le.BLOCK_SIZE;Q++,he+=s){for(let pe=0;pe<le.BLOCK_SIZE;pe++){const ce=e[he+pe]&255;R+=ce,ce<U&&(U=ce),ce>V&&(V=ce)}if(V-U>le.MIN_DYNAMIC_RANGE)for(Q++,he+=s;Q<le.BLOCK_SIZE;Q++,he+=s)for(let pe=0;pe<le.BLOCK_SIZE;pe++)R+=e[he+pe]&255}let H=R>>le.BLOCK_SIZE_POWER*2;if(V-U<=le.MIN_DYNAMIC_RANGE&&(H=U/2,p>0&&b>0)){const Q=(h[p-1][b]+2*h[p][b-1]+h[p-1][b-1])/4;U<Q&&(H=Q)}h[p][b]=H}}return h}}le.BLOCK_SIZE_POWER=3,le.BLOCK_SIZE=1<<le.BLOCK_SIZE_POWER,le.BLOCK_SIZE_MASK=le.BLOCK_SIZE-1,le.MINIMUM_DIMENSION=le.BLOCK_SIZE*5,le.MIN_DYNAMIC_RANGE=24;class Te{constructor(e,n){this.width=e,this.height=n}getWidth(){return this.width}getHeight(){return this.height}isCropSupported(){return!1}crop(e,n,o,s){throw new we("This luminance source does not support cropping.")}isRotateSupported(){return!1}rotateCounterClockwise(){throw new we("This luminance source does not support rotation by 90 degrees.")}rotateCounterClockwise45(){throw new we("This luminance source does not support rotation by 45 degrees.")}toString(){const e=new Uint8ClampedArray(this.width);let n=new fe;for(let o=0;o<this.height;o++){const s=this.getRow(o,e);for(let a=0;a<this.width;a++){const l=s[a]&255;let u;l<64?u="#":l<128?u="+":l<192?u=".":u=" ",n.append(u)}n.append(`
65
+ `)}return n.toString()}}class Je extends Te{constructor(e){super(e.getWidth(),e.getHeight()),this.delegate=e}getRow(e,n){const o=this.delegate.getRow(e,n),s=this.getWidth();for(let a=0;a<s;a++)o[a]=255-(o[a]&255);return o}getMatrix(){const e=this.delegate.getMatrix(),n=this.getWidth()*this.getHeight(),o=new Uint8ClampedArray(n);for(let s=0;s<n;s++)o[s]=255-(e[s]&255);return o}isCropSupported(){return this.delegate.isCropSupported()}crop(e,n,o,s){return new Je(this.delegate.crop(e,n,o,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new Je(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new Je(this.delegate.rotateCounterClockwise45())}}class xe extends Te{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=xe.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return xe.toGrayscaleBuffer(n.data,e.width,e.height)}static toGrayscaleBuffer(e,n,o){const s=new Uint8ClampedArray(n*o);for(let a=0,l=0,u=e.length;a<u;a+=4,l++){let h;if(e[a+3]===0)h=255;else{const y=e[a],b=e[a+1],I=e[a+2];h=306*y+601*b+117*I+512>>10}s[l]=h}return s}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const o=this.getWidth(),s=e*o;return n===null?n=this.buffer.slice(s,s+o):(n.length<o&&(n=new Uint8ClampedArray(o)),n.set(this.buffer.slice(s,s+o))),n}getMatrix(){return this.buffer}isCropSupported(){return!0}crop(e,n,o,s){return super.crop(e,n,o,s),this}isRotateSupported(){return!0}rotateCounterClockwise(){return this.rotate(-90),this}rotateCounterClockwise45(){return this.rotate(-45),this}getTempCanvasElement(){if(this.tempCanvasElement===null){const e=this.canvas.ownerDocument.createElement("canvas");e.width=this.canvas.width,e.height=this.canvas.height,this.tempCanvasElement=e}return this.tempCanvasElement}rotate(e){const n=this.getTempCanvasElement(),o=n.getContext("2d"),s=e*xe.DEGREE_TO_RADIANS,a=this.canvas.width,l=this.canvas.height,u=Math.ceil(Math.abs(Math.cos(s))*a+Math.abs(Math.sin(s))*l),h=Math.ceil(Math.abs(Math.sin(s))*a+Math.abs(Math.cos(s))*l);return n.width=u,n.height=h,o.translate(u/2,h/2),o.rotate(s),o.drawImage(this.canvas,a/-2,l/-2),this.buffer=xe.makeBufferFromCanvasImageData(n),this}invert(){return new Je(this)}}xe.DEGREE_TO_RADIANS=Math.PI/180;class $e{constructor(e,n,o){this.deviceId=e,this.label=n,this.kind="videoinput",this.groupId=o||void 0}toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}}}var Ue=(globalThis||To||self||window||void 0)&&(globalThis||To||self||window||void 0).__awaiter||function(C,e,n,o){function s(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function u(y){try{p(o.next(y))}catch(b){l(b)}}function h(y){try{p(o.throw(y))}catch(b){l(b)}}function p(y){y.done?a(y.value):s(y.value).then(u,h)}p((o=o.apply(C,e||[])).next())})};class Ze{constructor(e,n=500,o){this.reader=e,this.timeBetweenScansMillis=n,this._hints=o,this._stopContinuousDecode=!1,this._stopAsyncDecode=!1,this._timeBetweenDecodingAttempts=0}get hasNavigator(){return typeof navigator<"u"}get isMediaDevicesSuported(){return this.hasNavigator&&!!navigator.mediaDevices}get canEnumerateDevices(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices)}get timeBetweenDecodingAttempts(){return this._timeBetweenDecodingAttempts}set timeBetweenDecodingAttempts(e){this._timeBetweenDecodingAttempts=e<0?0:e}set hints(e){this._hints=e||null}get hints(){return this._hints}listVideoInputDevices(){return Ue(this,void 0,void 0,function*(){if(!this.hasNavigator)throw new Error("Can't enumerate devices, navigator is not present.");if(!this.canEnumerateDevices)throw new Error("Can't enumerate devices, method not supported.");const e=yield navigator.mediaDevices.enumerateDevices(),n=[];for(const o of e){const s=o.kind==="video"?"videoinput":o.kind;if(s!=="videoinput")continue;const a=o.deviceId||o.id,l=o.label||`Video device ${n.length+1}`,u=o.groupId,h={deviceId:a,label:l,kind:s,groupId:u};n.push(h)}return n})}getVideoInputDevices(){return Ue(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new $e(n.deviceId,n.label))})}findDeviceById(e){return Ue(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(o=>o.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return Ue(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return Ue(this,void 0,void 0,function*(){this.reset();let o;e?o={deviceId:{exact:e}}:o={facingMode:"environment"};const s={video:o};return yield this.decodeOnceFromConstraints(s,n)})}decodeOnceFromConstraints(e,n){return Ue(this,void 0,void 0,function*(){const o=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(o,n)})}decodeOnceFromStream(e,n){return Ue(this,void 0,void 0,function*(){this.reset();const o=yield this.attachStreamToVideo(e,n);return yield this.decodeOnce(o)})}decodeFromInputVideoDeviceContinuously(e,n,o){return Ue(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,o)})}decodeFromVideoDevice(e,n,o){return Ue(this,void 0,void 0,function*(){let s;e?s={deviceId:{exact:e}}:s={facingMode:"environment"};const a={video:s};return yield this.decodeFromConstraints(a,n,o)})}decodeFromConstraints(e,n,o){return Ue(this,void 0,void 0,function*(){const s=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeFromStream(s,n,o)})}decodeFromStream(e,n,o){return Ue(this,void 0,void 0,function*(){this.reset();const s=yield this.attachStreamToVideo(e,n);return yield this.decodeContinuously(s,o)})}stopAsyncDecode(){this._stopAsyncDecode=!0}stopContinuousDecode(){this._stopContinuousDecode=!0}attachStreamToVideo(e,n){return Ue(this,void 0,void 0,function*(){const o=this.prepareVideoElement(n);return this.addVideoSource(o,e),this.videoElement=o,this.stream=e,yield this.playVideoOnLoadAsync(o),o})}playVideoOnLoadAsync(e){return new Promise((n,o)=>this.playVideoOnLoad(e,()=>n()))}playVideoOnLoad(e,n){this.videoEndedListener=()=>this.stopStreams(),this.videoCanPlayListener=()=>this.tryPlayVideo(e),e.addEventListener("ended",this.videoEndedListener),e.addEventListener("canplay",this.videoCanPlayListener),e.addEventListener("playing",n),this.tryPlayVideo(e)}isVideoPlaying(e){return e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2}tryPlayVideo(e){return Ue(this,void 0,void 0,function*(){if(this.isVideoPlaying(e)){console.warn("Trying to play video that is already playing.");return}try{yield e.play()}catch{console.warn("It was not possible to play the video.")}})}getMediaElement(e,n){const o=document.getElementById(e);if(!o)throw new E(`element with id '${e}' not found`);if(o.nodeName.toLowerCase()!==n.toLowerCase())throw new E(`element with id '${e}' must be an ${n} element`);return o}decodeFromImage(e,n){if(!e&&!n)throw new E("either imageElement with a src set or an url must be provided");return n&&!e?this.decodeFromImageUrl(n):this.decodeFromImageElement(e)}decodeFromVideo(e,n){if(!e&&!n)throw new E("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrl(n):this.decodeFromVideoElement(e)}decodeFromVideoContinuously(e,n,o){if(e===void 0&&n===void 0)throw new E("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrlContinuously(n,o):this.decodeFromVideoElementContinuously(e,o)}decodeFromImageElement(e){if(!e)throw new E("An image element must be provided.");this.reset();const n=this.prepareImageElement(e);this.imageElement=n;let o;return this.isImageLoaded(n)?o=this.decodeOnce(n,!1,!0):o=this._decodeOnLoadImage(n),o}decodeFromVideoElement(e){const n=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideo(n)}decodeFromVideoElementContinuously(e,n){const o=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideoContinuously(o,n)}_decodeFromVideoElementSetup(e){if(!e)throw new E("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new E("An URL must be provided.");this.reset();const n=this.prepareImageElement();this.imageElement=n;const o=this._decodeOnLoadImage(n);return n.src=e,o}decodeFromVideoUrl(e){if(!e)throw new E("An URL must be provided.");this.reset();const n=this.prepareVideoElement(),o=this.decodeFromVideoElement(n);return n.src=e,o}decodeFromVideoUrlContinuously(e,n){if(!e)throw new E("An URL must be provided.");this.reset();const o=this.prepareVideoElement(),s=this.decodeFromVideoElementContinuously(o,n);return o.src=e,s}_decodeOnLoadImage(e){return new Promise((n,o)=>{this.imageLoadedListener=()=>this.decodeOnce(e,!1,!0).then(n,o),e.addEventListener("load",this.imageLoadedListener)})}_decodeOnLoadVideo(e){return Ue(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return Ue(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(e),this.decodeContinuously(e,n)})}isImageLoaded(e){return!(!e.complete||e.naturalWidth===0)}prepareImageElement(e){let n;return typeof e>"u"&&(n=document.createElement("img"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"img")),e instanceof HTMLImageElement&&(n=e),n}prepareVideoElement(e){let n;return!e&&typeof document<"u"&&(n=document.createElement("video"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"video")),e instanceof HTMLVideoElement&&(n=e),n.setAttribute("autoplay","true"),n.setAttribute("muted","true"),n.setAttribute("playsinline","true"),n}decodeOnce(e,n=!0,o=!0){this._stopAsyncDecode=!1;const s=(a,l)=>{if(this._stopAsyncDecode){l(new q("Video stream has ended before any code could be detected.")),this._stopAsyncDecode=void 0;return}try{const u=this.decode(e);a(u)}catch(u){const h=n&&u instanceof q,y=(u instanceof T||u instanceof L)&&o;if(h||y)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(u)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const o=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(o,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof T||s instanceof L,l=s instanceof q;(a||l)&&setTimeout(o,this._timeBetweenDecodingAttempts)}};o()}decode(e){const n=this.createBinaryBitmap(e);return this.decodeBitmap(n)}_isHTMLVideoElement(e){return e.videoWidth!==0}drawFrameOnCanvas(e,n,o){n||(n={sx:0,sy:0,sWidth:e.videoWidth,sHeight:e.videoHeight,dx:0,dy:0,dWidth:e.videoWidth,dHeight:e.videoHeight}),o||(o=this.captureCanvasContext),o.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}drawImageOnCanvas(e,n,o=this.captureCanvasContext){n||(n={sx:0,sy:0,sWidth:e.naturalWidth,sHeight:e.naturalHeight,dx:0,dy:0,dWidth:e.naturalWidth,dHeight:e.naturalHeight}),o||(o=this.captureCanvasContext),o.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}createBinaryBitmap(e){this.getCaptureCanvasContext(e),this._isHTMLVideoElement(e)?this.drawFrameOnCanvas(e):this.drawImageOnCanvas(e);const n=this.getCaptureCanvas(e),o=new xe(n),s=new le(o);return new D(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const o=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=o}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const n=this.createCaptureCanvas(e);this.captureCanvas=n}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const n=document.createElement("canvas");let o,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(o=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(o=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=o+"px",n.style.height=s+"px",n.width=o,n.height=s,n}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,n){try{e.srcObject=n}catch{e.src=URL.createObjectURL(n)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class qe{constructor(e,n,o=n==null?0:8*n.length,s,a,l=P.currentTimeMillis()){this.text=e,this.rawBytes=n,this.numBits=o,this.resultPoints=s,this.format=a,this.timestamp=l,this.text=e,this.rawBytes=n,o==null?this.numBits=n==null?0:8*n.length:this.numBits=o,this.resultPoints=s,this.format=a,this.resultMetadata=null,l==null?this.timestamp=P.currentTimeMillis():this.timestamp=l}getText(){return this.text}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}getResultPoints(){return this.resultPoints}getBarcodeFormat(){return this.format}getResultMetadata(){return this.resultMetadata}putMetadata(e,n){this.resultMetadata===null&&(this.resultMetadata=new Map),this.resultMetadata.set(e,n)}putAllMetadata(e){e!==null&&(this.resultMetadata===null?this.resultMetadata=e:this.resultMetadata=new Map(e))}addResultPoints(e){const n=this.resultPoints;if(n===null)this.resultPoints=e;else if(e!==null&&e.length>0){const o=new Array(n.length+e.length);P.arraycopy(n,0,o,0,n.length),P.arraycopy(e,0,o,n.length,e.length),this.resultPoints=o}}getTimestamp(){return this.timestamp}toString(){return this.text}}var ze;(function(C){C[C.AZTEC=0]="AZTEC",C[C.CODABAR=1]="CODABAR",C[C.CODE_39=2]="CODE_39",C[C.CODE_93=3]="CODE_93",C[C.CODE_128=4]="CODE_128",C[C.DATA_MATRIX=5]="DATA_MATRIX",C[C.EAN_8=6]="EAN_8",C[C.EAN_13=7]="EAN_13",C[C.ITF=8]="ITF",C[C.MAXICODE=9]="MAXICODE",C[C.PDF_417=10]="PDF_417",C[C.QR_CODE=11]="QR_CODE",C[C.RSS_14=12]="RSS_14",C[C.RSS_EXPANDED=13]="RSS_EXPANDED",C[C.UPC_A=14]="UPC_A",C[C.UPC_E=15]="UPC_E",C[C.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(ze||(ze={}));var ie=ze,de;(function(C){C[C.OTHER=0]="OTHER",C[C.ORIENTATION=1]="ORIENTATION",C[C.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",C[C.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",C[C.ISSUE_NUMBER=4]="ISSUE_NUMBER",C[C.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",C[C.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",C[C.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",C[C.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",C[C.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",C[C.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(de||(de={}));var _e=de;class Pe{constructor(e,n,o,s,a=-1,l=-1){this.rawBytes=e,this.text=n,this.byteSegments=o,this.ecLevel=s,this.structuredAppendSequenceNumber=a,this.structuredAppendParity=l,this.numBits=e==null?0:8*e.length}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}setNumBits(e){this.numBits=e}getText(){return this.text}getByteSegments(){return this.byteSegments}getECLevel(){return this.ecLevel}getErrorsCorrected(){return this.errorsCorrected}setErrorsCorrected(e){this.errorsCorrected=e}getErasures(){return this.erasures}setErasures(e){this.erasures=e}getOther(){return this.other}setOther(e){this.other=e}hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0}getStructuredAppendParity(){return this.structuredAppendParity}getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber}}class ae{exp(e){return this.expTable[e]}log(e){if(e===0)throw new A;return this.logTable[e]}static addOrSubtract(e,n){return e^n}}class J{constructor(e,n){if(n.length===0)throw new A;this.field=e;const o=n.length;if(o>1&&n[0]===0){let s=1;for(;s<o&&n[s]===0;)s++;s===o?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(o-s),P.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);const n=this.coefficients;let o;if(e===1){o=0;for(let l=0,u=n.length;l!==u;l++){const h=n[l];o=ae.addOrSubtract(o,h)}return o}o=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)o=ae.addOrSubtract(a.multiply(e,o),n[l]);return o}addOrSubtract(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,o=e.coefficients;if(n.length>o.length){const l=n;n=o,o=l}let s=new Int32Array(o.length);const a=o.length-n.length;P.arraycopy(o,0,s,0,a);for(let l=a;l<o.length;l++)s[l]=ae.addOrSubtract(n[l-a],o[l]);return new J(this.field,s)}multiply(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero()||e.isZero())return this.field.getZero();const n=this.coefficients,o=n.length,s=e.coefficients,a=s.length,l=new Int32Array(o+a-1),u=this.field;for(let h=0;h<o;h++){const p=n[h];for(let y=0;y<a;y++)l[h+y]=ae.addOrSubtract(l[h+y],u.multiply(p,s[y]))}return new J(u,l)}multiplyScalar(e){if(e===0)return this.field.getZero();if(e===1)return this;const n=this.coefficients.length,o=this.field,s=new Int32Array(n),a=this.coefficients;for(let l=0;l<n;l++)s[l]=o.multiply(a[l],e);return new J(o,s)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return this.field.getZero();const o=this.coefficients,s=o.length,a=new Int32Array(s+e),l=this.field;for(let u=0;u<s;u++)a[u]=l.multiply(o[u],n);return new J(l,a)}divide(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(e.isZero())throw new A("Divide by 0");const n=this.field;let o=n.getZero(),s=this;const a=e.getCoefficient(e.getDegree()),l=n.inverse(a);for(;s.getDegree()>=e.getDegree()&&!s.isZero();){const u=s.getDegree()-e.getDegree(),h=n.multiply(s.getCoefficient(s.getDegree()),l),p=e.multiplyByMonomial(u,h),y=n.buildMonomial(u,h);o=o.addOrSubtract(y),s=s.addOrSubtract(p)}return[o,s]}toString(){let e="";for(let n=this.getDegree();n>=0;n--){let o=this.getCoefficient(n);if(o!==0){if(o<0?(e+=" - ",o=-o):e.length>0&&(e+=" + "),n===0||o!==1){const s=this.field.log(o);s===0?e+="1":s===1?e+="a":(e+="a^",e+=s)}n!==0&&(n===1?e+="x":(e+="x^",e+=n))}}return e}}class ye extends g{}ye.kind="ArithmeticException";class Se extends ae{constructor(e,n,o){super(),this.primitive=e,this.size=n,this.generatorBase=o;const s=new Int32Array(n);let a=1;for(let u=0;u<n;u++)s[u]=a,a*=2,a>=n&&(a^=e,a&=n-1);this.expTable=s;const l=new Int32Array(n);for(let u=0;u<n-1;u++)l[s[u]]=u;this.logTable=l,this.zero=new J(this,Int32Array.from([0])),this.one=new J(this,Int32Array.from([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;const o=new Int32Array(e+1);return o[0]=n,new J(this,o)}inverse(e){if(e===0)throw new ye;return this.expTable[this.size-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.size-1)]}getSize(){return this.size}getGeneratorBase(){return this.generatorBase}toString(){return"GF(0x"+F.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}Se.AZTEC_DATA_12=new Se(4201,4096,1),Se.AZTEC_DATA_10=new Se(1033,1024,1),Se.AZTEC_DATA_6=new Se(67,64,1),Se.AZTEC_PARAM=new Se(19,16,1),Se.QR_CODE_FIELD_256=new Se(285,256,0),Se.DATA_MATRIX_FIELD_256=new Se(301,256,1),Se.AZTEC_DATA_8=Se.DATA_MATRIX_FIELD_256,Se.MAXICODE_FIELD_64=Se.AZTEC_DATA_6;class Ve extends g{}Ve.kind="ReedSolomonException";class St extends g{}St.kind="IllegalStateException";class vt{constructor(e){this.field=e}decode(e,n){const o=this.field,s=new J(o,e),a=new Int32Array(n);let l=!0;for(let R=0;R<n;R++){const U=s.evaluateAt(o.exp(R+o.getGeneratorBase()));a[a.length-1-R]=U,U!==0&&(l=!1)}if(l)return;const u=new J(o,a),h=this.runEuclideanAlgorithm(o.buildMonomial(n,1),u,n),p=h[0],y=h[1],b=this.findErrorLocations(p),I=this.findErrorMagnitudes(y,b);for(let R=0;R<b.length;R++){const U=e.length-1-o.log(b[R]);if(U<0)throw new Ve("Bad error location");e[U]=Se.addOrSubtract(e[U],I[R])}}runEuclideanAlgorithm(e,n,o){if(e.getDegree()<n.getDegree()){const R=e;e=n,n=R}const s=this.field;let a=e,l=n,u=s.getZero(),h=s.getOne();for(;l.getDegree()>=(o/2|0);){let R=a,U=u;if(a=l,u=h,a.isZero())throw new Ve("r_{i-1} was zero");l=R;let V=s.getZero();const H=a.getCoefficient(a.getDegree()),Q=s.inverse(H);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const he=l.getDegree()-a.getDegree(),pe=s.multiply(l.getCoefficient(l.getDegree()),Q);V=V.addOrSubtract(s.buildMonomial(he,pe)),l=l.addOrSubtract(a.multiplyByMonomial(he,pe))}if(h=V.multiply(u).addOrSubtract(U),l.getDegree()>=a.getDegree())throw new St("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new Ve("sigmaTilde(0) was zero");const y=s.inverse(p),b=h.multiplyScalar(y),I=l.multiplyScalar(y);return[b,I]}findErrorLocations(e){const n=e.getDegree();if(n===1)return Int32Array.from([e.getCoefficient(1)]);const o=new Int32Array(n);let s=0;const a=this.field;for(let l=1;l<a.getSize()&&s<n;l++)e.evaluateAt(l)===0&&(o[s]=a.inverse(l),s++);if(s!==n)throw new Ve("Error locator degree does not match number of roots");return o}findErrorMagnitudes(e,n){const o=n.length,s=new Int32Array(o),a=this.field;for(let l=0;l<o;l++){const u=a.inverse(n[l]);let h=1;for(let p=0;p<o;p++)if(l!==p){const y=a.multiply(n[p],u),b=(y&1)===0?y|1:y&-2;h=a.multiply(h,b)}s[l]=a.multiply(e.evaluateAt(u),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],u))}return s}}var et;(function(C){C[C.UPPER=0]="UPPER",C[C.LOWER=1]="LOWER",C[C.MIXED=2]="MIXED",C[C.DIGIT=3]="DIGIT",C[C.PUNCT=4]="PUNCT",C[C.BINARY=5]="BINARY"})(et||(et={}));class nt{decode(e){this.ddata=e;let n=e.getBits(),o=this.extractBits(n),s=this.correctBits(o),a=nt.convertBoolArrayToByteArray(s),l=nt.getEncodedData(s),u=new Pe(a,l,null,null);return u.setNumBits(s.length),u}static highLevelDecode(e){return this.getEncodedData(e)}static getEncodedData(e){let n=e.length,o=et.UPPER,s=et.UPPER,a="",l=0;for(;l<n;)if(s===et.BINARY){if(n-l<5)break;let u=nt.readCode(e,l,5);if(l+=5,u===0){if(n-l<11)break;u=nt.readCode(e,l,11)+31,l+=11}for(let h=0;h<u;h++){if(n-l<8){l=n;break}const p=nt.readCode(e,l,8);a+=me.castAsNonUtf8Char(p),l+=8}s=o}else{let u=s===et.DIGIT?4:5;if(n-l<u)break;let h=nt.readCode(e,l,u);l+=u;let p=nt.getCharacter(s,h);p.startsWith("CTRL_")?(o=s,s=nt.getTable(p.charAt(5)),p.charAt(6)==="L"&&(o=s)):(a+=p,s=o)}return a}static getTable(e){switch(e){case"L":return et.LOWER;case"P":return et.PUNCT;case"M":return et.MIXED;case"D":return et.DIGIT;case"B":return et.BINARY;case"U":default:return et.UPPER}}static getCharacter(e,n){switch(e){case et.UPPER:return nt.UPPER_TABLE[n];case et.LOWER:return nt.LOWER_TABLE[n];case et.MIXED:return nt.MIXED_TABLE[n];case et.PUNCT:return nt.PUNCT_TABLE[n];case et.DIGIT:return nt.DIGIT_TABLE[n];default:throw new St("Bad table")}}correctBits(e){let n,o;this.ddata.getNbLayers()<=2?(o=6,n=Se.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(o=8,n=Se.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(o=10,n=Se.AZTEC_DATA_10):(o=12,n=Se.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/o;if(a<s)throw new L;let l=e.length%o,u=new Int32Array(a);for(let I=0;I<a;I++,l+=o)u[I]=nt.readCode(e,l,o);try{new vt(n).decode(u,a-s)}catch(I){throw new L(I)}let h=(1<<o)-1,p=0;for(let I=0;I<s;I++){let R=u[I];if(R===0||R===h)throw new L;(R===1||R===h-1)&&p++}let y=new Array(s*o-p),b=0;for(let I=0;I<s;I++){let R=u[I];if(R===1||R===h-1)y.fill(R>1,b,b+o-1),b+=o-1;else for(let U=o-1;U>=0;--U)y[b++]=(R&1<<U)!==0}return y}extractBits(e){let n=this.ddata.isCompact(),o=this.ddata.getNbLayers(),s=(n?11:14)+o*4,a=new Int32Array(s),l=new Array(this.totalBitsInLayer(o,n));if(n)for(let u=0;u<a.length;u++)a[u]=u;else{let u=s+1+2*F.truncDivision(F.truncDivision(s,2)-1,15),h=s/2,p=F.truncDivision(u,2);for(let y=0;y<h;y++){let b=y+F.truncDivision(y,15);a[h-y-1]=p-b-1,a[h+y]=p+b+1}}for(let u=0,h=0;u<o;u++){let p=(o-u)*4+(n?9:12),y=u*2,b=s-1-y;for(let I=0;I<p;I++){let R=I*2;for(let U=0;U<2;U++)l[h+R+U]=e.get(a[y+U],a[y+I]),l[h+2*p+R+U]=e.get(a[y+I],a[b-U]),l[h+4*p+R+U]=e.get(a[b-U],a[b-I]),l[h+6*p+R+U]=e.get(a[b-I],a[y+U])}h+=p*8}return l}static readCode(e,n,o){let s=0;for(let a=n;a<n+o;a++)s<<=1,e[a]&&(s|=1);return s}static readByte(e,n){let o=e.length-n;return o>=8?nt.readCode(e,n,8):nt.readCode(e,n,o)<<8-o}static convertBoolArrayToByteArray(e){let n=new Uint8Array((e.length+7)/8);for(let o=0;o<n.length;o++)n[o]=nt.readByte(e,8*o);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}nt.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],nt.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],nt.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
66
+ `,"\\13","\f","\r","\\33","\\34","\\35","\\36","\\37","@","\\","^","_","`","|","~","\\177","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],nt.PUNCT_TABLE=["","\r",`\r
67
+ `,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],nt.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class Xe{constructor(){}static round(e){return e===NaN?0:e<=Number.MIN_SAFE_INTEGER?Number.MIN_SAFE_INTEGER:e>=Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+(e<0?-.5:.5)|0}static distance(e,n,o,s){const a=e-o,l=n-s;return Math.sqrt(a*a+l*l)}static sum(e){let n=0;for(let o=0,s=e.length;o!==s;o++){const a=e[o];n+=a}return n}}class In{static floatToIntBits(e){return e}}In.MAX_VALUE=Number.MAX_SAFE_INTEGER;class be{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof be){const n=e;return this.x===n.x&&this.y===n.y}return!1}hashCode(){return 31*In.floatToIntBits(this.x)+In.floatToIntBits(this.y)}toString(){return"("+this.x+","+this.y+")"}static orderBestPatterns(e){const n=this.distance(e[0],e[1]),o=this.distance(e[1],e[2]),s=this.distance(e[0],e[2]);let a,l,u;if(o>=n&&o>=s?(l=e[0],a=e[1],u=e[2]):s>=o&&s>=n?(l=e[1],a=e[0],u=e[2]):(l=e[2],a=e[0],u=e[1]),this.crossProductZ(a,l,u)<0){const h=a;a=u,u=h}e[0]=a,e[1]=l,e[2]=u}static distance(e,n){return Xe.distance(e.x,e.y,n.x,n.y)}static crossProductZ(e,n,o){const s=n.x,a=n.y;return(o.x-s)*(e.y-a)-(o.y-a)*(e.x-s)}}class Bn{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class $n extends Bn{constructor(e,n,o,s,a){super(e,n),this.compact=o,this.nbDatablocks=s,this.nbLayers=a}getNbLayers(){return this.nbLayers}getNbDatablocks(){return this.nbDatablocks}isCompact(){return this.compact}}class qt{constructor(e,n,o,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=qt.INIT_SIZE),o==null&&(o=e.getWidth()/2|0),s==null&&(s=e.getHeight()/2|0);const a=n/2|0;if(this.leftInit=o-a,this.rightInit=o+a,this.upInit=s-a,this.downInit=s+a,this.upInit<0||this.leftInit<0||this.downInit>=this.height||this.rightInit>=this.width)throw new q}detect(){let e=this.leftInit,n=this.rightInit,o=this.upInit,s=this.downInit,a=!1,l=!0,u=!1,h=!1,p=!1,y=!1,b=!1;const I=this.width,R=this.height;for(;l;){l=!1;let U=!0;for(;(U||!h)&&n<I;)U=this.containsBlackPoint(o,s,n,!1),U?(n++,l=!0,h=!0):h||n++;if(n>=I){a=!0;break}let V=!0;for(;(V||!p)&&s<R;)V=this.containsBlackPoint(e,n,s,!0),V?(s++,l=!0,p=!0):p||s++;if(s>=R){a=!0;break}let H=!0;for(;(H||!y)&&e>=0;)H=this.containsBlackPoint(o,s,e,!1),H?(e--,l=!0,y=!0):y||e--;if(e<0){a=!0;break}let Q=!0;for(;(Q||!b)&&o>=0;)Q=this.containsBlackPoint(e,n,o,!0),Q?(o--,l=!0,b=!0):b||o--;if(o<0){a=!0;break}l&&(u=!0)}if(!a&&u){const U=n-e;let V=null;for(let pe=1;V===null&&pe<U;pe++)V=this.getBlackPointOnSegment(e,s-pe,e+pe,s);if(V==null)throw new q;let H=null;for(let pe=1;H===null&&pe<U;pe++)H=this.getBlackPointOnSegment(e,o+pe,e+pe,o);if(H==null)throw new q;let Q=null;for(let pe=1;Q===null&&pe<U;pe++)Q=this.getBlackPointOnSegment(n,o+pe,n-pe,o);if(Q==null)throw new q;let he=null;for(let pe=1;he===null&&pe<U;pe++)he=this.getBlackPointOnSegment(n,s-pe,n-pe,s);if(he==null)throw new q;return this.centerEdges(he,V,Q,H)}else throw new q}getBlackPointOnSegment(e,n,o,s){const a=Xe.round(Xe.distance(e,n,o,s)),l=(o-e)/a,u=(s-n)/a,h=this.image;for(let p=0;p<a;p++){const y=Xe.round(e+p*l),b=Xe.round(n+p*u);if(h.get(y,b))return new be(y,b)}return null}centerEdges(e,n,o,s){const a=e.getX(),l=e.getY(),u=n.getX(),h=n.getY(),p=o.getX(),y=o.getY(),b=s.getX(),I=s.getY(),R=qt.CORR;return a<this.width/2?[new be(b-R,I+R),new be(u+R,h+R),new be(p-R,y-R),new be(a+R,l-R)]:[new be(b+R,I+R),new be(u+R,h-R),new be(p-R,y+R),new be(a-R,l-R)]}containsBlackPoint(e,n,o,s){const a=this.image;if(s){for(let l=e;l<=n;l++)if(a.get(l,o))return!0}else for(let l=e;l<=n;l++)if(a.get(o,l))return!0;return!1}}qt.INIT_SIZE=10,qt.CORR=1;class jn{static checkAndNudgePoints(e,n){const o=e.getWidth(),s=e.getHeight();let a=!0;for(let l=0;l<n.length&&a;l+=2){const u=Math.floor(n[l]),h=Math.floor(n[l+1]);if(u<-1||u>o||h<-1||h>s)throw new q;a=!1,u===-1?(n[l]=0,a=!0):u===o&&(n[l]=o-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}a=!0;for(let l=n.length-2;l>=0&&a;l-=2){const u=Math.floor(n[l]),h=Math.floor(n[l+1]);if(u<-1||u>o||h<-1||h>s)throw new q;a=!1,u===-1?(n[l]=0,a=!0):u===o&&(n[l]=o-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}}}class Ft{constructor(e,n,o,s,a,l,u,h,p){this.a11=e,this.a21=n,this.a31=o,this.a12=s,this.a22=a,this.a32=l,this.a13=u,this.a23=h,this.a33=p}static quadrilateralToQuadrilateral(e,n,o,s,a,l,u,h,p,y,b,I,R,U,V,H){const Q=Ft.quadrilateralToSquare(e,n,o,s,a,l,u,h);return Ft.squareToQuadrilateral(p,y,b,I,R,U,V,H).times(Q)}transformPoints(e){const n=e.length,o=this.a11,s=this.a12,a=this.a13,l=this.a21,u=this.a22,h=this.a23,p=this.a31,y=this.a32,b=this.a33;for(let I=0;I<n;I+=2){const R=e[I],U=e[I+1],V=a*R+h*U+b;e[I]=(o*R+l*U+p)/V,e[I+1]=(s*R+u*U+y)/V}}transformPointsWithValues(e,n){const o=this.a11,s=this.a12,a=this.a13,l=this.a21,u=this.a22,h=this.a23,p=this.a31,y=this.a32,b=this.a33,I=e.length;for(let R=0;R<I;R++){const U=e[R],V=n[R],H=a*U+h*V+b;e[R]=(o*U+l*V+p)/H,n[R]=(s*U+u*V+y)/H}}static squareToQuadrilateral(e,n,o,s,a,l,u,h){const p=e-o+a-u,y=n-s+l-h;if(p===0&&y===0)return new Ft(o-e,a-o,e,s-n,l-s,n,0,0,1);{const b=o-a,I=u-a,R=s-l,U=h-l,V=b*U-I*R,H=(p*U-I*y)/V,Q=(b*y-p*R)/V;return new Ft(o-e+H*o,u-e+Q*u,e,s-n+H*s,h-n+Q*h,n,H,Q,1)}}static quadrilateralToSquare(e,n,o,s,a,l,u,h){return Ft.squareToQuadrilateral(e,n,o,s,a,l,u,h).buildAdjoint()}buildAdjoint(){return new Ft(this.a22*this.a33-this.a23*this.a32,this.a23*this.a31-this.a21*this.a33,this.a21*this.a32-this.a22*this.a31,this.a13*this.a32-this.a12*this.a33,this.a11*this.a33-this.a13*this.a31,this.a12*this.a31-this.a11*this.a32,this.a12*this.a23-this.a13*this.a22,this.a13*this.a21-this.a11*this.a23,this.a11*this.a22-this.a12*this.a21)}times(e){return new Ft(this.a11*e.a11+this.a21*e.a12+this.a31*e.a13,this.a11*e.a21+this.a21*e.a22+this.a31*e.a23,this.a11*e.a31+this.a21*e.a32+this.a31*e.a33,this.a12*e.a11+this.a22*e.a12+this.a32*e.a13,this.a12*e.a21+this.a22*e.a22+this.a32*e.a23,this.a12*e.a31+this.a22*e.a32+this.a32*e.a33,this.a13*e.a11+this.a23*e.a12+this.a33*e.a13,this.a13*e.a21+this.a23*e.a22+this.a33*e.a23,this.a13*e.a31+this.a23*e.a32+this.a33*e.a33)}}class rr extends jn{sampleGrid(e,n,o,s,a,l,u,h,p,y,b,I,R,U,V,H,Q,he,pe){const ce=Ft.quadrilateralToQuadrilateral(s,a,l,u,h,p,y,b,I,R,U,V,H,Q,he,pe);return this.sampleGridWithTransform(e,n,o,ce)}sampleGridWithTransform(e,n,o,s){if(n<=0||o<=0)throw new q;const a=new te(n,o),l=new Float32Array(2*n);for(let u=0;u<o;u++){const h=l.length,p=u+.5;for(let y=0;y<h;y+=2)l[y]=y/2+.5,l[y+1]=p;s.transformPoints(l),jn.checkAndNudgePoints(e,l);try{for(let y=0;y<h;y+=2)e.get(Math.floor(l[y]),Math.floor(l[y+1]))&&a.set(y/2,u)}catch{throw new q}}return a}}class sn{static setGridSampler(e){sn.gridSampler=e}static getInstance(){return sn.gridSampler}}sn.gridSampler=new rr;class At{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new be(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class or{constructor(e){this.EXPECTED_CORNER_BITS=new Int32Array([3808,476,2107,1799]),this.image=e}detect(){return this.detectMirror(!1)}detectMirror(e){let n=this.getMatrixCenter(),o=this.getBullsEyeCorners(n);if(e){let l=o[0];o[0]=o[2],o[2]=l}this.extractParameters(o);let s=this.sampleGrid(this.image,o[this.shift%4],o[(this.shift+1)%4],o[(this.shift+2)%4],o[(this.shift+3)%4]),a=this.getMatrixCornerPoints(o);return new $n(s,a,this.compact,this.nbDataBlocks,this.nbLayers)}extractParameters(e){if(!this.isValidPoint(e[0])||!this.isValidPoint(e[1])||!this.isValidPoint(e[2])||!this.isValidPoint(e[3]))throw new q;let n=2*this.nbCenterLayers,o=new Int32Array([this.sampleLine(e[0],e[1],n),this.sampleLine(e[1],e[2],n),this.sampleLine(e[2],e[3],n),this.sampleLine(e[3],e[0],n)]);this.shift=this.getRotation(o,n);let s=0;for(let l=0;l<4;l++){let u=o[(this.shift+l)%4];this.compact?(s<<=7,s+=u>>1&127):(s<<=10,s+=(u>>2&992)+(u>>1&31))}let a=this.getCorrectedParameterData(s,this.compact);this.compact?(this.nbLayers=(a>>6)+1,this.nbDataBlocks=(a&63)+1):(this.nbLayers=(a>>11)+1,this.nbDataBlocks=(a&2047)+1)}getRotation(e,n){let o=0;e.forEach((s,a,l)=>{let u=(s>>n-2<<1)+(s&1);o=(o<<3)+u}),o=((o&1)<<11)+(o>>1);for(let s=0;s<4;s++)if(F.bitCount(o^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new q}getCorrectedParameterData(e,n){let o,s;n?(o=7,s=2):(o=10,s=4);let a=o-s,l=new Int32Array(o);for(let h=o-1;h>=0;--h)l[h]=e&15,e>>=4;try{new vt(Se.AZTEC_PARAM).decode(l,a)}catch{throw new q}let u=0;for(let h=0;h<s;h++)u=(u<<4)+l[h];return u}getBullsEyeCorners(e){let n=e,o=e,s=e,a=e,l=!0;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){let b=this.getFirstDifferent(n,l,1,-1),I=this.getFirstDifferent(o,l,1,1),R=this.getFirstDifferent(s,l,-1,1),U=this.getFirstDifferent(a,l,-1,-1);if(this.nbCenterLayers>2){let V=this.distancePoint(U,b)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(V<.75||V>1.25||!this.isWhiteOrBlackRectangle(b,I,R,U))break}n=b,o=I,s=R,a=U,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new q;this.compact=this.nbCenterLayers===5;let u=new be(n.getX()+.5,n.getY()-.5),h=new be(o.getX()+.5,o.getY()+.5),p=new be(s.getX()-.5,s.getY()+.5),y=new be(a.getX()-.5,a.getY()-.5);return this.expandSquare([u,h,p,y],2*this.nbCenterLayers-3,2*this.nbCenterLayers)}getMatrixCenter(){let e,n,o,s;try{let u=new qt(this.image).detect();e=u[0],n=u[1],o=u[2],s=u[3]}catch{let h=this.image.getWidth()/2,p=this.image.getHeight()/2;e=this.getFirstDifferent(new At(h+7,p-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new At(h+7,p+7),!1,1,1).toResultPoint(),o=this.getFirstDifferent(new At(h-7,p+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new At(h-7,p-7),!1,-1,-1).toResultPoint()}let a=Xe.round((e.getX()+s.getX()+n.getX()+o.getX())/4),l=Xe.round((e.getY()+s.getY()+n.getY()+o.getY())/4);try{let u=new qt(this.image,15,a,l).detect();e=u[0],n=u[1],o=u[2],s=u[3]}catch{e=this.getFirstDifferent(new At(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new At(a+7,l+7),!1,1,1).toResultPoint(),o=this.getFirstDifferent(new At(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new At(a-7,l-7),!1,-1,-1).toResultPoint()}return a=Xe.round((e.getX()+s.getX()+n.getX()+o.getX())/4),l=Xe.round((e.getY()+s.getY()+n.getY()+o.getY())/4),new At(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,o,s,a){let l=sn.getInstance(),u=this.getDimension(),h=u/2-this.nbCenterLayers,p=u/2+this.nbCenterLayers;return l.sampleGrid(e,u,u,h,h,p,h,p,p,h,p,n.getX(),n.getY(),o.getX(),o.getY(),s.getX(),s.getY(),a.getX(),a.getY())}sampleLine(e,n,o){let s=0,a=this.distanceResultPoint(e,n),l=a/o,u=e.getX(),h=e.getY(),p=l*(n.getX()-e.getX())/a,y=l*(n.getY()-e.getY())/a;for(let b=0;b<o;b++)this.image.get(Xe.round(u+b*p),Xe.round(h+b*y))&&(s|=1<<o-b-1);return s}isWhiteOrBlackRectangle(e,n,o,s){let a=3;e=new At(e.getX()-a,e.getY()+a),n=new At(n.getX()-a,n.getY()-a),o=new At(o.getX()+a,o.getY()-a),s=new At(s.getX()+a,s.getY()+a);let l=this.getColor(s,e);if(l===0)return!1;let u=this.getColor(e,n);return u!==l||(u=this.getColor(n,o),u!==l)?!1:(u=this.getColor(o,s),u===l)}getColor(e,n){let o=this.distancePoint(e,n),s=(n.getX()-e.getX())/o,a=(n.getY()-e.getY())/o,l=0,u=e.getX(),h=e.getY(),p=this.image.get(e.getX(),e.getY()),y=Math.ceil(o);for(let I=0;I<y;I++)u+=s,h+=a,this.image.get(Xe.round(u),Xe.round(h))!==p&&l++;let b=l/o;return b>.1&&b<.9?0:b<=.1===p?1:-1}getFirstDifferent(e,n,o,s){let a=e.getX()+o,l=e.getY()+s;for(;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=o,l+=s;for(a-=o,l-=s;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=o;for(a-=o;this.isValid(a,l)&&this.image.get(a,l)===n;)l+=s;return l-=s,new At(a,l)}expandSquare(e,n,o){let s=o/(2*n),a=e[0].getX()-e[2].getX(),l=e[0].getY()-e[2].getY(),u=(e[0].getX()+e[2].getX())/2,h=(e[0].getY()+e[2].getY())/2,p=new be(u+s*a,h+s*l),y=new be(u-s*a,h-s*l);a=e[1].getX()-e[3].getX(),l=e[1].getY()-e[3].getY(),u=(e[1].getX()+e[3].getX())/2,h=(e[1].getY()+e[3].getY())/2;let b=new be(u+s*a,h+s*l),I=new be(u-s*a,h-s*l);return[p,b,y,I]}isValid(e,n){return e>=0&&e<this.image.getWidth()&&n>0&&n<this.image.getHeight()}isValidPoint(e){let n=Xe.round(e.getX()),o=Xe.round(e.getY());return this.isValid(n,o)}distancePoint(e,n){return Xe.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return Xe.distance(e.getX(),e.getY(),n.getX(),n.getY())}getDimension(){return this.compact?4*this.nbLayers+11:this.nbLayers<=4?4*this.nbLayers+15:4*this.nbLayers+2*(F.truncDivision(this.nbLayers-4,8)+1)+15}}class Ln{decode(e,n=null){let o=null,s=new or(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new nt().decode(y)}catch(y){o=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new nt().decode(y)}catch(y){throw o??y}let u=new qe(l.getText(),l.getRawBytes(),l.getNumBits(),a,ie.AZTEC,P.currentTimeMillis()),h=l.getByteSegments();h!=null&&u.putMetadata(_e.BYTE_SEGMENTS,h);let p=l.getECLevel();return p!=null&&u.putMetadata(_e.ERROR_CORRECTION_LEVEL,p),u}reportFoundResultPoints(e,n){if(e!=null){let o=e.get(B.NEED_RESULT_POINT_CALLBACK);o!=null&&n.forEach((s,a,l)=>{o.foundPossibleResultPoint(s)})}}reset(){}}class wr extends Ze{constructor(e=500){super(new Ln,e)}}class gt{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(B.TRY_HARDER)===!0&&e.isRotateSupported()){const a=e.rotateCounterClockwise(),l=this.doDecode(a,n),u=l.getResultMetadata();let h=270;u!==null&&u.get(_e.ORIENTATION)===!0&&(h=h+u.get(_e.ORIENTATION)%360),l.putMetadata(_e.ORIENTATION,h);const p=l.getResultPoints();if(p!==null){const y=a.getHeight();for(let b=0;b<p.length;b++)p[b]=new be(y-p[b].getY()-1,p[b].getX())}return l}else throw new q}}reset(){}doDecode(e,n){const o=e.getWidth(),s=e.getHeight();let a=new re(o);const l=n&&n.get(B.TRY_HARDER)===!0,u=Math.max(1,s>>(l?8:5));let h;l?h=s:h=15;const p=Math.trunc(s/2);for(let y=0;y<h;y++){const b=Math.trunc((y+1)/2),I=(y&1)===0,R=p+u*(I?b:-b);if(R<0||R>=s)break;try{a=e.getBlackRow(R,a)}catch{continue}for(let U=0;U<2;U++){if(U===1&&(a.reverse(),n&&n.get(B.NEED_RESULT_POINT_CALLBACK)===!0)){const V=new Map;n.forEach((H,Q)=>V.set(Q,H)),V.delete(B.NEED_RESULT_POINT_CALLBACK),n=V}try{const V=this.decodeRow(R,a,n);if(U===1){V.putMetadata(_e.ORIENTATION,180);const H=V.getResultPoints();H!==null&&(H[0]=new be(o-H[0].getX()-1,H[0].getY()),H[1]=new be(o-H[1].getX()-1,H[1].getY()))}return V}catch{}}}throw new q}static recordPattern(e,n,o){const s=o.length;for(let p=0;p<s;p++)o[p]=0;const a=e.getSize();if(n>=a)throw new q;let l=!e.get(n),u=0,h=n;for(;h<a;){if(e.get(h)!==l)o[u]++;else{if(++u===s)break;o[u]=1,l=!l}h++}if(!(u===s||u===s-1&&h===a))throw new q}static recordPatternInReverse(e,n,o){let s=o.length,a=e.get(n);for(;n>0&&s>=0;)e.get(--n)!==a&&(s--,a=!a);if(s>=0)throw new q;gt.recordPattern(e,n+1,o)}static patternMatchVariance(e,n,o){const s=e.length;let a=0,l=0;for(let p=0;p<s;p++)a+=e[p],l+=n[p];if(a<l)return Number.POSITIVE_INFINITY;const u=a/l;o*=u;let h=0;for(let p=0;p<s;p++){const y=e[p],b=n[p]*u,I=y>b?y-b:b-y;if(I>o)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class ge extends gt{static findStartPattern(e){const n=e.getSize(),o=e.getNextSet(0);let s=0,a=Int32Array.from([0,0,0,0,0,0]),l=o,u=!1;const h=6;for(let p=o;p<n;p++)if(e.get(p)!==u)a[s]++;else{if(s===h-1){let y=ge.MAX_AVG_VARIANCE,b=-1;for(let I=ge.CODE_START_A;I<=ge.CODE_START_C;I++){const R=gt.patternMatchVariance(a,ge.CODE_PATTERNS[I],ge.MAX_INDIVIDUAL_VARIANCE);R<y&&(y=R,b=I)}if(b>=0&&e.isRange(Math.max(0,l-(p-l)/2),l,!1))return Int32Array.from([l,p,b]);l+=a[0]+a[1],a=a.slice(2,a.length-1),a[s-1]=0,a[s]=0,s--}else s++;a[s]=1,u=!u}throw new q}static decodeCode(e,n,o){gt.recordPattern(e,o,n);let s=ge.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<ge.CODE_PATTERNS.length;l++){const u=ge.CODE_PATTERNS[l],h=this.patternMatchVariance(n,u,ge.MAX_INDIVIDUAL_VARIANCE);h<s&&(s=h,a=l)}if(a>=0)return a;throw new q}decodeRow(e,n,o){const s=o&&o.get(B.ASSUME_GS1)===!0,a=ge.findStartPattern(n),l=a[2];let u=0;const h=new Uint8Array(20);h[u++]=l;let p;switch(l){case ge.CODE_START_A:p=ge.CODE_CODE_A;break;case ge.CODE_START_B:p=ge.CODE_CODE_B;break;case ge.CODE_START_C:p=ge.CODE_CODE_C;break;default:throw new L}let y=!1,b=!1,I="",R=a[0],U=a[1];const V=Int32Array.from([0,0,0,0,0,0]);let H=0,Q=0,he=l,pe=0,ce=!0,Ke=!1,He=!1;for(;!y;){const Tr=b;switch(b=!1,H=Q,Q=ge.decodeCode(n,V,U),h[u++]=Q,Q!==ge.CODE_STOP&&(ce=!0),Q!==ge.CODE_STOP&&(pe++,he+=pe*Q),R=U,U+=V.reduce((bd,Ad)=>bd+Ad,0),Q){case ge.CODE_START_A:case ge.CODE_START_B:case ge.CODE_START_C:throw new L}switch(p){case ge.CODE_CODE_A:if(Q<64)He===Ke?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),He=!1;else if(Q<96)He===Ke?I+=String.fromCharCode(Q-64):I+=String.fromCharCode(Q+64),He=!1;else switch(Q!==ge.CODE_STOP&&(ce=!1),Q){case ge.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case ge.CODE_FNC_2:case ge.CODE_FNC_3:break;case ge.CODE_FNC_4_A:!Ke&&He?(Ke=!0,He=!1):Ke&&He?(Ke=!1,He=!1):He=!0;break;case ge.CODE_SHIFT:b=!0,p=ge.CODE_CODE_B;break;case ge.CODE_CODE_B:p=ge.CODE_CODE_B;break;case ge.CODE_CODE_C:p=ge.CODE_CODE_C;break;case ge.CODE_STOP:y=!0;break}break;case ge.CODE_CODE_B:if(Q<96)He===Ke?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),He=!1;else switch(Q!==ge.CODE_STOP&&(ce=!1),Q){case ge.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case ge.CODE_FNC_2:case ge.CODE_FNC_3:break;case ge.CODE_FNC_4_B:!Ke&&He?(Ke=!0,He=!1):Ke&&He?(Ke=!1,He=!1):He=!0;break;case ge.CODE_SHIFT:b=!0,p=ge.CODE_CODE_A;break;case ge.CODE_CODE_A:p=ge.CODE_CODE_A;break;case ge.CODE_CODE_C:p=ge.CODE_CODE_C;break;case ge.CODE_STOP:y=!0;break}break;case ge.CODE_CODE_C:if(Q<100)Q<10&&(I+="0"),I+=Q;else switch(Q!==ge.CODE_STOP&&(ce=!1),Q){case ge.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case ge.CODE_CODE_A:p=ge.CODE_CODE_A;break;case ge.CODE_CODE_B:p=ge.CODE_CODE_B;break;case ge.CODE_STOP:y=!0;break}break}Tr&&(p=p===ge.CODE_CODE_A?ge.CODE_CODE_B:ge.CODE_CODE_A)}const tn=U-R;if(U=n.getNextUnset(U),!n.isRange(U,Math.min(n.getSize(),U+(U-R)/2),!1))throw new q;if(he-=pe*H,he%103!==H)throw new T;const yn=I.length;if(yn===0)throw new q;yn>0&&ce&&(p===ge.CODE_CODE_C?I=I.substring(0,yn-2):I=I.substring(0,yn-1));const nn=(a[1]+a[0])/2,ft=R+tn/2,Ht=h.length,an=new Uint8Array(Ht);for(let Tr=0;Tr<Ht;Tr++)an[Tr]=h[Tr];const Sr=[new be(nn,e),new be(ft,e)];return new qe(I,an,0,Sr,ie.CODE_128,new Date().getTime())}}ge.CODE_PATTERNS=[Int32Array.from([2,1,2,2,2,2]),Int32Array.from([2,2,2,1,2,2]),Int32Array.from([2,2,2,2,2,1]),Int32Array.from([1,2,1,2,2,3]),Int32Array.from([1,2,1,3,2,2]),Int32Array.from([1,3,1,2,2,2]),Int32Array.from([1,2,2,2,1,3]),Int32Array.from([1,2,2,3,1,2]),Int32Array.from([1,3,2,2,1,2]),Int32Array.from([2,2,1,2,1,3]),Int32Array.from([2,2,1,3,1,2]),Int32Array.from([2,3,1,2,1,2]),Int32Array.from([1,1,2,2,3,2]),Int32Array.from([1,2,2,1,3,2]),Int32Array.from([1,2,2,2,3,1]),Int32Array.from([1,1,3,2,2,2]),Int32Array.from([1,2,3,1,2,2]),Int32Array.from([1,2,3,2,2,1]),Int32Array.from([2,2,3,2,1,1]),Int32Array.from([2,2,1,1,3,2]),Int32Array.from([2,2,1,2,3,1]),Int32Array.from([2,1,3,2,1,2]),Int32Array.from([2,2,3,1,1,2]),Int32Array.from([3,1,2,1,3,1]),Int32Array.from([3,1,1,2,2,2]),Int32Array.from([3,2,1,1,2,2]),Int32Array.from([3,2,1,2,2,1]),Int32Array.from([3,1,2,2,1,2]),Int32Array.from([3,2,2,1,1,2]),Int32Array.from([3,2,2,2,1,1]),Int32Array.from([2,1,2,1,2,3]),Int32Array.from([2,1,2,3,2,1]),Int32Array.from([2,3,2,1,2,1]),Int32Array.from([1,1,1,3,2,3]),Int32Array.from([1,3,1,1,2,3]),Int32Array.from([1,3,1,3,2,1]),Int32Array.from([1,1,2,3,1,3]),Int32Array.from([1,3,2,1,1,3]),Int32Array.from([1,3,2,3,1,1]),Int32Array.from([2,1,1,3,1,3]),Int32Array.from([2,3,1,1,1,3]),Int32Array.from([2,3,1,3,1,1]),Int32Array.from([1,1,2,1,3,3]),Int32Array.from([1,1,2,3,3,1]),Int32Array.from([1,3,2,1,3,1]),Int32Array.from([1,1,3,1,2,3]),Int32Array.from([1,1,3,3,2,1]),Int32Array.from([1,3,3,1,2,1]),Int32Array.from([3,1,3,1,2,1]),Int32Array.from([2,1,1,3,3,1]),Int32Array.from([2,3,1,1,3,1]),Int32Array.from([2,1,3,1,1,3]),Int32Array.from([2,1,3,3,1,1]),Int32Array.from([2,1,3,1,3,1]),Int32Array.from([3,1,1,1,2,3]),Int32Array.from([3,1,1,3,2,1]),Int32Array.from([3,3,1,1,2,1]),Int32Array.from([3,1,2,1,1,3]),Int32Array.from([3,1,2,3,1,1]),Int32Array.from([3,3,2,1,1,1]),Int32Array.from([3,1,4,1,1,1]),Int32Array.from([2,2,1,4,1,1]),Int32Array.from([4,3,1,1,1,1]),Int32Array.from([1,1,1,2,2,4]),Int32Array.from([1,1,1,4,2,2]),Int32Array.from([1,2,1,1,2,4]),Int32Array.from([1,2,1,4,2,1]),Int32Array.from([1,4,1,1,2,2]),Int32Array.from([1,4,1,2,2,1]),Int32Array.from([1,1,2,2,1,4]),Int32Array.from([1,1,2,4,1,2]),Int32Array.from([1,2,2,1,1,4]),Int32Array.from([1,2,2,4,1,1]),Int32Array.from([1,4,2,1,1,2]),Int32Array.from([1,4,2,2,1,1]),Int32Array.from([2,4,1,2,1,1]),Int32Array.from([2,2,1,1,1,4]),Int32Array.from([4,1,3,1,1,1]),Int32Array.from([2,4,1,1,1,2]),Int32Array.from([1,3,4,1,1,1]),Int32Array.from([1,1,1,2,4,2]),Int32Array.from([1,2,1,1,4,2]),Int32Array.from([1,2,1,2,4,1]),Int32Array.from([1,1,4,2,1,2]),Int32Array.from([1,2,4,1,1,2]),Int32Array.from([1,2,4,2,1,1]),Int32Array.from([4,1,1,2,1,2]),Int32Array.from([4,2,1,1,1,2]),Int32Array.from([4,2,1,2,1,1]),Int32Array.from([2,1,2,1,4,1]),Int32Array.from([2,1,4,1,2,1]),Int32Array.from([4,1,2,1,2,1]),Int32Array.from([1,1,1,1,4,3]),Int32Array.from([1,1,1,3,4,1]),Int32Array.from([1,3,1,1,4,1]),Int32Array.from([1,1,4,1,1,3]),Int32Array.from([1,1,4,3,1,1]),Int32Array.from([4,1,1,1,1,3]),Int32Array.from([4,1,1,3,1,1]),Int32Array.from([1,1,3,1,4,1]),Int32Array.from([1,1,4,1,3,1]),Int32Array.from([3,1,1,1,4,1]),Int32Array.from([4,1,1,1,3,1]),Int32Array.from([2,1,1,4,1,2]),Int32Array.from([2,1,1,2,1,4]),Int32Array.from([2,1,1,2,3,2]),Int32Array.from([2,3,3,1,1,1,2])],ge.MAX_AVG_VARIANCE=.25,ge.MAX_INDIVIDUAL_VARIANCE=.7,ge.CODE_SHIFT=98,ge.CODE_CODE_C=99,ge.CODE_CODE_B=100,ge.CODE_CODE_A=101,ge.CODE_FNC_1=102,ge.CODE_FNC_2=97,ge.CODE_FNC_3=96,ge.CODE_FNC_4_A=101,ge.CODE_FNC_4_B=100,ge.CODE_START_A=103,ge.CODE_START_B=104,ge.CODE_START_C=105,ge.CODE_STOP=106;class O extends gt{constructor(e=!1,n=!1){super(),this.usingCheckDigit=e,this.extendedMode=n,this.decodeRowResult="",this.counters=new Int32Array(9)}decodeRow(e,n,o){let s=this.counters;s.fill(0),this.decodeRowResult="";let a=O.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),u=n.getSize(),h,p;do{O.recordPattern(n,l,s);let V=O.toNarrowWidePattern(s);if(V<0)throw new q;h=O.patternToChar(V),this.decodeRowResult+=h,p=l;for(let H of s)l+=H;l=n.getNextSet(l)}while(h!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let y=0;for(let V of s)y+=V;let b=l-p-y;if(l!==u&&b*2<y)throw new q;if(this.usingCheckDigit){let V=this.decodeRowResult.length-1,H=0;for(let Q=0;Q<V;Q++)H+=O.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(Q));if(this.decodeRowResult.charAt(V)!==O.ALPHABET_STRING.charAt(H%43))throw new T;this.decodeRowResult=this.decodeRowResult.substring(0,V)}if(this.decodeRowResult.length===0)throw new q;let I;this.extendedMode?I=O.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let R=(a[1]+a[0])/2,U=p+y/2;return new qe(I,null,0,[new be(R,e),new be(U,e)],ie.CODE_39,new Date().getTime())}static findAsteriskPattern(e,n){let o=e.getSize(),s=e.getNextSet(0),a=0,l=s,u=!1,h=n.length;for(let p=s;p<o;p++)if(e.get(p)!==u)n[a]++;else{if(a===h-1){if(this.toNarrowWidePattern(n)===O.ASTERISK_ENCODING&&e.isRange(Math.max(0,l-Math.floor((p-l)/2)),l,!1))return[l,p];l+=n[0]+n[1],n.copyWithin(0,2,2+a-1),n[a-1]=0,n[a]=0,a--}else a++;n[a]=1,u=!u}throw new q}static toNarrowWidePattern(e){let n=e.length,o=0,s;do{let a=2147483647;for(let h of e)h<a&&h>o&&(a=h);o=a,s=0;let l=0,u=0;for(let h=0;h<n;h++){let p=e[h];p>o&&(u|=1<<n-1-h,s++,l+=p)}if(s===3){for(let h=0;h<n&&s>0;h++){let p=e[h];if(p>o&&(s--,p*2>=l))return-1}return u}}while(s>3);return-1}static patternToChar(e){for(let n=0;n<O.CHARACTER_ENCODINGS.length;n++)if(O.CHARACTER_ENCODINGS[n]===e)return O.ALPHABET_STRING.charAt(n);if(e===O.ASTERISK_ENCODING)return"*";throw new q}static decodeExtended(e){let n=e.length,o="";for(let s=0;s<n;s++){let a=e.charAt(s);if(a==="+"||a==="$"||a==="%"||a==="/"){let l=e.charAt(s+1),u="\0";switch(a){case"+":if(l>="A"&&l<="Z")u=String.fromCharCode(l.charCodeAt(0)+32);else throw new L;break;case"$":if(l>="A"&&l<="Z")u=String.fromCharCode(l.charCodeAt(0)-64);else throw new L;break;case"%":if(l>="A"&&l<="E")u=String.fromCharCode(l.charCodeAt(0)-38);else if(l>="F"&&l<="J")u=String.fromCharCode(l.charCodeAt(0)-11);else if(l>="K"&&l<="O")u=String.fromCharCode(l.charCodeAt(0)+16);else if(l>="P"&&l<="T")u=String.fromCharCode(l.charCodeAt(0)+43);else if(l==="U")u="\0";else if(l==="V")u="@";else if(l==="W")u="`";else if(l==="X"||l==="Y"||l==="Z")u="";else throw new L;break;case"/":if(l>="A"&&l<="O")u=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")u=":";else throw new L;break}o+=u,s++}else o+=a}return o}}O.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",O.CHARACTER_ENCODINGS=[52,289,97,352,49,304,112,37,292,100,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,168,162,138,42],O.ASTERISK_ENCODING=148;class ne extends gt{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,o){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new fe;ne.decodeMiddle(n,s[1],a[0],l);let u=l.toString(),h=null;o!=null&&(h=o.get(B.ALLOWED_LENGTHS)),h==null&&(h=ne.DEFAULT_ALLOWED_LENGTHS);let p=u.length,y=!1,b=0;for(let U of h){if(p===U){y=!0;break}U>b&&(b=U)}if(!y&&p>b&&(y=!0),!y)throw new L;const I=[new be(s[1],e),new be(a[0],e)];return new qe(u,null,0,I,ie.ITF,new Date().getTime())}static decodeMiddle(e,n,o,s){let a=new Int32Array(10),l=new Int32Array(5),u=new Int32Array(5);for(a.fill(0),l.fill(0),u.fill(0);n<o;){gt.recordPattern(e,n,a);for(let p=0;p<5;p++){let y=2*p;l[p]=a[y],u[p]=a[y+1]}let h=ne.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(u),s.append(h.toString()),a.forEach(function(p){n+=p})}}decodeStart(e){let n=ne.skipWhiteSpace(e),o=ne.findGuardPattern(e,n,ne.START_PATTERN);return this.narrowLineWidth=(o[1]-o[0])/4,this.validateQuietZone(e,o[0]),o}validateQuietZone(e,n){let o=this.narrowLineWidth*10;o=o<n?o:n;for(let s=n-1;o>0&&s>=0&&!e.get(s);s--)o--;if(o!==0)throw new q}static skipWhiteSpace(e){const n=e.getSize(),o=e.getNextSet(0);if(o===n)throw new q;return o}decodeEnd(e){e.reverse();try{let n=ne.skipWhiteSpace(e),o;try{o=ne.findGuardPattern(e,n,ne.END_PATTERN_REVERSED[0])}catch(a){a instanceof q&&(o=ne.findGuardPattern(e,n,ne.END_PATTERN_REVERSED[1]))}this.validateQuietZone(e,o[0]);let s=o[0];return o[0]=e.getSize()-o[1],o[1]=e.getSize()-s,o}finally{e.reverse()}}static findGuardPattern(e,n,o){let s=o.length,a=new Int32Array(s),l=e.getSize(),u=!1,h=0,p=n;a.fill(0);for(let y=n;y<l;y++)if(e.get(y)!==u)a[h]++;else{if(h===s-1){if(gt.patternMatchVariance(a,o,ne.MAX_INDIVIDUAL_VARIANCE)<ne.MAX_AVG_VARIANCE)return[p,y];p+=a[0]+a[1],P.arraycopy(a,2,a,0,h-1),a[h-1]=0,a[h]=0,h--}else h++;a[h]=1,u=!u}throw new q}static decodeDigit(e){let n=ne.MAX_AVG_VARIANCE,o=-1,s=ne.PATTERNS.length;for(let a=0;a<s;a++){let l=ne.PATTERNS[a],u=gt.patternMatchVariance(e,l,ne.MAX_INDIVIDUAL_VARIANCE);u<n?(n=u,o=a):u===n&&(o=-1)}if(o>=0)return o%10;throw new q}}ne.PATTERNS=[Int32Array.from([1,1,2,2,1]),Int32Array.from([2,1,1,1,2]),Int32Array.from([1,2,1,1,2]),Int32Array.from([2,2,1,1,1]),Int32Array.from([1,1,2,1,2]),Int32Array.from([2,1,2,1,1]),Int32Array.from([1,2,2,1,1]),Int32Array.from([1,1,1,2,2]),Int32Array.from([2,1,1,2,1]),Int32Array.from([1,2,1,2,1]),Int32Array.from([1,1,3,3,1]),Int32Array.from([3,1,1,1,3]),Int32Array.from([1,3,1,1,3]),Int32Array.from([3,3,1,1,1]),Int32Array.from([1,1,3,1,3]),Int32Array.from([3,1,3,1,1]),Int32Array.from([1,3,3,1,1]),Int32Array.from([1,1,1,3,3]),Int32Array.from([3,1,1,3,1]),Int32Array.from([1,3,1,3,1])],ne.MAX_AVG_VARIANCE=.38,ne.MAX_INDIVIDUAL_VARIANCE=.5,ne.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],ne.START_PATTERN=Int32Array.from([1,1,1,1]),ne.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class Me extends gt{constructor(){super(...arguments),this.decodeRowStringBuffer=""}static findStartGuardPattern(e){let n=!1,o,s=0,a=Int32Array.from([0,0,0]);for(;!n;){a=Int32Array.from([0,0,0]),o=Me.findGuardPattern(e,s,!1,this.START_END_PATTERN,a);let l=o[0];s=o[1];let u=l-(s-l);u>=0&&(n=e.isRange(u,l,!1))}return o}static checkChecksum(e){return Me.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let o=parseInt(e.charAt(n-1),10);return Me.getStandardUPCEANChecksum(e.substring(0,n-1))===o}static getStandardUPCEANChecksum(e){let n=e.length,o=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new L;o+=a}o*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new L;o+=a}return(1e3-o)%10}static decodeEnd(e,n){return Me.findGuardPattern(e,n,!1,Me.START_END_PATTERN,new Int32Array(Me.START_END_PATTERN.length).fill(0))}static findGuardPatternWithoutCounters(e,n,o,s){return this.findGuardPattern(e,n,o,s,new Int32Array(s.length))}static findGuardPattern(e,n,o,s,a){let l=e.getSize();n=o?e.getNextUnset(n):e.getNextSet(n);let u=0,h=n,p=s.length,y=o;for(let b=n;b<l;b++)if(e.get(b)!==y)a[u]++;else{if(u===p-1){if(gt.patternMatchVariance(a,s,Me.MAX_INDIVIDUAL_VARIANCE)<Me.MAX_AVG_VARIANCE)return Int32Array.from([h,b]);h+=a[0]+a[1];let I=a.slice(2,a.length-1);for(let R=0;R<u-1;R++)a[R]=I[R];a[u-1]=0,a[u]=0,u--}else u++;a[u]=1,y=!y}throw new q}static decodeDigit(e,n,o,s){this.recordPattern(e,o,n);let a=this.MAX_AVG_VARIANCE,l=-1,u=s.length;for(let h=0;h<u;h++){let p=s[h],y=gt.patternMatchVariance(n,p,Me.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new q}}Me.MAX_AVG_VARIANCE=.48,Me.MAX_INDIVIDUAL_VARIANCE=.7,Me.START_END_PATTERN=Int32Array.from([1,1,1]),Me.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),Me.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),Me.L_PATTERNS=[Int32Array.from([3,2,1,1]),Int32Array.from([2,2,2,1]),Int32Array.from([2,1,2,2]),Int32Array.from([1,4,1,1]),Int32Array.from([1,1,3,2]),Int32Array.from([1,2,3,1]),Int32Array.from([1,1,1,4]),Int32Array.from([1,3,1,2]),Int32Array.from([1,2,1,3]),Int32Array.from([3,1,1,2])];class Ee{constructor(){this.CHECK_DIGIT_ENCODINGS=[24,20,18,17,12,6,3,10,9,5],this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,o){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,o,s),l=s.toString(),u=Ee.parseExtensionString(l),h=[new be((o[0]+o[1])/2,e),new be(a,e)],p=new qe(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return u!=null&&p.putAllMetadata(u),p}decodeMiddle(e,n,o){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],u=0;for(let p=0;p<5&&l<a;p++){let y=Me.decodeDigit(e,s,l,Me.L_AND_G_PATTERNS);o+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(u|=1<<4-p),p!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(o.length!==5)throw new q;let h=this.determineCheckDigit(u);if(Ee.extensionChecksum(o.toString())!==h)throw new q;return l}static extensionChecksum(e){let n=e.length,o=0;for(let s=n-2;s>=0;s-=2)o+=e.charAt(s).charCodeAt(0)-48;o*=3;for(let s=n-1;s>=0;s-=2)o+=e.charAt(s).charCodeAt(0)-48;return o*=3,o%10}determineCheckDigit(e){for(let n=0;n<10;n++)if(e===this.CHECK_DIGIT_ENCODINGS[n])return n;throw new q}static parseExtensionString(e){if(e.length!==5)return null;let n=Ee.parseExtension5String(e);return n==null?null:new Map([[_e.SUGGESTED_PRICE,n]])}static parseExtension5String(e){let n;switch(e.charAt(0)){case"0":n="£";break;case"5":n="$";break;case"9":switch(e){case"90000":return null;case"99991":return"0.00";case"99990":return"Used"}n="";break;default:n="";break}let o=parseInt(e.substring(1)),s=(o/100).toString(),a=o%100,l=a<10?"0"+a:a.toString();return n+s+"."+l}}class Oe{constructor(){this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,o){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,o,s),l=s.toString(),u=Oe.parseExtensionString(l),h=[new be((o[0]+o[1])/2,e),new be(a,e)],p=new qe(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return u!=null&&p.putAllMetadata(u),p}decodeMiddle(e,n,o){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],u=0;for(let h=0;h<2&&l<a;h++){let p=Me.decodeDigit(e,s,l,Me.L_AND_G_PATTERNS);o+=String.fromCharCode(48+p%10);for(let y of s)l+=y;p>=10&&(u|=1<<1-h),h!==1&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(o.length!==2)throw new q;if(parseInt(o.toString())%4!==u)throw new q;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[_e.ISSUE_NUMBER,parseInt(e)]])}}class rt{static decodeRow(e,n,o){let s=Me.findGuardPattern(n,o,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new Ee().decodeRow(e,n,s)}catch{return new Oe().decodeRow(e,n,s)}}}rt.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class Ye extends Me{constructor(){super(),this.decodeRowStringBuffer="",Ye.L_AND_G_PATTERNS=Ye.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=Ye.L_PATTERNS[e-10],o=new Int32Array(n.length);for(let s=0;s<n.length;s++)o[s]=n[n.length-s-1];Ye.L_AND_G_PATTERNS[e]=o}}decodeRow(e,n,o){let s=Ye.findStartGuardPattern(n),a=o==null?null:o.get(B.NEED_RESULT_POINT_CALLBACK);if(a!=null){const ce=new be((s[0]+s[1])/2,e);a.foundPossibleResultPoint(ce)}let l=this.decodeMiddle(n,s,this.decodeRowStringBuffer),u=l.rowOffset,h=l.resultString;if(a!=null){const ce=new be(u,e);a.foundPossibleResultPoint(ce)}let p=this.decodeEnd(n,u);if(a!=null){const ce=new be((p[0]+p[1])/2,e);a.foundPossibleResultPoint(ce)}let y=p[1],b=y+(y-p[0]);if(b>=n.getSize()||!n.isRange(y,b,!1))throw new q;let I=h.toString();if(I.length<8)throw new L;if(!Ye.checkChecksum(I))throw new T;let R=(s[1]+s[0])/2,U=(p[1]+p[0])/2,V=this.getBarcodeFormat(),H=[new be(R,e),new be(U,e)],Q=new qe(I,null,0,H,V,new Date().getTime()),he=0;try{let ce=rt.decodeRow(e,n,p[1]);Q.putMetadata(_e.UPC_EAN_EXTENSION,ce.getText()),Q.putAllMetadata(ce.getResultMetadata()),Q.addResultPoints(ce.getResultPoints()),he=ce.getText().length}catch{}let pe=o==null?null:o.get(B.ALLOWED_EAN_EXTENSIONS);if(pe!=null){let ce=!1;for(let Ke in pe)if(he.toString()===Ke){ce=!0;break}if(!ce)throw new q}return Q}decodeEnd(e,n){return Ye.findGuardPattern(e,n,!1,Ye.START_END_PATTERN,new Int32Array(Ye.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return Ye.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let o=parseInt(e.charAt(n-1),10);return Ye.getStandardUPCEANChecksum(e.substring(0,n-1))===o}static getStandardUPCEANChecksum(e){let n=e.length,o=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new L;o+=a}o*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new L;o+=a}return(1e3-o)%10}}class Fn extends Ye{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,o){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],u=0;for(let p=0;p<6&&l<a;p++){let y=Ye.decodeDigit(e,s,l,Ye.L_AND_G_PATTERNS);o+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(u|=1<<5-p)}o=Fn.determineFirstDigit(o,u),l=Ye.findGuardPattern(e,l,!0,Ye.MIDDLE_PATTERN,new Int32Array(Ye.MIDDLE_PATTERN.length).fill(0))[1];for(let p=0;p<6&&l<a;p++){let y=Ye.decodeDigit(e,s,l,Ye.L_PATTERNS);o+=String.fromCharCode(48+y);for(let b of s)l+=b}return{rowOffset:l,resultString:o}}getBarcodeFormat(){return ie.EAN_13}static determineFirstDigit(e,n){for(let o=0;o<10;o++)if(n===this.FIRST_DIGIT_ENCODINGS[o])return e=String.fromCharCode(48+o)+e,e;throw new q}}Fn.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class as extends Ye{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,o){const s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1];for(let h=0;h<4&&l<a;h++){let p=Ye.decodeDigit(e,s,l,Ye.L_PATTERNS);o+=String.fromCharCode(48+p);for(let y of s)l+=y}l=Ye.findGuardPattern(e,l,!0,Ye.MIDDLE_PATTERN,new Int32Array(Ye.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let p=Ye.decodeDigit(e,s,l,Ye.L_PATTERNS);o+=String.fromCharCode(48+p);for(let y of s)l+=y}return{rowOffset:l,resultString:o}}getBarcodeFormat(){return ie.EAN_8}}class ls extends Ye{constructor(){super(...arguments),this.ean13Reader=new Fn}getBarcodeFormat(){return ie.UPC_A}decode(e,n){return this.maybeReturnResult(this.ean13Reader.decode(e))}decodeRow(e,n,o){return this.maybeReturnResult(this.ean13Reader.decodeRow(e,n,o))}decodeMiddle(e,n,o){return this.ean13Reader.decodeMiddle(e,n,o)}maybeReturnResult(e){let n=e.getText();if(n.charAt(0)==="0"){let o=new qe(n.substring(1),null,null,e.getResultPoints(),ie.UPC_A);return e.getResultMetadata()!=null&&o.putAllMetadata(e.getResultMetadata()),o}else throw new q}reset(){this.ean13Reader.reset()}}class xn extends Ye{constructor(){super(),this.decodeMiddleCounters=new Int32Array(4)}decodeMiddle(e,n,o){const s=this.decodeMiddleCounters.map(p=>p);s[0]=0,s[1]=0,s[2]=0,s[3]=0;const a=e.getSize();let l=n[1],u=0;for(let p=0;p<6&&l<a;p++){const y=xn.decodeDigit(e,s,l,xn.L_AND_G_PATTERNS);o+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(u|=1<<5-p)}let h=xn.determineNumSysAndCheckDigit(o,u);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return xn.findGuardPatternWithoutCounters(e,n,!0,xn.MIDDLE_END_PATTERN)}checkChecksum(e){return Ye.checkChecksum(xn.convertUPCEtoUPCA(e))}static determineNumSysAndCheckDigit(e,n){for(let o=0;o<=1;o++)for(let s=0;s<10;s++)if(n===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[o][s]){let a=String.fromCharCode(48+o),l=String.fromCharCode(48+s);return a+e+l}throw q.getNotFoundInstance()}getBarcodeFormat(){return ie.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),o=new fe;o.append(e.charAt(0));let s=n[5];switch(s){case 0:case 1:case 2:o.appendChars(n,0,2),o.append(s),o.append("0000"),o.appendChars(n,2,3);break;case 3:o.appendChars(n,0,3),o.append("00000"),o.appendChars(n,3,2);break;case 4:o.appendChars(n,0,4),o.append("00000"),o.append(n[4]);break;default:o.appendChars(n,0,5),o.append("0000"),o.append(s);break}return e.length>=8&&o.append(e.charAt(7)),o.toString()}}xn.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),xn.NUMSYS_AND_CHECK_DIGIT_PATTERNS=[Int32Array.from([56,52,50,49,44,38,35,42,41,37]),Int32Array.from([7,11,13,14,19,25,28,21,22,26])];class $o extends gt{constructor(e){super();let n=e==null?null:e.get(B.POSSIBLE_FORMATS),o=[];c(n)?(o.push(new Fn),o.push(new ls),o.push(new as),o.push(new xn)):(n.indexOf(ie.EAN_13)>-1&&o.push(new Fn),n.indexOf(ie.UPC_A)>-1&&o.push(new ls),n.indexOf(ie.EAN_8)>-1&&o.push(new as),n.indexOf(ie.UPC_E)>-1&&o.push(new xn)),this.readers=o}decodeRow(e,n,o){for(let s of this.readers)try{const a=s.decodeRow(e,n,o),l=a.getBarcodeFormat()===ie.EAN_13&&a.getText().charAt(0)==="0",u=o==null?null:o.get(B.POSSIBLE_FORMATS),h=u==null||u.includes(ie.UPC_A);if(l&&h){const p=a.getRawBytes(),y=new qe(a.getText().substring(1),p,p?p.length:null,a.getResultPoints(),ie.UPC_A);return y.putAllMetadata(a.getResultMetadata()),y}return a}catch{}throw new q}reset(){for(let e of this.readers)e.reset()}}class Wt extends gt{constructor(){super(),this.decodeFinderCounters=new Int32Array(4),this.dataCharacterCounters=new Int32Array(8),this.oddRoundingErrors=new Array(4),this.evenRoundingErrors=new Array(4),this.oddCounts=new Array(this.dataCharacterCounters.length/2),this.evenCounts=new Array(this.dataCharacterCounters.length/2)}getDecodeFinderCounters(){return this.decodeFinderCounters}getDataCharacterCounters(){return this.dataCharacterCounters}getOddRoundingErrors(){return this.oddRoundingErrors}getEvenRoundingErrors(){return this.evenRoundingErrors}getOddCounts(){return this.oddCounts}getEvenCounts(){return this.evenCounts}parseFinderValue(e,n){for(let o=0;o<n.length;o++)if(gt.patternMatchVariance(e,n[o],Wt.MAX_INDIVIDUAL_VARIANCE)<Wt.MAX_AVG_VARIANCE)return o;throw new q}static count(e){return Xe.sum(new Int32Array(e))}static increment(e,n){let o=0,s=n[0];for(let a=1;a<e.length;a++)n[a]>s&&(s=n[a],o=a);e[o]++}static decrement(e,n){let o=0,s=n[0];for(let a=1;a<e.length;a++)n[a]<s&&(s=n[a],o=a);e[o]--}static isFinderPattern(e){let n=e[0]+e[1],o=n+e[2]+e[3],s=n/o;if(s>=Wt.MIN_FINDER_PATTERN_RATIO&&s<=Wt.MAX_FINDER_PATTERN_RATIO){let a=Number.MAX_SAFE_INTEGER,l=Number.MIN_SAFE_INTEGER;for(let u of e)u>l&&(l=u),u<a&&(a=u);return l<10*a}return!1}}Wt.MAX_AVG_VARIANCE=.2,Wt.MAX_INDIVIDUAL_VARIANCE=.45,Wt.MIN_FINDER_PATTERN_RATIO=9.5/12,Wt.MAX_FINDER_PATTERN_RATIO=12.5/14;class _r{constructor(e,n){this.value=e,this.checksumPortion=n}getValue(){return this.value}getChecksumPortion(){return this.checksumPortion}toString(){return this.value+"("+this.checksumPortion+")"}equals(e){if(!(e instanceof _r))return!1;const n=e;return this.value===n.value&&this.checksumPortion===n.checksumPortion}hashCode(){return this.value^this.checksumPortion}}class co{constructor(e,n,o,s,a){this.value=e,this.startEnd=n,this.value=e,this.startEnd=n,this.resultPoints=new Array,this.resultPoints.push(new be(o,a)),this.resultPoints.push(new be(s,a))}getValue(){return this.value}getStartEnd(){return this.startEnd}getResultPoints(){return this.resultPoints}equals(e){if(!(e instanceof co))return!1;const n=e;return this.value===n.value}hashCode(){return this.value}}class Sn{constructor(){}static getRSSvalue(e,n,o){let s=0;for(let h of e)s+=h;let a=0,l=0,u=e.length;for(let h=0;h<u-1;h++){let p;for(p=1,l|=1<<h;p<e[h];p++,l&=~(1<<h)){let y=Sn.combins(s-p-1,u-h-2);if(o&&l===0&&s-p-(u-h-1)>=u-h-1&&(y-=Sn.combins(s-p-(u-h),u-h-2)),u-h-1>1){let b=0;for(let I=s-p-(u-h-2);I>n;I--)b+=Sn.combins(s-p-I-1,u-h-3);y-=b*(u-1-h)}else s-p>n&&y--;a+=y}s-=p}return a}static combins(e,n){let o,s;e-n>n?(s=n,o=e-n):(s=e-n,o=n);let a=1,l=1;for(let u=e;u>o;u--)a*=u,l<=s&&(a/=l,l++);for(;l<=s;)a/=l,l++;return a}}class Xu{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let o=12*n,s=new re(o),a=0,u=e[0].getRightChar().getValue();for(let h=11;h>=0;--h)(u&1<<h)!=0&&s.set(a),a++;for(let h=1;h<e.length;++h){let p=e[h],y=p.getLeftChar().getValue();for(let b=11;b>=0;--b)(y&1<<b)!=0&&s.set(a),a++;if(p.getRightChar()!=null){let b=p.getRightChar().getValue();for(let I=11;I>=0;--I)(b&1<<I)!=0&&s.set(a),a++}}return s}}class ir{constructor(e,n){n?this.decodedInformation=null:(this.finished=e,this.decodedInformation=n)}getDecodedInformation(){return this.decodedInformation}isFinished(){return this.finished}}class jo{constructor(e){this.newPosition=e}getNewPosition(){return this.newPosition}}class Jt extends jo{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===Jt.FNC1}}Jt.FNC1="$";class sr extends jo{constructor(e,n,o){super(e),o?(this.remaining=!0,this.remainingValue=this.remainingValue):(this.remaining=!1,this.remainingValue=0),this.newString=n}getNewString(){return this.newString}isRemaining(){return this.remaining}getRemainingValue(){return this.remainingValue}}class hn extends jo{constructor(e,n,o){if(super(e),n<0||n>10||o<0||o>10)throw new L;this.firstDigit=n,this.secondDigit=o}getFirstDigit(){return this.firstDigit}getSecondDigit(){return this.secondDigit}getValue(){return this.firstDigit*10+this.secondDigit}isFirstDigitFNC1(){return this.firstDigit===hn.FNC1}isSecondDigitFNC1(){return this.secondDigit===hn.FNC1}isAnyFNC1(){return this.firstDigit===hn.FNC1||this.secondDigit===hn.FNC1}}hn.FNC1=10;class ve{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new q;let n=e.substring(0,2);for(let a of ve.TWO_DIGIT_DATA_LENGTH)if(a[0]===n)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(2,a[2],e):ve.processFixedAI(2,a[1],e);if(e.length<3)throw new q;let o=e.substring(0,3);for(let a of ve.THREE_DIGIT_DATA_LENGTH)if(a[0]===o)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(3,a[2],e):ve.processFixedAI(3,a[1],e);for(let a of ve.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH)if(a[0]===o)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(4,a[2],e):ve.processFixedAI(4,a[1],e);if(e.length<4)throw new q;let s=e.substring(0,4);for(let a of ve.FOUR_DIGIT_DATA_LENGTH)if(a[0]===s)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(4,a[2],e):ve.processFixedAI(4,a[1],e);throw new q}static processFixedAI(e,n,o){if(o.length<e)throw new q;let s=o.substring(0,e);if(o.length<e+n)throw new q;let a=o.substring(e,e+n),l=o.substring(e+n),u="("+s+")"+a,h=ve.parseFieldsInGeneralPurpose(l);return h==null?u:u+h}static processVariableAI(e,n,o){let s=o.substring(0,e),a;o.length<e+n?a=o.length:a=e+n;let l=o.substring(e,a),u=o.substring(a),h="("+s+")"+l,p=ve.parseFieldsInGeneralPurpose(u);return p==null?h:h+p}}ve.VARIABLE_LENGTH=[],ve.TWO_DIGIT_DATA_LENGTH=[["00",18],["01",14],["02",14],["10",ve.VARIABLE_LENGTH,20],["11",6],["12",6],["13",6],["15",6],["17",6],["20",2],["21",ve.VARIABLE_LENGTH,20],["22",ve.VARIABLE_LENGTH,29],["30",ve.VARIABLE_LENGTH,8],["37",ve.VARIABLE_LENGTH,8],["90",ve.VARIABLE_LENGTH,30],["91",ve.VARIABLE_LENGTH,30],["92",ve.VARIABLE_LENGTH,30],["93",ve.VARIABLE_LENGTH,30],["94",ve.VARIABLE_LENGTH,30],["95",ve.VARIABLE_LENGTH,30],["96",ve.VARIABLE_LENGTH,30],["97",ve.VARIABLE_LENGTH,3],["98",ve.VARIABLE_LENGTH,30],["99",ve.VARIABLE_LENGTH,30]],ve.THREE_DIGIT_DATA_LENGTH=[["240",ve.VARIABLE_LENGTH,30],["241",ve.VARIABLE_LENGTH,30],["242",ve.VARIABLE_LENGTH,6],["250",ve.VARIABLE_LENGTH,30],["251",ve.VARIABLE_LENGTH,30],["253",ve.VARIABLE_LENGTH,17],["254",ve.VARIABLE_LENGTH,20],["400",ve.VARIABLE_LENGTH,30],["401",ve.VARIABLE_LENGTH,30],["402",17],["403",ve.VARIABLE_LENGTH,30],["410",13],["411",13],["412",13],["413",13],["414",13],["420",ve.VARIABLE_LENGTH,20],["421",ve.VARIABLE_LENGTH,15],["422",3],["423",ve.VARIABLE_LENGTH,15],["424",3],["425",3],["426",3]],ve.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH=[["310",6],["311",6],["312",6],["313",6],["314",6],["315",6],["316",6],["320",6],["321",6],["322",6],["323",6],["324",6],["325",6],["326",6],["327",6],["328",6],["329",6],["330",6],["331",6],["332",6],["333",6],["334",6],["335",6],["336",6],["340",6],["341",6],["342",6],["343",6],["344",6],["345",6],["346",6],["347",6],["348",6],["349",6],["350",6],["351",6],["352",6],["353",6],["354",6],["355",6],["356",6],["357",6],["360",6],["361",6],["362",6],["363",6],["364",6],["365",6],["366",6],["367",6],["368",6],["369",6],["390",ve.VARIABLE_LENGTH,15],["391",ve.VARIABLE_LENGTH,18],["392",ve.VARIABLE_LENGTH,15],["393",ve.VARIABLE_LENGTH,18],["703",ve.VARIABLE_LENGTH,30]],ve.FOUR_DIGIT_DATA_LENGTH=[["7001",13],["7002",ve.VARIABLE_LENGTH,30],["7003",10],["8001",14],["8002",ve.VARIABLE_LENGTH,20],["8003",ve.VARIABLE_LENGTH,30],["8004",ve.VARIABLE_LENGTH,30],["8005",6],["8006",18],["8007",ve.VARIABLE_LENGTH,30],["8008",ve.VARIABLE_LENGTH,12],["8018",18],["8020",ve.VARIABLE_LENGTH,25],["8100",6],["8101",10],["8102",2],["8110",ve.VARIABLE_LENGTH,70],["8200",ve.VARIABLE_LENGTH,70]];class vr{constructor(e){this.buffer=new fe,this.information=e}decodeAllCodes(e,n){let o=n,s=null;do{let a=this.decodeGeneralPurposeField(o,s),l=ve.parseFieldsInGeneralPurpose(a.getNewString());if(l!=null&&e.append(l),a.isRemaining()?s=""+a.getRemainingValue():s=null,o===a.getNewPosition())break;o=a.getNewPosition()}while(!0);return e.toString()}isStillNumeric(e){if(e+7>this.information.getSize())return e+4<=this.information.getSize();for(let n=e;n<e+3;++n)if(this.information.get(n))return!0;return this.information.get(e+3)}decodeNumeric(e){if(e+7>this.information.getSize()){let a=this.extractNumericValueFromBitArray(e,4);return a===0?new hn(this.information.getSize(),hn.FNC1,hn.FNC1):new hn(this.information.getSize(),a-1,hn.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),o=(n-8)/11,s=(n-8)%11;return new hn(e+7,o,s)}extractNumericValueFromBitArray(e,n){return vr.extractNumericValueFromBitArray(this.information,e,n)}static extractNumericValueFromBitArray(e,n,o){let s=0;for(let a=0;a<o;++a)e.get(n+a)&&(s|=1<<o-a-1);return s}decodeGeneralPurposeField(e,n){this.buffer.setLengthToZero(),n!=null&&this.buffer.append(n),this.current.setPosition(e);let o=this.parseBlocks();return o!=null&&o.isRemaining()?new sr(this.current.getPosition(),this.buffer.toString(),o.getRemainingValue()):new sr(this.current.getPosition(),this.buffer.toString())}parseBlocks(){let e,n;do{let o=this.current.getPosition();if(this.current.isAlpha()?(n=this.parseAlphaBlock(),e=n.isFinished()):this.current.isIsoIec646()?(n=this.parseIsoIec646Block(),e=n.isFinished()):(n=this.parseNumericBlock(),e=n.isFinished()),!(o!==this.current.getPosition())&&!e)break}while(!e);return n.getDecodedInformation()}parseNumericBlock(){for(;this.isStillNumeric(this.current.getPosition());){let e=this.decodeNumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFirstDigitFNC1()){let n;return e.isSecondDigitFNC1()?n=new sr(this.current.getPosition(),this.buffer.toString()):n=new sr(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new ir(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new sr(this.current.getPosition(),this.buffer.toString());return new ir(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new ir(!1)}parseIsoIec646Block(){for(;this.isStillIsoIec646(this.current.getPosition());){let e=this.decodeIsoIec646(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new sr(this.current.getPosition(),this.buffer.toString());return new ir(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setAlpha()),new ir(!1)}parseAlphaBlock(){for(;this.isStillAlpha(this.current.getPosition());){let e=this.decodeAlphanumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new sr(this.current.getPosition(),this.buffer.toString());return new ir(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setIsoIec646()),new ir(!1)}isStillIsoIec646(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+7>this.information.getSize())return!1;let o=this.extractNumericValueFromBitArray(e,7);if(o>=64&&o<116)return!0;if(e+8>this.information.getSize())return!1;let s=this.extractNumericValueFromBitArray(e,8);return s>=232&&s<253}decodeIsoIec646(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Jt(e+5,Jt.FNC1);if(n>=5&&n<15)return new Jt(e+5,"0"+(n-5));let o=this.extractNumericValueFromBitArray(e,7);if(o>=64&&o<90)return new Jt(e+7,""+(o+1));if(o>=90&&o<116)return new Jt(e+7,""+(o+7));let s=this.extractNumericValueFromBitArray(e,8),a;switch(s){case 232:a="!";break;case 233:a='"';break;case 234:a="%";break;case 235:a="&";break;case 236:a="'";break;case 237:a="(";break;case 238:a=")";break;case 239:a="*";break;case 240:a="+";break;case 241:a=",";break;case 242:a="-";break;case 243:a=".";break;case 244:a="/";break;case 245:a=":";break;case 246:a=";";break;case 247:a="<";break;case 248:a="=";break;case 249:a=">";break;case 250:a="?";break;case 251:a="_";break;case 252:a=" ";break;default:throw new L}return new Jt(e+8,a)}isStillAlpha(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+6>this.information.getSize())return!1;let o=this.extractNumericValueFromBitArray(e,6);return o>=16&&o<63}decodeAlphanumeric(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Jt(e+5,Jt.FNC1);if(n>=5&&n<15)return new Jt(e+5,"0"+(n-5));let o=this.extractNumericValueFromBitArray(e,6);if(o>=32&&o<58)return new Jt(e+6,""+(o+33));let s;switch(o){case 58:s="*";break;case 59:s=",";break;case 60:s="-";break;case 61:s=".";break;case 62:s="/";break;default:throw new St("Decoding invalid alphanumeric value: "+o)}return new Jt(e+6,s)}isAlphaTo646ToAlphaLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<5&&n+e<this.information.getSize();++n)if(n===2){if(!this.information.get(e+2))return!1}else if(this.information.get(e+n))return!1;return!0}isAlphaOr646ToNumericLatch(e){if(e+3>this.information.getSize())return!1;for(let n=e;n<e+3;++n)if(this.information.get(n))return!1;return!0}isNumericToAlphaNumericLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<4&&n+e<this.information.getSize();++n)if(this.information.get(e+n))return!1;return!0}}class Ho{constructor(e){this.information=e,this.generalDecoder=new vr(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class Qt extends Ho{constructor(e){super(e)}encodeCompressedGtin(e,n){e.append("(01)");let o=e.length();e.append("9"),this.encodeCompressedGtinWithoutAI(e,n,o)}encodeCompressedGtinWithoutAI(e,n,o){for(let s=0;s<4;++s){let a=this.getGeneralDecoder().extractNumericValueFromBitArray(n+10*s,10);a/100===0&&e.append("0"),a/10===0&&e.append("0"),e.append(a)}Qt.appendCheckDigit(e,o)}static appendCheckDigit(e,n){let o=0;for(let s=0;s<13;s++){let a=e.charAt(s+n).charCodeAt(0)-48;o+=(s&1)===0?3*a:a}o=10-o%10,o===10&&(o=0),e.append(o)}}Qt.GTIN_SIZE=40;class Cr extends Qt{constructor(e){super(e)}parseInformation(){let e=new fe;e.append("(01)");let n=e.length(),o=this.getGeneralDecoder().extractNumericValueFromBitArray(Cr.HEADER_SIZE,4);return e.append(o),this.encodeCompressedGtinWithoutAI(e,Cr.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,Cr.HEADER_SIZE+44)}}Cr.HEADER_SIZE=4;class uo extends Ho{constructor(e){super(e)}parseInformation(){let e=new fe;return this.getGeneralDecoder().decodeAllCodes(e,uo.HEADER_SIZE)}}uo.HEADER_SIZE=5;class fo extends Qt{constructor(e){super(e)}encodeCompressedWeight(e,n,o){let s=this.getGeneralDecoder().extractNumericValueFromBitArray(n,o);this.addWeightCode(e,s);let a=this.checkWeight(s),l=1e5;for(let u=0;u<5;++u)a/l===0&&e.append("0"),l/=10;e.append(a)}}class Tn extends fo{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=Tn.HEADER_SIZE+fo.GTIN_SIZE+Tn.WEIGHT_SIZE)throw new q;let e=new fe;return this.encodeCompressedGtin(e,Tn.HEADER_SIZE),this.encodeCompressedWeight(e,Tn.HEADER_SIZE+fo.GTIN_SIZE,Tn.WEIGHT_SIZE),e.toString()}}Tn.HEADER_SIZE=5,Tn.WEIGHT_SIZE=15;class Yu extends Tn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Ku extends Tn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class Nn extends Qt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Nn.HEADER_SIZE+Qt.GTIN_SIZE)throw new q;let e=new fe;this.encodeCompressedGtin(e,Nn.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Nn.HEADER_SIZE+Qt.GTIN_SIZE,Nn.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let o=this.getGeneralDecoder().decodeGeneralPurposeField(Nn.HEADER_SIZE+Qt.GTIN_SIZE+Nn.LAST_DIGIT_SIZE,null);return e.append(o.getNewString()),e.toString()}}Nn.HEADER_SIZE=8,Nn.LAST_DIGIT_SIZE=2;class Xt extends Qt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Xt.HEADER_SIZE+Qt.GTIN_SIZE)throw new q;let e=new fe;this.encodeCompressedGtin(e,Xt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Xt.HEADER_SIZE+Qt.GTIN_SIZE,Xt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let o=this.getGeneralDecoder().extractNumericValueFromBitArray(Xt.HEADER_SIZE+Qt.GTIN_SIZE+Xt.LAST_DIGIT_SIZE,Xt.FIRST_THREE_DIGITS_SIZE);o/100==0&&e.append("0"),o/10==0&&e.append("0"),e.append(o);let s=this.getGeneralDecoder().decodeGeneralPurposeField(Xt.HEADER_SIZE+Qt.GTIN_SIZE+Xt.LAST_DIGIT_SIZE+Xt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}Xt.HEADER_SIZE=8,Xt.LAST_DIGIT_SIZE=2,Xt.FIRST_THREE_DIGITS_SIZE=10;class Ct extends fo{constructor(e,n,o){super(e),this.dateCode=o,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=Ct.HEADER_SIZE+Ct.GTIN_SIZE+Ct.WEIGHT_SIZE+Ct.DATE_SIZE)throw new q;let e=new fe;return this.encodeCompressedGtin(e,Ct.HEADER_SIZE),this.encodeCompressedWeight(e,Ct.HEADER_SIZE+Ct.GTIN_SIZE,Ct.WEIGHT_SIZE),this.encodeCompressedDate(e,Ct.HEADER_SIZE+Ct.GTIN_SIZE+Ct.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let o=this.getGeneralDecoder().extractNumericValueFromBitArray(n,Ct.DATE_SIZE);if(o==38400)return;e.append("("),e.append(this.dateCode),e.append(")");let s=o%32;o/=32;let a=o%12+1;o/=12;let l=o;l/10==0&&e.append("0"),e.append(l),a/10==0&&e.append("0"),e.append(a),s/10==0&&e.append("0"),e.append(s)}addWeightCode(e,n){e.append("("),e.append(this.firstAIdigits),e.append(n/1e5),e.append(")")}checkWeight(e){return e%1e5}}Ct.HEADER_SIZE=8,Ct.WEIGHT_SIZE=20,Ct.DATE_SIZE=16;function cs(C){try{if(C.get(1))return new Cr(C);if(!C.get(2))return new uo(C);switch(vr.extractNumericValueFromBitArray(C,1,4)){case 4:return new Yu(C);case 5:return new Ku(C)}switch(vr.extractNumericValueFromBitArray(C,1,5)){case 12:return new Nn(C);case 13:return new Xt(C)}switch(vr.extractNumericValueFromBitArray(C,1,7)){case 56:return new Ct(C,"310","11");case 57:return new Ct(C,"320","11");case 58:return new Ct(C,"310","13");case 59:return new Ct(C,"320","13");case 60:return new Ct(C,"310","15");case 61:return new Ct(C,"320","15");case 62:return new Ct(C,"310","17");case 63:return new Ct(C,"320","17")}}catch(e){throw console.log(e),new St("unknown decoder: "+C)}}class Hn{constructor(e,n,o,s){this.leftchar=e,this.rightchar=n,this.finderpattern=o,this.maybeLast=s}mayBeLast(){return this.maybeLast}getLeftChar(){return this.leftchar}getRightChar(){return this.rightchar}getFinderPattern(){return this.finderpattern}mustBeLast(){return this.rightchar==null}toString(){return"[ "+this.leftchar+", "+this.rightchar+" : "+(this.finderpattern==null?"null":this.finderpattern.getValue())+" ]"}static equals(e,n){return e instanceof Hn?Hn.equalsOrNull(e.leftchar,n.leftchar)&&Hn.equalsOrNull(e.rightchar,n.rightchar)&&Hn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:Hn.equals(e,n)}hashCode(){return this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue()}}class Wo{constructor(e,n,o){this.pairs=e,this.rowNumber=n,this.wasReversed=o}getPairs(){return this.pairs}getRowNumber(){return this.rowNumber}isReversed(){return this.wasReversed}isEquivalent(e){return this.checkEqualitity(this,e)}toString(){return"{ "+this.pairs+" }"}equals(e,n){return e instanceof Wo?this.checkEqualitity(e,n)&&e.wasReversed===n.wasReversed:!1}checkEqualitity(e,n){if(!e||!n)return;let o;return e.forEach((s,a)=>{n.forEach(l=>{s.getLeftChar().getValue()===l.getLeftChar().getValue()&&s.getRightChar().getValue()===l.getRightChar().getValue()&&s.getFinderPatter().getValue()===l.getFinderPatter().getValue()&&(o=!0)})}),o}}class se extends Wt{constructor(e){super(...arguments),this.pairs=new Array(se.MAX_PAIRS),this.rows=new Array,this.startEnd=[2],this.verbose=e===!0}decodeRow(e,n,o){this.pairs.length=0,this.startFromEven=!1;try{return se.constructResult(this.decodeRow2pairs(e,n))}catch(s){this.verbose&&console.log(s)}return this.pairs.length=0,this.startFromEven=!0,se.constructResult(this.decodeRow2pairs(e,n))}reset(){this.pairs.length=0,this.rows.length=0}decodeRow2pairs(e,n){let o=!1;for(;!o;)try{this.pairs.push(this.retrieveNextPair(n,this.pairs,e))}catch(a){if(a instanceof q){if(!this.pairs.length)throw new q;o=!0}}if(this.checkChecksum())return this.pairs;let s;if(this.rows.length?s=!0:s=!1,this.storeRow(e,!1),s){let a=this.checkRowsBoolean(!1);if(a!=null||(a=this.checkRowsBoolean(!0),a!=null))return a}throw new q}checkRowsBoolean(e){if(this.rows.length>25)return this.rows.length=0,null;this.pairs.length=0,e&&(this.rows=this.rows.reverse());let n=null;try{n=this.checkRows(new Array,0)}catch(o){this.verbose&&console.log(o)}return e&&(this.rows=this.rows.reverse()),n}checkRows(e,n){for(let o=n;o<this.rows.length;o++){let s=this.rows[o];this.pairs.length=0;for(let l of e)this.pairs.push(l.getPairs());if(this.pairs.push(s.getPairs()),!se.isValidSequence(this.pairs))continue;if(this.checkChecksum())return this.pairs;let a=new Array(e);a.push(s);try{return this.checkRows(a,o+1)}catch(l){this.verbose&&console.log(l)}}throw new q}static isValidSequence(e){for(let n of se.FINDER_PATTERN_SEQUENCES){if(e.length>n.length)continue;let o=!0;for(let s=0;s<e.length;s++)if(e[s].getFinderPattern().getValue()!=n[s]){o=!1;break}if(o)return!0}return!1}storeRow(e,n){let o=0,s=!1,a=!1;for(;o<this.rows.length;){let l=this.rows[o];if(l.getRowNumber()>e){a=l.isEquivalent(this.pairs);break}s=l.isEquivalent(this.pairs),o++}a||s||se.isPartialRow(this.pairs,this.rows)||(this.rows.push(o,new Wo(this.pairs,e,n)),this.removePartialRows(this.pairs,this.rows))}removePartialRows(e,n){for(let o of n)if(o.getPairs().length!==e.length){for(let s of o.getPairs())for(let a of e)if(Hn.equals(s,a))break}}static isPartialRow(e,n){for(let o of n){let s=!0;for(let a of e){let l=!1;for(let u of o.getPairs())if(a.equals(u)){l=!0;break}if(!l){s=!1;break}}if(s)return!0}return!1}getRows(){return this.rows}static constructResult(e){let n=Xu.buildBitArray(e),s=cs(n).parseInformation(),a=e[0].getFinderPattern().getResultPoints(),l=e[e.length-1].getFinderPattern().getResultPoints(),u=[a[0],a[1],l[0],l[1]];return new qe(s,null,null,u,ie.RSS_EXPANDED,null)}checkChecksum(){let e=this.pairs.get(0),n=e.getLeftChar(),o=e.getRightChar();if(o==null)return!1;let s=o.getChecksumPortion(),a=2;for(let u=1;u<this.pairs.size();++u){let h=this.pairs.get(u);s+=h.getLeftChar().getChecksumPortion(),a++;let p=h.getRightChar();p!=null&&(s+=p.getChecksumPortion(),a++)}return s%=211,211*(a-4)+s==n.getValue()}static getNextSecondBar(e,n){let o;return e.get(n)?(o=e.getNextUnset(n),o=e.getNextSet(o)):(o=e.getNextSet(n),o=e.getNextUnset(o)),o}retrieveNextPair(e,n,o){let s=n.length%2==0;this.startFromEven&&(s=!s);let a,l=!0,u=-1;do this.findNextPair(e,n,u),a=this.parseFoundFinderPattern(e,o,s),a==null?u=se.getNextSecondBar(e,this.startEnd[0]):l=!1;while(l);let h=this.decodeDataCharacter(e,a,s,!0);if(!this.isEmptyPair(n)&&n[n.length-1].mustBeLast())throw new q;let p;try{p=this.decodeDataCharacter(e,a,s,!1)}catch(y){p=null,this.verbose&&console.log(y)}return new Hn(h,p,a,!0)}isEmptyPair(e){return e.length===0}findNextPair(e,n,o){let s=this.getDecodeFinderCounters();s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l;o>=0?l=o:this.isEmptyPair(n)?l=0:l=n[n.length-1].getFinderPattern().getStartEnd()[1];let u=n.length%2!=0;this.startFromEven&&(u=!u);let h=!1;for(;l<a&&(h=!e.get(l),!!h);)l++;let p=0,y=l;for(let b=l;b<a;b++)if(e.get(b)!=h)s[p]++;else{if(p==3){if(u&&se.reverseCounters(s),se.isFinderPattern(s)){this.startEnd[0]=y,this.startEnd[1]=b;return}u&&se.reverseCounters(s),y+=s[0]+s[1],s[0]=s[2],s[1]=s[3],s[2]=0,s[3]=0,p--}else p++;s[p]=1,h=!h}throw new q}static reverseCounters(e){let n=e.length;for(let o=0;o<n/2;++o){let s=e[o];e[o]=e[n-o-1],e[n-o-1]=s}}parseFoundFinderPattern(e,n,o){let s,a,l;if(o){let p=this.startEnd[0]-1;for(;p>=0&&!e.get(p);)p--;p++,s=this.startEnd[0]-p,a=p,l=this.startEnd[1]}else a=this.startEnd[0],l=e.getNextUnset(this.startEnd[1]+1),s=l-this.startEnd[1];let u=this.getDecodeFinderCounters();P.arraycopy(u,0,u,1,u.length-1),u[0]=s;let h;try{h=this.parseFinderValue(u,se.FINDER_PATTERNS)}catch{return null}return new co(h,[a,l],a,l,n)}decodeDataCharacter(e,n,o,s){let a=this.getDataCharacterCounters();for(let ft=0;ft<a.length;ft++)a[ft]=0;if(s)se.recordPatternInReverse(e,n.getStartEnd()[0],a);else{se.recordPattern(e,n.getStartEnd()[1],a);for(let ft=0,Ht=a.length-1;ft<Ht;ft++,Ht--){let an=a[ft];a[ft]=a[Ht],a[Ht]=an}}let l=17,u=Xe.sum(new Int32Array(a))/l,h=(n.getStartEnd()[1]-n.getStartEnd()[0])/15;if(Math.abs(u-h)/h>.3)throw new q;let p=this.getOddCounts(),y=this.getEvenCounts(),b=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let ft=0;ft<a.length;ft++){let Ht=1*a[ft]/u,an=Ht+.5;if(an<1){if(Ht<.3)throw new q;an=1}else if(an>8){if(Ht>8.7)throw new q;an=8}let Sr=ft/2;(ft&1)==0?(p[Sr]=an,b[Sr]=Ht-an):(y[Sr]=an,I[Sr]=Ht-an)}this.adjustOddEvenCounts(l);let R=4*n.getValue()+(o?0:2)+(s?0:1)-1,U=0,V=0;for(let ft=p.length-1;ft>=0;ft--){if(se.isNotA1left(n,o,s)){let Ht=se.WEIGHTS[R][2*ft];V+=p[ft]*Ht}U+=p[ft]}let H=0;for(let ft=y.length-1;ft>=0;ft--)if(se.isNotA1left(n,o,s)){let Ht=se.WEIGHTS[R][2*ft+1];H+=y[ft]*Ht}let Q=V+H;if((U&1)!=0||U>13||U<4)throw new q;let he=(13-U)/2,pe=se.SYMBOL_WIDEST[he],ce=9-pe,Ke=Sn.getRSSvalue(p,pe,!0),He=Sn.getRSSvalue(y,ce,!1),tn=se.EVEN_TOTAL_SUBSET[he],yn=se.GSUM[he],nn=Ke*tn+He+yn;return new _r(nn,Q)}static isNotA1left(e,n,o){return!(e.getValue()==0&&n&&o)}adjustOddEvenCounts(e){let n=Xe.sum(new Int32Array(this.getOddCounts())),o=Xe.sum(new Int32Array(this.getEvenCounts())),s=!1,a=!1;n>13?a=!0:n<4&&(s=!0);let l=!1,u=!1;o>13?u=!0:o<4&&(l=!0);let h=n+o-e,p=(n&1)==1,y=(o&1)==0;if(h==1)if(p){if(y)throw new q;a=!0}else{if(!y)throw new q;u=!0}else if(h==-1)if(p){if(y)throw new q;s=!0}else{if(!y)throw new q;l=!0}else if(h==0){if(p){if(!y)throw new q;n<o?(s=!0,u=!0):(a=!0,l=!0)}else if(y)throw new q}else throw new q;if(s){if(a)throw new q;se.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&se.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(u)throw new q;se.increment(this.getEvenCounts(),this.getOddRoundingErrors())}u&&se.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}se.SYMBOL_WIDEST=[7,5,4,3,1],se.EVEN_TOTAL_SUBSET=[4,20,52,104,204],se.GSUM=[0,348,1388,2948,3988],se.FINDER_PATTERNS=[Int32Array.from([1,8,4,1]),Int32Array.from([3,6,4,1]),Int32Array.from([3,4,6,1]),Int32Array.from([3,2,8,1]),Int32Array.from([2,6,5,1]),Int32Array.from([2,2,9,1])],se.WEIGHTS=[[1,3,9,27,81,32,96,77],[20,60,180,118,143,7,21,63],[189,145,13,39,117,140,209,205],[193,157,49,147,19,57,171,91],[62,186,136,197,169,85,44,132],[185,133,188,142,4,12,36,108],[113,128,173,97,80,29,87,50],[150,28,84,41,123,158,52,156],[46,138,203,187,139,206,196,166],[76,17,51,153,37,111,122,155],[43,129,176,106,107,110,119,146],[16,48,144,10,30,90,59,177],[109,116,137,200,178,112,125,164],[70,210,208,202,184,130,179,115],[134,191,151,31,93,68,204,190],[148,22,66,198,172,94,71,2],[6,18,54,162,64,192,154,40],[120,149,25,75,14,42,126,167],[79,26,78,23,69,207,199,175],[103,98,83,38,114,131,182,124],[161,61,183,127,170,88,53,159],[55,165,73,8,24,72,5,15],[45,135,194,160,58,174,100,89]],se.FINDER_PAT_A=0,se.FINDER_PAT_B=1,se.FINDER_PAT_C=2,se.FINDER_PAT_D=3,se.FINDER_PAT_E=4,se.FINDER_PAT_F=5,se.FINDER_PATTERN_SEQUENCES=[[se.FINDER_PAT_A,se.FINDER_PAT_A],[se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B],[se.FINDER_PAT_A,se.FINDER_PAT_C,se.FINDER_PAT_B,se.FINDER_PAT_D],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_C],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_D,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_D],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_E],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F]],se.MAX_PAIRS=11;class Ju extends _r{constructor(e,n,o){super(e,n),this.count=0,this.finderPattern=o}getFinderPattern(){return this.finderPattern}getCount(){return this.count}incrementCount(){this.count++}}class Tt extends Wt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,o){const s=this.decodePair(n,!1,e,o);Tt.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,o);Tt.addOrTally(this.possibleRightPairs,a),n.reverse();for(let l of this.possibleLeftPairs)if(l.getCount()>1){for(let u of this.possibleRightPairs)if(u.getCount()>1&&Tt.checkChecksum(l,u))return Tt.constructResult(l,u)}throw new q}static addOrTally(e,n){if(n==null)return;let o=!1;for(let s of e)if(s.getValue()===n.getValue()){s.incrementCount(),o=!0;break}o||e.push(n)}reset(){this.possibleLeftPairs.length=0,this.possibleRightPairs.length=0}static constructResult(e,n){let o=4537077*e.getValue()+n.getValue(),s=new String(o).toString(),a=new fe;for(let p=13-s.length;p>0;p--)a.append("0");a.append(s);let l=0;for(let p=0;p<13;p++){let y=a.charAt(p).charCodeAt(0)-48;l+=(p&1)===0?3*y:y}l=10-l%10,l===10&&(l=0),a.append(l.toString());let u=e.getFinderPattern().getResultPoints(),h=n.getFinderPattern().getResultPoints();return new qe(a.toString(),null,0,[u[0],u[1],h[0],h[1]],ie.RSS_14,new Date().getTime())}static checkChecksum(e,n){let o=(e.getChecksumPortion()+16*n.getChecksumPortion())%79,s=9*e.getFinderPattern().getValue()+n.getFinderPattern().getValue();return s>72&&s--,s>8&&s--,o===s}decodePair(e,n,o,s){try{let a=this.findFinderPattern(e,n),l=this.parseFoundFinderPattern(e,o,n,a),u=s==null?null:s.get(B.NEED_RESULT_POINT_CALLBACK);if(u!=null){let y=(a[0]+a[1])/2;n&&(y=e.getSize()-1-y),u.foundPossibleResultPoint(new be(y,o))}let h=this.decodeDataCharacter(e,l,!0),p=this.decodeDataCharacter(e,l,!1);return new Ju(1597*h.getValue()+p.getValue(),h.getChecksumPortion()+4*p.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,o){let s=this.getDataCharacterCounters();for(let H=0;H<s.length;H++)s[H]=0;if(o)gt.recordPatternInReverse(e,n.getStartEnd()[0],s);else{gt.recordPattern(e,n.getStartEnd()[1]+1,s);for(let H=0,Q=s.length-1;H<Q;H++,Q--){let he=s[H];s[H]=s[Q],s[Q]=he}}let a=o?16:15,l=Xe.sum(new Int32Array(s))/a,u=this.getOddCounts(),h=this.getEvenCounts(),p=this.getOddRoundingErrors(),y=this.getEvenRoundingErrors();for(let H=0;H<s.length;H++){let Q=s[H]/l,he=Math.floor(Q+.5);he<1?he=1:he>8&&(he=8);let pe=Math.floor(H/2);(H&1)===0?(u[pe]=he,p[pe]=Q-he):(h[pe]=he,y[pe]=Q-he)}this.adjustOddEvenCounts(o,a);let b=0,I=0;for(let H=u.length-1;H>=0;H--)I*=9,I+=u[H],b+=u[H];let R=0,U=0;for(let H=h.length-1;H>=0;H--)R*=9,R+=h[H],U+=h[H];let V=I+3*R;if(o){if((b&1)!==0||b>12||b<4)throw new q;let H=(12-b)/2,Q=Tt.OUTSIDE_ODD_WIDEST[H],he=9-Q,pe=Sn.getRSSvalue(u,Q,!1),ce=Sn.getRSSvalue(h,he,!0),Ke=Tt.OUTSIDE_EVEN_TOTAL_SUBSET[H],He=Tt.OUTSIDE_GSUM[H];return new _r(pe*Ke+ce+He,V)}else{if((U&1)!==0||U>10||U<4)throw new q;let H=(10-U)/2,Q=Tt.INSIDE_ODD_WIDEST[H],he=9-Q,pe=Sn.getRSSvalue(u,Q,!0),ce=Sn.getRSSvalue(h,he,!1),Ke=Tt.INSIDE_ODD_TOTAL_SUBSET[H],He=Tt.INSIDE_GSUM[H];return new _r(ce*Ke+pe+He,V)}}findFinderPattern(e,n){let o=this.getDecodeFinderCounters();o[0]=0,o[1]=0,o[2]=0,o[3]=0;let s=e.getSize(),a=!1,l=0;for(;l<s&&(a=!e.get(l),n!==a);)l++;let u=0,h=l;for(let p=l;p<s;p++)if(e.get(p)!==a)o[u]++;else{if(u===3){if(Wt.isFinderPattern(o))return[h,p];h+=o[0]+o[1],o[0]=o[2],o[1]=o[3],o[2]=0,o[3]=0,u--}else u++;o[u]=1,a=!a}throw new q}parseFoundFinderPattern(e,n,o,s){let a=e.get(s[0]),l=s[0]-1;for(;l>=0&&a!==e.get(l);)l--;l++;const u=s[0]-l,h=this.getDecodeFinderCounters(),p=new Int32Array(h.length);P.arraycopy(h,0,p,1,h.length-1),p[0]=u;const y=this.parseFinderValue(p,Tt.FINDER_PATTERNS);let b=l,I=s[1];return o&&(b=e.getSize()-1-b,I=e.getSize()-1-I),new co(y,[l,s[1]],b,I,n)}adjustOddEvenCounts(e,n){let o=Xe.sum(new Int32Array(this.getOddCounts())),s=Xe.sum(new Int32Array(this.getEvenCounts())),a=!1,l=!1,u=!1,h=!1;e?(o>12?l=!0:o<4&&(a=!0),s>12?h=!0:s<4&&(u=!0)):(o>11?l=!0:o<5&&(a=!0),s>10?h=!0:s<4&&(u=!0));let p=o+s-n,y=(o&1)===(e?1:0),b=(s&1)===1;if(p===1)if(y){if(b)throw new q;l=!0}else{if(!b)throw new q;h=!0}else if(p===-1)if(y){if(b)throw new q;a=!0}else{if(!b)throw new q;u=!0}else if(p===0){if(y){if(!b)throw new q;o<s?(a=!0,h=!0):(l=!0,u=!0)}else if(b)throw new q}else throw new q;if(a){if(l)throw new q;Wt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Wt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),u){if(h)throw new q;Wt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&Wt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}Tt.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],Tt.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],Tt.OUTSIDE_GSUM=[0,161,961,2015,2715],Tt.INSIDE_GSUM=[0,336,1036,1516],Tt.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],Tt.INSIDE_ODD_WIDEST=[2,4,6,8],Tt.FINDER_PATTERNS=[Int32Array.from([3,8,2,1]),Int32Array.from([3,5,5,1]),Int32Array.from([3,3,7,1]),Int32Array.from([3,1,9,1]),Int32Array.from([2,7,4,1]),Int32Array.from([2,5,6,1]),Int32Array.from([2,3,8,1]),Int32Array.from([1,5,7,1]),Int32Array.from([1,3,9,1])];class br extends gt{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const o=e?e.get(B.POSSIBLE_FORMATS):null,s=e&&e.get(B.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;o?((o.includes(ie.EAN_13)||o.includes(ie.UPC_A)||o.includes(ie.EAN_8)||o.includes(ie.UPC_E))&&this.readers.push(new $o(e)),o.includes(ie.CODE_39)&&this.readers.push(new O(s)),o.includes(ie.CODE_128)&&this.readers.push(new ge),o.includes(ie.ITF)&&this.readers.push(new ne),o.includes(ie.RSS_14)&&this.readers.push(new Tt),o.includes(ie.RSS_EXPANDED)&&this.readers.push(new se(this.verbose))):(this.readers.push(new $o(e)),this.readers.push(new O),this.readers.push(new $o(e)),this.readers.push(new ge),this.readers.push(new ne),this.readers.push(new Tt),this.readers.push(new se(this.verbose)))}decodeRow(e,n,o){for(let s=0;s<this.readers.length;s++)try{return this.readers[s].decodeRow(e,n,o)}catch{}throw new q}reset(){this.readers.forEach(e=>e.reset())}}class Qu extends Ze{constructor(e=500,n){super(new br(n),e,n)}}class at{constructor(e,n,o){this.ecCodewords=e,this.ecBlocks=[n],o&&this.ecBlocks.push(o)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class ot{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Qe{constructor(e,n,o,s,a,l){this.versionNumber=e,this.symbolSizeRows=n,this.symbolSizeColumns=o,this.dataRegionSizeRows=s,this.dataRegionSizeColumns=a,this.ecBlocks=l;let u=0;const h=l.getECCodewords(),p=l.getECBlocks();for(let y of p)u+=y.getCount()*(y.getDataCodewords()+h);this.totalCodewords=u}getVersionNumber(){return this.versionNumber}getSymbolSizeRows(){return this.symbolSizeRows}getSymbolSizeColumns(){return this.symbolSizeColumns}getDataRegionSizeRows(){return this.dataRegionSizeRows}getDataRegionSizeColumns(){return this.dataRegionSizeColumns}getTotalCodewords(){return this.totalCodewords}getECBlocks(){return this.ecBlocks}static getVersionForDimensions(e,n){if((e&1)!==0||(n&1)!==0)throw new L;for(let o of Qe.VERSIONS)if(o.symbolSizeRows===e&&o.symbolSizeColumns===n)return o;throw new L}toString(){return""+this.versionNumber}static buildVersions(){return[new Qe(1,10,10,8,8,new at(5,new ot(1,3))),new Qe(2,12,12,10,10,new at(7,new ot(1,5))),new Qe(3,14,14,12,12,new at(10,new ot(1,8))),new Qe(4,16,16,14,14,new at(12,new ot(1,12))),new Qe(5,18,18,16,16,new at(14,new ot(1,18))),new Qe(6,20,20,18,18,new at(18,new ot(1,22))),new Qe(7,22,22,20,20,new at(20,new ot(1,30))),new Qe(8,24,24,22,22,new at(24,new ot(1,36))),new Qe(9,26,26,24,24,new at(28,new ot(1,44))),new Qe(10,32,32,14,14,new at(36,new ot(1,62))),new Qe(11,36,36,16,16,new at(42,new ot(1,86))),new Qe(12,40,40,18,18,new at(48,new ot(1,114))),new Qe(13,44,44,20,20,new at(56,new ot(1,144))),new Qe(14,48,48,22,22,new at(68,new ot(1,174))),new Qe(15,52,52,24,24,new at(42,new ot(2,102))),new Qe(16,64,64,14,14,new at(56,new ot(2,140))),new Qe(17,72,72,16,16,new at(36,new ot(4,92))),new Qe(18,80,80,18,18,new at(48,new ot(4,114))),new Qe(19,88,88,20,20,new at(56,new ot(4,144))),new Qe(20,96,96,22,22,new at(68,new ot(4,174))),new Qe(21,104,104,24,24,new at(56,new ot(6,136))),new Qe(22,120,120,18,18,new at(68,new ot(6,175))),new Qe(23,132,132,20,20,new at(62,new ot(8,163))),new Qe(24,144,144,22,22,new at(62,new ot(8,156),new ot(2,155))),new Qe(25,8,18,6,16,new at(7,new ot(1,5))),new Qe(26,8,32,6,14,new at(11,new ot(1,10))),new Qe(27,12,26,10,24,new at(14,new ot(1,16))),new Qe(28,12,36,10,16,new at(18,new ot(1,22))),new Qe(29,16,36,14,16,new at(24,new ot(1,32))),new Qe(30,16,48,14,22,new at(28,new ot(1,49)))]}}Qe.VERSIONS=Qe.buildVersions();class Go{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new L;this.version=Go.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new te(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),o=e.getWidth();return Qe.getVersionForDimensions(n,o)}readCodewords(){const e=new Int8Array(this.version.getTotalCodewords());let n=0,o=4,s=0;const a=this.mappingBitMatrix.getHeight(),l=this.mappingBitMatrix.getWidth();let u=!1,h=!1,p=!1,y=!1;do if(o===a&&s===0&&!u)e[n++]=this.readCorner1(a,l)&255,o-=2,s+=2,u=!0;else if(o===a-2&&s===0&&(l&3)!==0&&!h)e[n++]=this.readCorner2(a,l)&255,o-=2,s+=2,h=!0;else if(o===a+4&&s===2&&(l&7)===0&&!p)e[n++]=this.readCorner3(a,l)&255,o-=2,s+=2,p=!0;else if(o===a-2&&s===0&&(l&7)===4&&!y)e[n++]=this.readCorner4(a,l)&255,o-=2,s+=2,y=!0;else{do o<a&&s>=0&&!this.readMappingMatrix.get(s,o)&&(e[n++]=this.readUtah(o,s,a,l)&255),o-=2,s+=2;while(o>=0&&s<l);o+=1,s+=3;do o>=0&&s<l&&!this.readMappingMatrix.get(s,o)&&(e[n++]=this.readUtah(o,s,a,l)&255),o+=2,s-=2;while(o<a&&s>=0);o+=3,s+=1}while(o<a||s<l);if(n!==this.version.getTotalCodewords())throw new L;return e}readModule(e,n,o,s){return e<0&&(e+=o,n+=4-(o+4&7)),n<0&&(n+=s,e+=4-(s+4&7)),this.readMappingMatrix.set(n,e),this.mappingBitMatrix.get(n,e)}readUtah(e,n,o,s){let a=0;return this.readModule(e-2,n-2,o,s)&&(a|=1),a<<=1,this.readModule(e-2,n-1,o,s)&&(a|=1),a<<=1,this.readModule(e-1,n-2,o,s)&&(a|=1),a<<=1,this.readModule(e-1,n-1,o,s)&&(a|=1),a<<=1,this.readModule(e-1,n,o,s)&&(a|=1),a<<=1,this.readModule(e,n-2,o,s)&&(a|=1),a<<=1,this.readModule(e,n-1,o,s)&&(a|=1),a<<=1,this.readModule(e,n,o,s)&&(a|=1),a}readCorner1(e,n){let o=0;return this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,1,e,n)&&(o|=1),o<<=1,this.readModule(e-1,2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o<<=1,this.readModule(2,n-1,e,n)&&(o|=1),o<<=1,this.readModule(3,n-1,e,n)&&(o|=1),o}readCorner2(e,n){let o=0;return this.readModule(e-3,0,e,n)&&(o|=1),o<<=1,this.readModule(e-2,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(0,n-4,e,n)&&(o|=1),o<<=1,this.readModule(0,n-3,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o}readCorner3(e,n){let o=0;return this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,n-1,e,n)&&(o|=1),o<<=1,this.readModule(0,n-3,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-3,e,n)&&(o|=1),o<<=1,this.readModule(1,n-2,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o}readCorner4(e,n){let o=0;return this.readModule(e-3,0,e,n)&&(o|=1),o<<=1,this.readModule(e-2,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o<<=1,this.readModule(2,n-1,e,n)&&(o|=1),o<<=1,this.readModule(3,n-1,e,n)&&(o|=1),o}extractDataRegion(e){const n=this.version.getSymbolSizeRows(),o=this.version.getSymbolSizeColumns();if(e.getHeight()!==n)throw new A("Dimension of bitMatrix must match the version size");const s=this.version.getDataRegionSizeRows(),a=this.version.getDataRegionSizeColumns(),l=n/s|0,u=o/a|0,h=l*s,p=u*a,y=new te(p,h);for(let b=0;b<l;++b){const I=b*s;for(let R=0;R<u;++R){const U=R*a;for(let V=0;V<s;++V){const H=b*(s+2)+1+V,Q=I+V;for(let he=0;he<a;++he){const pe=R*(a+2)+1+he;if(e.get(pe,H)){const ce=U+he;y.set(ce,Q)}}}}}return y}}class qo{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n){const o=n.getECBlocks();let s=0;const a=o.getECBlocks();for(let V of a)s+=V.getCount();const l=new Array(s);let u=0;for(let V of a)for(let H=0;H<V.getCount();H++){const Q=V.getDataCodewords(),he=o.getECCodewords()+Q;l[u++]=new qo(Q,new Uint8Array(he))}const p=l[0].codewords.length-o.getECCodewords(),y=p-1;let b=0;for(let V=0;V<y;V++)for(let H=0;H<u;H++)l[H].codewords[V]=e[b++];const I=n.getVersionNumber()===24,R=I?8:u;for(let V=0;V<R;V++)l[V].codewords[p-1]=e[b++];const U=l[0].codewords.length;for(let V=p;V<U;V++)for(let H=0;H<u;H++){const Q=I?(H+8)%u:H,he=I&&Q>7?V-1:V;l[Q].codewords[he]=e[b++]}if(b!==e.length)throw new A;return l}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}class Xo{constructor(e){this.bytes=e,this.byteOffset=0,this.bitOffset=0}getBitOffset(){return this.bitOffset}getByteOffset(){return this.byteOffset}readBits(e){if(e<1||e>32||e>this.available())throw new A(""+e);let n=0,o=this.bitOffset,s=this.byteOffset;const a=this.bytes;if(o>0){const l=8-o,u=e<l?e:l,h=l-u,p=255>>8-u<<h;n=(a[s]&p)>>h,e-=u,o+=u,o===8&&(o=0,s++)}if(e>0){for(;e>=8;)n=n<<8|a[s]&255,s++,e-=8;if(e>0){const l=8-e,u=255>>l<<l;n=n<<e|(a[s]&u)>>l,o+=e}}return this.bitOffset=o,this.byteOffset=s,n}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var Pt;(function(C){C[C.PAD_ENCODE=0]="PAD_ENCODE",C[C.ASCII_ENCODE=1]="ASCII_ENCODE",C[C.C40_ENCODE=2]="C40_ENCODE",C[C.TEXT_ENCODE=3]="TEXT_ENCODE",C[C.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",C[C.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",C[C.BASE256_ENCODE=6]="BASE256_ENCODE"})(Pt||(Pt={}));class Wn{static decode(e){const n=new Xo(e),o=new fe,s=new fe,a=new Array;let l=Pt.ASCII_ENCODE;do if(l===Pt.ASCII_ENCODE)l=this.decodeAsciiSegment(n,o,s);else{switch(l){case Pt.C40_ENCODE:this.decodeC40Segment(n,o);break;case Pt.TEXT_ENCODE:this.decodeTextSegment(n,o);break;case Pt.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,o);break;case Pt.EDIFACT_ENCODE:this.decodeEdifactSegment(n,o);break;case Pt.BASE256_ENCODE:this.decodeBase256Segment(n,o,a);break;default:throw new L}l=Pt.ASCII_ENCODE}while(l!==Pt.PAD_ENCODE&&n.available()>0);return s.length()>0&&o.append(s.toString()),new Pe(e,o.toString(),a.length===0?null:a,null)}static decodeAsciiSegment(e,n,o){let s=!1;do{let a=e.readBits(8);if(a===0)throw new L;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Pt.ASCII_ENCODE;if(a===129)return Pt.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Pt.C40_ENCODE;case 231:return Pt.BASE256_ENCODE;case 232:n.append("");break;case 233:case 234:break;case 235:s=!0;break;case 236:n.append("[)>05"),o.insert(0,"");break;case 237:n.append("[)>06"),o.insert(0,"");break;case 238:return Pt.ANSIX12_ENCODE;case 239:return Pt.TEXT_ENCODE;case 240:return Pt.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new L;break}}while(e.available()>0);return Pt.ASCII_ENCODE}static decodeC40Segment(e,n){let o=!1;const s=[];let a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let u=0;u<3;u++){const h=s[u];switch(a){case 0:if(h<3)a=h+1;else if(h<this.C40_BASIC_SET_CHARS.length){const p=this.C40_BASIC_SET_CHARS[h];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else throw new L;break;case 1:o?(n.append(String.fromCharCode(h+128)),o=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.C40_SHIFT2_SET_CHARS.length){const p=this.C40_SHIFT2_SET_CHARS[h];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:o=!0;break;default:throw new L}a=0;break;case 3:o?(n.append(String.fromCharCode(h+224)),o=!1):n.append(String.fromCharCode(h+96)),a=0;break;default:throw new L}}}while(e.available()>0)}static decodeTextSegment(e,n){let o=!1,s=[],a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let u=0;u<3;u++){const h=s[u];switch(a){case 0:if(h<3)a=h+1;else if(h<this.TEXT_BASIC_SET_CHARS.length){const p=this.TEXT_BASIC_SET_CHARS[h];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else throw new L;break;case 1:o?(n.append(String.fromCharCode(h+128)),o=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.TEXT_SHIFT2_SET_CHARS.length){const p=this.TEXT_SHIFT2_SET_CHARS[h];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:o=!0;break;default:throw new L}a=0;break;case 3:if(h<this.TEXT_SHIFT3_SET_CHARS.length){const p=this.TEXT_SHIFT3_SET_CHARS[h];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p),a=0}else throw new L;break;default:throw new L}}}while(e.available()>0)}static decodeAnsiX12Segment(e,n){const o=[];do{if(e.available()===8)return;const s=e.readBits(8);if(s===254)return;this.parseTwoBytes(s,e.readBits(8),o);for(let a=0;a<3;a++){const l=o[a];switch(l){case 0:n.append("\r");break;case 1:n.append("*");break;case 2:n.append(">");break;case 3:n.append(" ");break;default:if(l<14)n.append(String.fromCharCode(l+44));else if(l<40)n.append(String.fromCharCode(l+51));else throw new L;break}}}while(e.available()>0)}static parseTwoBytes(e,n,o){let s=(e<<8)+n-1,a=Math.floor(s/1600);o[0]=a,s-=a*1600,a=Math.floor(s/40),o[1]=a,o[2]=s-a*40}static decodeEdifactSegment(e,n){do{if(e.available()<=16)return;for(let o=0;o<4;o++){let s=e.readBits(6);if(s===31){const a=8-e.getBitOffset();a!==8&&e.readBits(a);return}(s&32)===0&&(s|=64),n.append(String.fromCharCode(s))}}while(e.available()>0)}static decodeBase256Segment(e,n,o){let s=1+e.getByteOffset();const a=this.unrandomize255State(e.readBits(8),s++);let l;if(a===0?l=e.available()/8|0:a<250?l=a:l=250*(a-249)+this.unrandomize255State(e.readBits(8),s++),l<0)throw new L;const u=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new L;u[h]=this.unrandomize255State(e.readBits(8),s++)}o.push(u);try{n.append(G.decode(u,me.ISO88591))}catch(h){throw new St("Platform does not support required encoding: "+h.message)}}static unrandomize255State(e,n){const o=149*n%255+1,s=e-o;return s>=0?s:s+256}}Wn.C40_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],Wn.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],Wn.TEXT_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],Wn.TEXT_SHIFT2_SET_CHARS=Wn.C40_SHIFT2_SET_CHARS,Wn.TEXT_SHIFT3_SET_CHARS=["`","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","{","|","}","~",""];class ed{constructor(){this.rsDecoder=new vt(Se.DATA_MATRIX_FIELD_256)}decode(e){const n=new Go(e),o=n.getVersion(),s=n.readCodewords(),a=qo.getDataBlocks(s,o);let l=0;for(let p of a)l+=p.getNumDataCodewords();const u=new Uint8Array(l),h=a.length;for(let p=0;p<h;p++){const y=a[p],b=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(b,I);for(let R=0;R<I;R++)u[R*h+p]=b[R]}return Wn.decode(u)}correctErrors(e,n){const o=new Int32Array(e);try{this.rsDecoder.decode(o,e.length-n)}catch{throw new T}for(let s=0;s<n;s++)e[s]=o[s]}}class Rt{constructor(e){this.image=e,this.rectangleDetector=new qt(this.image)}detect(){const e=this.rectangleDetector.detect();let n=this.detectSolid1(e);if(n=this.detectSolid2(n),n[3]=this.correctTopRight(n),!n[3])throw new q;n=this.shiftToModuleCenter(n);const o=n[0],s=n[1],a=n[2],l=n[3];let u=this.transitionsBetween(o,l)+1,h=this.transitionsBetween(a,l)+1;(u&1)===1&&(u+=1),(h&1)===1&&(h+=1),4*u<7*h&&4*h<7*u&&(u=h=Math.max(u,h));let p=Rt.sampleGrid(this.image,o,s,a,l,u,h);return new Bn(p,[o,s,a,l])}static shiftPoint(e,n,o){let s=(n.getX()-e.getX())/(o+1),a=(n.getY()-e.getY())/(o+1);return new be(e.getX()+s,e.getY()+a)}static moveAway(e,n,o){let s=e.getX(),a=e.getY();return s<n?s-=1:s+=1,a<o?a-=1:a+=1,new be(s,a)}detectSolid1(e){let n=e[0],o=e[1],s=e[3],a=e[2],l=this.transitionsBetween(n,o),u=this.transitionsBetween(o,s),h=this.transitionsBetween(s,a),p=this.transitionsBetween(a,n),y=l,b=[a,n,o,s];return y>u&&(y=u,b[0]=n,b[1]=o,b[2]=s,b[3]=a),y>h&&(y=h,b[0]=o,b[1]=s,b[2]=a,b[3]=n),y>p&&(b[0]=s,b[1]=a,b[2]=n,b[3]=o),b}detectSolid2(e){let n=e[0],o=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),u=Rt.shiftPoint(o,s,(l+1)*4),h=Rt.shiftPoint(s,o,(l+1)*4),p=this.transitionsBetween(u,n),y=this.transitionsBetween(h,a);return p<y?(e[0]=n,e[1]=o,e[2]=s,e[3]=a):(e[0]=o,e[1]=s,e[2]=a,e[3]=n),e}correctTopRight(e){let n=e[0],o=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),u=this.transitionsBetween(o,a),h=Rt.shiftPoint(n,o,(u+1)*4),p=Rt.shiftPoint(s,o,(l+1)*4);l=this.transitionsBetween(h,a),u=this.transitionsBetween(p,a);let y=new be(a.getX()+(s.getX()-o.getX())/(l+1),a.getY()+(s.getY()-o.getY())/(l+1)),b=new be(a.getX()+(n.getX()-o.getX())/(u+1),a.getY()+(n.getY()-o.getY())/(u+1));if(!this.isValid(y))return this.isValid(b)?b:null;if(!this.isValid(b))return y;let I=this.transitionsBetween(h,y)+this.transitionsBetween(p,y),R=this.transitionsBetween(h,b)+this.transitionsBetween(p,b);return I>R?y:b}shiftToModuleCenter(e){let n=e[0],o=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a)+1,u=this.transitionsBetween(s,a)+1,h=Rt.shiftPoint(n,o,u*4),p=Rt.shiftPoint(s,o,l*4);l=this.transitionsBetween(h,a)+1,u=this.transitionsBetween(p,a)+1,(l&1)===1&&(l+=1),(u&1)===1&&(u+=1);let y=(n.getX()+o.getX()+s.getX()+a.getX())/4,b=(n.getY()+o.getY()+s.getY()+a.getY())/4;n=Rt.moveAway(n,y,b),o=Rt.moveAway(o,y,b),s=Rt.moveAway(s,y,b),a=Rt.moveAway(a,y,b);let I,R;return h=Rt.shiftPoint(n,o,u*4),h=Rt.shiftPoint(h,a,l*4),I=Rt.shiftPoint(o,n,u*4),I=Rt.shiftPoint(I,s,l*4),p=Rt.shiftPoint(s,a,u*4),p=Rt.shiftPoint(p,o,l*4),R=Rt.shiftPoint(a,s,u*4),R=Rt.shiftPoint(R,n,l*4),[h,I,p,R]}isValid(e){return e.getX()>=0&&e.getX()<this.image.getWidth()&&e.getY()>0&&e.getY()<this.image.getHeight()}static sampleGrid(e,n,o,s,a,l,u){return sn.getInstance().sampleGrid(e,l,u,.5,.5,l-.5,.5,l-.5,u-.5,.5,u-.5,n.getX(),n.getY(),a.getX(),a.getY(),s.getX(),s.getY(),o.getX(),o.getY())}transitionsBetween(e,n){let o=Math.trunc(e.getX()),s=Math.trunc(e.getY()),a=Math.trunc(n.getX()),l=Math.trunc(n.getY()),u=Math.abs(l-s)>Math.abs(a-o);if(u){let V=o;o=s,s=V,V=a,a=l,l=V}let h=Math.abs(a-o),p=Math.abs(l-s),y=-h/2,b=s<l?1:-1,I=o<a?1:-1,R=0,U=this.image.get(u?s:o,u?o:s);for(let V=o,H=s;V!==a;V+=I){let Q=this.image.get(u?H:V,u?V:H);if(Q!==U&&(R++,U=Q),y+=p,y>0){if(H===l)break;H+=b,y-=h}}return R}}class Gn{constructor(){this.decoder=new ed}decode(e,n=null){let o,s;if(n!=null&&n.has(B.PURE_BARCODE)){const p=Gn.extractPureBits(e.getBlackMatrix());o=this.decoder.decode(p),s=Gn.NO_POINTS}else{const p=new Rt(e.getBlackMatrix()).detect();o=this.decoder.decode(p.getBits()),s=p.getPoints()}const a=o.getRawBytes(),l=new qe(o.getText(),a,8*a.length,s,ie.DATA_MATRIX,P.currentTimeMillis()),u=o.getByteSegments();u!=null&&l.putMetadata(_e.BYTE_SEGMENTS,u);const h=o.getECLevel();return h!=null&&l.putMetadata(_e.ERROR_CORRECTION_LEVEL,h),l}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),o=e.getBottomRightOnBit();if(n==null||o==null)throw new q;const s=this.moduleSize(n,e);let a=n[1];const l=o[1];let u=n[0];const p=(o[0]-u+1)/s,y=(l-a+1)/s;if(p<=0||y<=0)throw new q;const b=s/2;a+=b,u+=b;const I=new te(p,y);for(let R=0;R<y;R++){const U=a+R*s;for(let V=0;V<p;V++)e.get(u+V*s,U)&&I.set(V,R)}return I}static moduleSize(e,n){const o=n.getWidth();let s=e[0];const a=e[1];for(;s<o&&n.get(s,a);)s++;if(s===o)throw new q;const l=s-e[0];if(l===0)throw new q;return l}}Gn.NO_POINTS=[];class td extends Ze{constructor(e=500){super(new Gn,e)}}var Ar;(function(C){C[C.L=0]="L",C[C.M=1]="M",C[C.Q=2]="Q",C[C.H=3]="H"})(Ar||(Ar={}));class pt{constructor(e,n,o){this.value=e,this.stringValue=n,this.bits=o,pt.FOR_BITS.set(o,this),pt.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return pt.L;case"M":return pt.M;case"Q":return pt.Q;case"H":return pt.H;default:throw new E(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof pt))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=pt.FOR_BITS.size)throw new A;return pt.FOR_BITS.get(e)}}pt.FOR_BITS=new Map,pt.FOR_VALUE=new Map,pt.L=new pt(Ar.L,"L",1),pt.M=new pt(Ar.M,"M",0),pt.Q=new pt(Ar.Q,"Q",3),pt.H=new pt(Ar.H,"H",2);class Gt{constructor(e){this.errorCorrectionLevel=pt.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return F.bitCount(e^n)}static decodeFormatInformation(e,n){const o=Gt.doDecodeFormatInformation(e,n);return o!==null?o:Gt.doDecodeFormatInformation(e^Gt.FORMAT_INFO_MASK_QR,n^Gt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let o=Number.MAX_SAFE_INTEGER,s=0;for(const a of Gt.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new Gt(a[1]);let u=Gt.numBitsDiffering(e,l);u<o&&(s=a[1],o=u),e!==n&&(u=Gt.numBitsDiffering(n,l),u<o&&(s=a[1],o=u))}return o<=3?new Gt(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof Gt))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}Gt.FORMAT_INFO_MASK_QR=21522,Gt.FORMAT_INFO_DECODE_LOOKUP=[Int32Array.from([21522,0]),Int32Array.from([20773,1]),Int32Array.from([24188,2]),Int32Array.from([23371,3]),Int32Array.from([17913,4]),Int32Array.from([16590,5]),Int32Array.from([20375,6]),Int32Array.from([19104,7]),Int32Array.from([30660,8]),Int32Array.from([29427,9]),Int32Array.from([32170,10]),Int32Array.from([30877,11]),Int32Array.from([26159,12]),Int32Array.from([25368,13]),Int32Array.from([27713,14]),Int32Array.from([26998,15]),Int32Array.from([5769,16]),Int32Array.from([5054,17]),Int32Array.from([7399,18]),Int32Array.from([6608,19]),Int32Array.from([1890,20]),Int32Array.from([597,21]),Int32Array.from([3340,22]),Int32Array.from([2107,23]),Int32Array.from([13663,24]),Int32Array.from([12392,25]),Int32Array.from([16177,26]),Int32Array.from([14854,27]),Int32Array.from([9396,28]),Int32Array.from([8579,29]),Int32Array.from([11994,30]),Int32Array.from([11245,31])];class X{constructor(e,...n){this.ecCodewordsPerBlock=e,this.ecBlocks=n}getECCodewordsPerBlock(){return this.ecCodewordsPerBlock}getNumBlocks(){let e=0;const n=this.ecBlocks;for(const o of n)e+=o.getCount();return e}getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks()}getECBlocks(){return this.ecBlocks}}class k{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Ne{constructor(e,n,...o){this.versionNumber=e,this.alignmentPatternCenters=n,this.ecBlocks=o;let s=0;const a=o[0].getECCodewordsPerBlock(),l=o[0].getECBlocks();for(const u of l)s+=u.getCount()*(u.getDataCodewords()+a);this.totalCodewords=s}getVersionNumber(){return this.versionNumber}getAlignmentPatternCenters(){return this.alignmentPatternCenters}getTotalCodewords(){return this.totalCodewords}getDimensionForVersion(){return 17+4*this.versionNumber}getECBlocksForLevel(e){return this.ecBlocks[e.getValue()]}static getProvisionalVersionForDimension(e){if(e%4!==1)throw new L;try{return this.getVersionForNumber((e-17)/4)}catch{throw new L}}static getVersionForNumber(e){if(e<1||e>40)throw new A;return Ne.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,o=0;for(let s=0;s<Ne.VERSION_DECODE_INFO.length;s++){const a=Ne.VERSION_DECODE_INFO[s];if(a===e)return Ne.getVersionForNumber(s+7);const l=Gt.numBitsDiffering(e,a);l<n&&(o=s+7,n=l)}return n<=3?Ne.getVersionForNumber(o):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new te(e);n.setRegion(0,0,9,9),n.setRegion(e-8,0,8,9),n.setRegion(0,e-8,9,8);const o=this.alignmentPatternCenters.length;for(let s=0;s<o;s++){const a=this.alignmentPatternCenters[s]-2;for(let l=0;l<o;l++)s===0&&(l===0||l===o-1)||s===o-1&&l===0||n.setRegion(this.alignmentPatternCenters[l]-2,a,5,5)}return n.setRegion(6,9,1,e-17),n.setRegion(9,6,e-17,1),this.versionNumber>6&&(n.setRegion(e-11,0,3,6),n.setRegion(0,e-11,6,3)),n}toString(){return""+this.versionNumber}}Ne.VERSION_DECODE_INFO=Int32Array.from([31892,34236,39577,42195,48118,51042,55367,58893,63784,68472,70749,76311,79154,84390,87683,92361,96236,102084,102881,110507,110734,117786,119615,126325,127568,133589,136944,141498,145311,150283,152622,158308,161089,167017]),Ne.VERSIONS=[new Ne(1,new Int32Array(0),new X(7,new k(1,19)),new X(10,new k(1,16)),new X(13,new k(1,13)),new X(17,new k(1,9))),new Ne(2,Int32Array.from([6,18]),new X(10,new k(1,34)),new X(16,new k(1,28)),new X(22,new k(1,22)),new X(28,new k(1,16))),new Ne(3,Int32Array.from([6,22]),new X(15,new k(1,55)),new X(26,new k(1,44)),new X(18,new k(2,17)),new X(22,new k(2,13))),new Ne(4,Int32Array.from([6,26]),new X(20,new k(1,80)),new X(18,new k(2,32)),new X(26,new k(2,24)),new X(16,new k(4,9))),new Ne(5,Int32Array.from([6,30]),new X(26,new k(1,108)),new X(24,new k(2,43)),new X(18,new k(2,15),new k(2,16)),new X(22,new k(2,11),new k(2,12))),new Ne(6,Int32Array.from([6,34]),new X(18,new k(2,68)),new X(16,new k(4,27)),new X(24,new k(4,19)),new X(28,new k(4,15))),new Ne(7,Int32Array.from([6,22,38]),new X(20,new k(2,78)),new X(18,new k(4,31)),new X(18,new k(2,14),new k(4,15)),new X(26,new k(4,13),new k(1,14))),new Ne(8,Int32Array.from([6,24,42]),new X(24,new k(2,97)),new X(22,new k(2,38),new k(2,39)),new X(22,new k(4,18),new k(2,19)),new X(26,new k(4,14),new k(2,15))),new Ne(9,Int32Array.from([6,26,46]),new X(30,new k(2,116)),new X(22,new k(3,36),new k(2,37)),new X(20,new k(4,16),new k(4,17)),new X(24,new k(4,12),new k(4,13))),new Ne(10,Int32Array.from([6,28,50]),new X(18,new k(2,68),new k(2,69)),new X(26,new k(4,43),new k(1,44)),new X(24,new k(6,19),new k(2,20)),new X(28,new k(6,15),new k(2,16))),new Ne(11,Int32Array.from([6,30,54]),new X(20,new k(4,81)),new X(30,new k(1,50),new k(4,51)),new X(28,new k(4,22),new k(4,23)),new X(24,new k(3,12),new k(8,13))),new Ne(12,Int32Array.from([6,32,58]),new X(24,new k(2,92),new k(2,93)),new X(22,new k(6,36),new k(2,37)),new X(26,new k(4,20),new k(6,21)),new X(28,new k(7,14),new k(4,15))),new Ne(13,Int32Array.from([6,34,62]),new X(26,new k(4,107)),new X(22,new k(8,37),new k(1,38)),new X(24,new k(8,20),new k(4,21)),new X(22,new k(12,11),new k(4,12))),new Ne(14,Int32Array.from([6,26,46,66]),new X(30,new k(3,115),new k(1,116)),new X(24,new k(4,40),new k(5,41)),new X(20,new k(11,16),new k(5,17)),new X(24,new k(11,12),new k(5,13))),new Ne(15,Int32Array.from([6,26,48,70]),new X(22,new k(5,87),new k(1,88)),new X(24,new k(5,41),new k(5,42)),new X(30,new k(5,24),new k(7,25)),new X(24,new k(11,12),new k(7,13))),new Ne(16,Int32Array.from([6,26,50,74]),new X(24,new k(5,98),new k(1,99)),new X(28,new k(7,45),new k(3,46)),new X(24,new k(15,19),new k(2,20)),new X(30,new k(3,15),new k(13,16))),new Ne(17,Int32Array.from([6,30,54,78]),new X(28,new k(1,107),new k(5,108)),new X(28,new k(10,46),new k(1,47)),new X(28,new k(1,22),new k(15,23)),new X(28,new k(2,14),new k(17,15))),new Ne(18,Int32Array.from([6,30,56,82]),new X(30,new k(5,120),new k(1,121)),new X(26,new k(9,43),new k(4,44)),new X(28,new k(17,22),new k(1,23)),new X(28,new k(2,14),new k(19,15))),new Ne(19,Int32Array.from([6,30,58,86]),new X(28,new k(3,113),new k(4,114)),new X(26,new k(3,44),new k(11,45)),new X(26,new k(17,21),new k(4,22)),new X(26,new k(9,13),new k(16,14))),new Ne(20,Int32Array.from([6,34,62,90]),new X(28,new k(3,107),new k(5,108)),new X(26,new k(3,41),new k(13,42)),new X(30,new k(15,24),new k(5,25)),new X(28,new k(15,15),new k(10,16))),new Ne(21,Int32Array.from([6,28,50,72,94]),new X(28,new k(4,116),new k(4,117)),new X(26,new k(17,42)),new X(28,new k(17,22),new k(6,23)),new X(30,new k(19,16),new k(6,17))),new Ne(22,Int32Array.from([6,26,50,74,98]),new X(28,new k(2,111),new k(7,112)),new X(28,new k(17,46)),new X(30,new k(7,24),new k(16,25)),new X(24,new k(34,13))),new Ne(23,Int32Array.from([6,30,54,78,102]),new X(30,new k(4,121),new k(5,122)),new X(28,new k(4,47),new k(14,48)),new X(30,new k(11,24),new k(14,25)),new X(30,new k(16,15),new k(14,16))),new Ne(24,Int32Array.from([6,28,54,80,106]),new X(30,new k(6,117),new k(4,118)),new X(28,new k(6,45),new k(14,46)),new X(30,new k(11,24),new k(16,25)),new X(30,new k(30,16),new k(2,17))),new Ne(25,Int32Array.from([6,32,58,84,110]),new X(26,new k(8,106),new k(4,107)),new X(28,new k(8,47),new k(13,48)),new X(30,new k(7,24),new k(22,25)),new X(30,new k(22,15),new k(13,16))),new Ne(26,Int32Array.from([6,30,58,86,114]),new X(28,new k(10,114),new k(2,115)),new X(28,new k(19,46),new k(4,47)),new X(28,new k(28,22),new k(6,23)),new X(30,new k(33,16),new k(4,17))),new Ne(27,Int32Array.from([6,34,62,90,118]),new X(30,new k(8,122),new k(4,123)),new X(28,new k(22,45),new k(3,46)),new X(30,new k(8,23),new k(26,24)),new X(30,new k(12,15),new k(28,16))),new Ne(28,Int32Array.from([6,26,50,74,98,122]),new X(30,new k(3,117),new k(10,118)),new X(28,new k(3,45),new k(23,46)),new X(30,new k(4,24),new k(31,25)),new X(30,new k(11,15),new k(31,16))),new Ne(29,Int32Array.from([6,30,54,78,102,126]),new X(30,new k(7,116),new k(7,117)),new X(28,new k(21,45),new k(7,46)),new X(30,new k(1,23),new k(37,24)),new X(30,new k(19,15),new k(26,16))),new Ne(30,Int32Array.from([6,26,52,78,104,130]),new X(30,new k(5,115),new k(10,116)),new X(28,new k(19,47),new k(10,48)),new X(30,new k(15,24),new k(25,25)),new X(30,new k(23,15),new k(25,16))),new Ne(31,Int32Array.from([6,30,56,82,108,134]),new X(30,new k(13,115),new k(3,116)),new X(28,new k(2,46),new k(29,47)),new X(30,new k(42,24),new k(1,25)),new X(30,new k(23,15),new k(28,16))),new Ne(32,Int32Array.from([6,34,60,86,112,138]),new X(30,new k(17,115)),new X(28,new k(10,46),new k(23,47)),new X(30,new k(10,24),new k(35,25)),new X(30,new k(19,15),new k(35,16))),new Ne(33,Int32Array.from([6,30,58,86,114,142]),new X(30,new k(17,115),new k(1,116)),new X(28,new k(14,46),new k(21,47)),new X(30,new k(29,24),new k(19,25)),new X(30,new k(11,15),new k(46,16))),new Ne(34,Int32Array.from([6,34,62,90,118,146]),new X(30,new k(13,115),new k(6,116)),new X(28,new k(14,46),new k(23,47)),new X(30,new k(44,24),new k(7,25)),new X(30,new k(59,16),new k(1,17))),new Ne(35,Int32Array.from([6,30,54,78,102,126,150]),new X(30,new k(12,121),new k(7,122)),new X(28,new k(12,47),new k(26,48)),new X(30,new k(39,24),new k(14,25)),new X(30,new k(22,15),new k(41,16))),new Ne(36,Int32Array.from([6,24,50,76,102,128,154]),new X(30,new k(6,121),new k(14,122)),new X(28,new k(6,47),new k(34,48)),new X(30,new k(46,24),new k(10,25)),new X(30,new k(2,15),new k(64,16))),new Ne(37,Int32Array.from([6,28,54,80,106,132,158]),new X(30,new k(17,122),new k(4,123)),new X(28,new k(29,46),new k(14,47)),new X(30,new k(49,24),new k(10,25)),new X(30,new k(24,15),new k(46,16))),new Ne(38,Int32Array.from([6,32,58,84,110,136,162]),new X(30,new k(4,122),new k(18,123)),new X(28,new k(13,46),new k(32,47)),new X(30,new k(48,24),new k(14,25)),new X(30,new k(42,15),new k(32,16))),new Ne(39,Int32Array.from([6,26,54,82,110,138,166]),new X(30,new k(20,117),new k(4,118)),new X(28,new k(40,47),new k(7,48)),new X(30,new k(43,24),new k(22,25)),new X(30,new k(10,15),new k(67,16))),new Ne(40,Int32Array.from([6,30,58,86,114,142,170]),new X(30,new k(19,118),new k(6,119)),new X(28,new k(18,47),new k(31,48)),new X(30,new k(34,24),new k(34,25)),new X(30,new k(20,15),new k(61,16)))];var Ut;(function(C){C[C.DATA_MASK_000=0]="DATA_MASK_000",C[C.DATA_MASK_001=1]="DATA_MASK_001",C[C.DATA_MASK_010=2]="DATA_MASK_010",C[C.DATA_MASK_011=3]="DATA_MASK_011",C[C.DATA_MASK_100=4]="DATA_MASK_100",C[C.DATA_MASK_101=5]="DATA_MASK_101",C[C.DATA_MASK_110=6]="DATA_MASK_110",C[C.DATA_MASK_111=7]="DATA_MASK_111"})(Ut||(Ut={}));class pn{constructor(e,n){this.value=e,this.isMasked=n}unmaskBitMatrix(e,n){for(let o=0;o<n;o++)for(let s=0;s<n;s++)this.isMasked(o,s)&&e.flip(s,o)}}pn.values=new Map([[Ut.DATA_MASK_000,new pn(Ut.DATA_MASK_000,(C,e)=>(C+e&1)===0)],[Ut.DATA_MASK_001,new pn(Ut.DATA_MASK_001,(C,e)=>(C&1)===0)],[Ut.DATA_MASK_010,new pn(Ut.DATA_MASK_010,(C,e)=>e%3===0)],[Ut.DATA_MASK_011,new pn(Ut.DATA_MASK_011,(C,e)=>(C+e)%3===0)],[Ut.DATA_MASK_100,new pn(Ut.DATA_MASK_100,(C,e)=>(Math.floor(C/2)+Math.floor(e/3)&1)===0)],[Ut.DATA_MASK_101,new pn(Ut.DATA_MASK_101,(C,e)=>C*e%6===0)],[Ut.DATA_MASK_110,new pn(Ut.DATA_MASK_110,(C,e)=>C*e%6<3)],[Ut.DATA_MASK_111,new pn(Ut.DATA_MASK_111,(C,e)=>(C+e+C*e%3&1)===0)]]);class nd{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new L;this.bitMatrix=e}readFormatInformation(){if(this.parsedFormatInfo!==null&&this.parsedFormatInfo!==void 0)return this.parsedFormatInfo;let e=0;for(let a=0;a<6;a++)e=this.copyBit(a,8,e);e=this.copyBit(7,8,e),e=this.copyBit(8,8,e),e=this.copyBit(8,7,e);for(let a=5;a>=0;a--)e=this.copyBit(8,a,e);const n=this.bitMatrix.getHeight();let o=0;const s=n-7;for(let a=n-1;a>=s;a--)o=this.copyBit(8,a,o);for(let a=n-8;a<n;a++)o=this.copyBit(a,8,o);if(this.parsedFormatInfo=Gt.decodeFormatInformation(e,o),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new L}readVersion(){if(this.parsedVersion!==null&&this.parsedVersion!==void 0)return this.parsedVersion;const e=this.bitMatrix.getHeight(),n=Math.floor((e-17)/4);if(n<=6)return Ne.getVersionForNumber(n);let o=0;const s=e-11;for(let l=5;l>=0;l--)for(let u=e-9;u>=s;u--)o=this.copyBit(u,l,o);let a=Ne.decodeVersionInformation(o);if(a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;o=0;for(let l=5;l>=0;l--)for(let u=e-9;u>=s;u--)o=this.copyBit(l,u,o);if(a=Ne.decodeVersionInformation(o),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new L}copyBit(e,n,o){return(this.isMirror?this.bitMatrix.get(n,e):this.bitMatrix.get(e,n))?o<<1|1:o<<1}readCodewords(){const e=this.readFormatInformation(),n=this.readVersion(),o=pn.values.get(e.getDataMask()),s=this.bitMatrix.getHeight();o.unmaskBitMatrix(this.bitMatrix,s);const a=n.buildFunctionPattern();let l=!0;const u=new Uint8Array(n.getTotalCodewords());let h=0,p=0,y=0;for(let b=s-1;b>0;b-=2){b===6&&b--;for(let I=0;I<s;I++){const R=l?s-1-I:I;for(let U=0;U<2;U++)a.get(b-U,R)||(y++,p<<=1,this.bitMatrix.get(b-U,R)&&(p|=1),y===8&&(u[h++]=p,y=0,p=0))}l=!l}if(h!==n.getTotalCodewords())throw new L;return u}remask(){if(this.parsedFormatInfo===null)return;const e=pn.values[this.parsedFormatInfo.getDataMask()],n=this.bitMatrix.getHeight();e.unmaskBitMatrix(this.bitMatrix,n)}setMirror(e){this.parsedVersion=null,this.parsedFormatInfo=null,this.isMirror=e}mirror(){const e=this.bitMatrix;for(let n=0,o=e.getWidth();n<o;n++)for(let s=n+1,a=e.getHeight();s<a;s++)e.get(n,s)!==e.get(s,n)&&(e.flip(s,n),e.flip(n,s))}}class Yo{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n,o){if(e.length!==n.getTotalCodewords())throw new A;const s=n.getECBlocksForLevel(o);let a=0;const l=s.getECBlocks();for(const U of l)a+=U.getCount();const u=new Array(a);let h=0;for(const U of l)for(let V=0;V<U.getCount();V++){const H=U.getDataCodewords(),Q=s.getECCodewordsPerBlock()+H;u[h++]=new Yo(H,new Uint8Array(Q))}const p=u[0].codewords.length;let y=u.length-1;for(;y>=0&&u[y].codewords.length!==p;)y--;y++;const b=p-s.getECCodewordsPerBlock();let I=0;for(let U=0;U<b;U++)for(let V=0;V<h;V++)u[V].codewords[U]=e[I++];for(let U=y;U<h;U++)u[U].codewords[b]=e[I++];const R=u[0].codewords.length;for(let U=b;U<R;U++)for(let V=0;V<h;V++){const H=V<y?U:U+1;u[V].codewords[H]=e[I++]}return u}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var mn;(function(C){C[C.TERMINATOR=0]="TERMINATOR",C[C.NUMERIC=1]="NUMERIC",C[C.ALPHANUMERIC=2]="ALPHANUMERIC",C[C.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",C[C.BYTE=4]="BYTE",C[C.ECI=5]="ECI",C[C.KANJI=6]="KANJI",C[C.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",C[C.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",C[C.HANZI=9]="HANZI"})(mn||(mn={}));class Re{constructor(e,n,o,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=o,this.bits=s,Re.FOR_BITS.set(s,this),Re.FOR_VALUE.set(e,this)}static forBits(e){const n=Re.FOR_BITS.get(e);if(n===void 0)throw new A;return n}getCharacterCountBits(e){const n=e.getVersionNumber();let o;return n<=9?o=0:n<=26?o=1:o=2,this.characterCountBitsForVersions[o]}getValue(){return this.value}getBits(){return this.bits}equals(e){if(!(e instanceof Re))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}Re.FOR_BITS=new Map,Re.FOR_VALUE=new Map,Re.TERMINATOR=new Re(mn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Re.NUMERIC=new Re(mn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Re.ALPHANUMERIC=new Re(mn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Re.STRUCTURED_APPEND=new Re(mn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Re.BYTE=new Re(mn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Re.ECI=new Re(mn.ECI,"ECI",Int32Array.from([0,0,0]),7),Re.KANJI=new Re(mn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Re.FNC1_FIRST_POSITION=new Re(mn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Re.FNC1_SECOND_POSITION=new Re(mn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Re.HANZI=new Re(mn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class Et{static decode(e,n,o,s){const a=new Xo(e);let l=new fe;const u=new Array;let h=-1,p=-1;try{let y=null,b=!1,I;do{if(a.available()<4)I=Re.TERMINATOR;else{const R=a.readBits(4);I=Re.forBits(R)}switch(I){case Re.TERMINATOR:break;case Re.FNC1_FIRST_POSITION:case Re.FNC1_SECOND_POSITION:b=!0;break;case Re.STRUCTURED_APPEND:if(a.available()<16)throw new L;h=a.readBits(8),p=a.readBits(8);break;case Re.ECI:const R=Et.parseECIValue(a);if(y=z.getCharacterSetECIByValue(R),y===null)throw new L;break;case Re.HANZI:const U=a.readBits(4),V=a.readBits(I.getCharacterCountBits(n));U===Et.GB2312_SUBSET&&Et.decodeHanziSegment(a,l,V);break;default:const H=a.readBits(I.getCharacterCountBits(n));switch(I){case Re.NUMERIC:Et.decodeNumericSegment(a,l,H);break;case Re.ALPHANUMERIC:Et.decodeAlphanumericSegment(a,l,H,b);break;case Re.BYTE:Et.decodeByteSegment(a,l,H,y,u,s);break;case Re.KANJI:Et.decodeKanjiSegment(a,l,H);break;default:throw new L}break}}while(I!==Re.TERMINATOR)}catch{throw new L}return new Pe(e,l.toString(),u.length===0?null:u,o===null?null:o.toString(),h,p)}static decodeHanziSegment(e,n,o){if(o*13>e.available())throw new L;const s=new Uint8Array(2*o);let a=0;for(;o>0;){const l=e.readBits(13);let u=l/96<<8&4294967295|l%96;u<959?u+=41377:u+=42657,s[a]=u>>8&255,s[a+1]=u&255,a+=2,o--}try{n.append(G.decode(s,me.GB2312))}catch(l){throw new L(l)}}static decodeKanjiSegment(e,n,o){if(o*13>e.available())throw new L;const s=new Uint8Array(2*o);let a=0;for(;o>0;){const l=e.readBits(13);let u=l/192<<8&4294967295|l%192;u<7936?u+=33088:u+=49472,s[a]=u>>8,s[a+1]=u,a+=2,o--}try{n.append(G.decode(s,me.SHIFT_JIS))}catch(l){throw new L(l)}}static decodeByteSegment(e,n,o,s,a,l){if(8*o>e.available())throw new L;const u=new Uint8Array(o);for(let p=0;p<o;p++)u[p]=e.readBits(8);let h;s===null?h=me.guessEncoding(u,l):h=s.getName();try{n.append(G.decode(u,h))}catch(p){throw new L(p)}a.push(u)}static toAlphaNumericChar(e){if(e>=Et.ALPHANUMERIC_CHARS.length)throw new L;return Et.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,o,s){const a=n.length();for(;o>1;){if(e.available()<11)throw new L;const l=e.readBits(11);n.append(Et.toAlphaNumericChar(Math.floor(l/45))),n.append(Et.toAlphaNumericChar(l%45)),o-=2}if(o===1){if(e.available()<6)throw new L;n.append(Et.toAlphaNumericChar(e.readBits(6)))}if(s)for(let l=a;l<n.length();l++)n.charAt(l)==="%"&&(l<n.length()-1&&n.charAt(l+1)==="%"?n.deleteCharAt(l+1):n.setCharAt(l,""))}static decodeNumericSegment(e,n,o){for(;o>=3;){if(e.available()<10)throw new L;const s=e.readBits(10);if(s>=1e3)throw new L;n.append(Et.toAlphaNumericChar(Math.floor(s/100))),n.append(Et.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(Et.toAlphaNumericChar(s%10)),o-=3}if(o===2){if(e.available()<7)throw new L;const s=e.readBits(7);if(s>=100)throw new L;n.append(Et.toAlphaNumericChar(Math.floor(s/10))),n.append(Et.toAlphaNumericChar(s%10))}else if(o===1){if(e.available()<4)throw new L;const s=e.readBits(4);if(s>=10)throw new L;n.append(Et.toAlphaNumericChar(s))}}static parseECIValue(e){const n=e.readBits(8);if((n&128)===0)return n&127;if((n&192)===128){const o=e.readBits(8);return(n&63)<<8&4294967295|o}if((n&224)===192){const o=e.readBits(16);return(n&31)<<16&4294967295|o}throw new L}}Et.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",Et.GB2312_SUBSET=1;class us{constructor(e){this.mirrored=e}isMirrored(){return this.mirrored}applyMirroredCorrection(e){if(!this.mirrored||e===null||e.length<3)return;const n=e[0];e[0]=e[2],e[2]=n}}class rd{constructor(){this.rsDecoder=new vt(Se.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(te.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const o=new nd(e);let s=null;try{return this.decodeBitMatrixParser(o,n)}catch(a){s=a}try{o.remask(),o.setMirror(!0),o.readVersion(),o.readFormatInformation(),o.mirror();const a=this.decodeBitMatrixParser(o,n);return a.setOther(new us(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const o=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=Yo.getDataBlocks(a,o,s);let u=0;for(const y of l)u+=y.getNumDataCodewords();const h=new Uint8Array(u);let p=0;for(const y of l){const b=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(b,I);for(let R=0;R<I;R++)h[p++]=b[R]}return Et.decode(h,o,s,n)}correctErrors(e,n){const o=new Int32Array(e);try{this.rsDecoder.decode(o,e.length-n)}catch{throw new T}for(let s=0;s<n;s++)e[s]=o[s]}}class Ko extends be{constructor(e,n,o){super(e,n),this.estimatedModuleSize=o}aboutEquals(e,n,o){if(Math.abs(n-this.getY())<=e&&Math.abs(o-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,o){const s=(this.getX()+n)/2,a=(this.getY()+e)/2,l=(this.estimatedModuleSize+o)/2;return new Ko(s,a,l)}}class ho{constructor(e,n,o,s,a,l,u){this.image=e,this.startX=n,this.startY=o,this.width=s,this.height=a,this.moduleSize=l,this.resultPointCallback=u,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(3)}find(){const e=this.startX,n=this.height,o=this.width,s=e+o,a=this.startY+n/2,l=new Int32Array(3),u=this.image;for(let h=0;h<n;h++){const p=a+((h&1)===0?Math.floor((h+1)/2):-Math.floor((h+1)/2));l[0]=0,l[1]=0,l[2]=0;let y=e;for(;y<s&&!u.get(y,p);)y++;let b=0;for(;y<s;){if(u.get(y,p))if(b===1)l[1]++;else if(b===2){if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,y);if(I!==null)return I}l[0]=l[2],l[1]=1,l[2]=0,b=1}else l[++b]++;else b===1&&b++,l[b]++;y++}if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,s);if(I!==null)return I}}if(this.possibleCenters.length!==0)return this.possibleCenters[0];throw new q}static centerFromEnd(e,n){return n-e[2]-e[1]/2}foundPatternCross(e){const n=this.moduleSize,o=n/2;for(let s=0;s<3;s++)if(Math.abs(n-e[s])>=o)return!1;return!0}crossCheckVertical(e,n,o,s){const a=this.image,l=a.getHeight(),u=this.crossCheckStateCount;u[0]=0,u[1]=0,u[2]=0;let h=e;for(;h>=0&&a.get(n,h)&&u[1]<=o;)u[1]++,h--;if(h<0||u[1]>o)return NaN;for(;h>=0&&!a.get(n,h)&&u[0]<=o;)u[0]++,h--;if(u[0]>o)return NaN;for(h=e+1;h<l&&a.get(n,h)&&u[1]<=o;)u[1]++,h++;if(h===l||u[1]>o)return NaN;for(;h<l&&!a.get(n,h)&&u[2]<=o;)u[2]++,h++;if(u[2]>o)return NaN;const p=u[0]+u[1]+u[2];return 5*Math.abs(p-s)>=2*s?NaN:this.foundPatternCross(u)?ho.centerFromEnd(u,h):NaN}handlePossibleCenter(e,n,o){const s=e[0]+e[1]+e[2],a=ho.centerFromEnd(e,o),l=this.crossCheckVertical(n,a,2*e[1],s);if(!isNaN(l)){const u=(e[0]+e[1]+e[2])/3;for(const p of this.possibleCenters)if(p.aboutEquals(u,l,a))return p.combineEstimate(l,a,u);const h=new Ko(a,l,u);this.possibleCenters.push(h),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(h)}return null}}class Jo extends be{constructor(e,n,o,s){super(e,n),this.estimatedModuleSize=o,this.count=s,s===void 0&&(this.count=1)}getEstimatedModuleSize(){return this.estimatedModuleSize}getCount(){return this.count}aboutEquals(e,n,o){if(Math.abs(n-this.getY())<=e&&Math.abs(o-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,o){const s=this.count+1,a=(this.count*this.getX()+n)/s,l=(this.count*this.getY()+e)/s,u=(this.count*this.estimatedModuleSize+o)/s;return new Jo(a,l,u,s)}}class od{constructor(e){this.bottomLeft=e[0],this.topLeft=e[1],this.topRight=e[2]}getBottomLeft(){return this.bottomLeft}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}}class zt{constructor(e,n){this.image=e,this.resultPointCallback=n,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(5),this.resultPointCallback=n}getImage(){return this.image}getPossibleCenters(){return this.possibleCenters}find(e){const n=e!=null&&e.get(B.TRY_HARDER)!==void 0,o=e!=null&&e.get(B.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let u=Math.floor(3*a/(4*zt.MAX_MODULES));(u<zt.MIN_SKIP||n)&&(u=zt.MIN_SKIP);let h=!1;const p=new Int32Array(5);for(let b=u-1;b<a&&!h;b+=u){p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0;let I=0;for(let R=0;R<l;R++)if(s.get(R,b))(I&1)===1&&I++,p[I]++;else if((I&1)===0)if(I===4)if(zt.foundPatternCross(p)){if(this.handlePossibleCenter(p,b,R,o)===!0)if(u=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const V=this.findRowSkip();V>p[2]&&(b+=V-p[2]-u,R=l-1)}else{p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;continue}I=0,p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0}else p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;else p[++I]++;else p[I]++;zt.foundPatternCross(p)&&this.handlePossibleCenter(p,b,l,o)===!0&&(u=p[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const y=this.selectBestPatterns();return be.orderBestPatterns(y),new od(y)}static centerFromEnd(e,n){return n-e[4]-e[3]-e[2]/2}static foundPatternCross(e){let n=0;for(let a=0;a<5;a++){const l=e[a];if(l===0)return!1;n+=l}if(n<7)return!1;const o=n/7,s=o/2;return Math.abs(o-e[0])<s&&Math.abs(o-e[1])<s&&Math.abs(3*o-e[2])<3*s&&Math.abs(o-e[3])<s&&Math.abs(o-e[4])<s}getCrossCheckStateCount(){const e=this.crossCheckStateCount;return e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e}crossCheckDiagonal(e,n,o,s){const a=this.getCrossCheckStateCount();let l=0;const u=this.image;for(;e>=l&&n>=l&&u.get(n-l,e-l);)a[2]++,l++;if(e<l||n<l)return!1;for(;e>=l&&n>=l&&!u.get(n-l,e-l)&&a[1]<=o;)a[1]++,l++;if(e<l||n<l||a[1]>o)return!1;for(;e>=l&&n>=l&&u.get(n-l,e-l)&&a[0]<=o;)a[0]++,l++;if(a[0]>o)return!1;const h=u.getHeight(),p=u.getWidth();for(l=1;e+l<h&&n+l<p&&u.get(n+l,e+l);)a[2]++,l++;if(e+l>=h||n+l>=p)return!1;for(;e+l<h&&n+l<p&&!u.get(n+l,e+l)&&a[3]<o;)a[3]++,l++;if(e+l>=h||n+l>=p||a[3]>=o)return!1;for(;e+l<h&&n+l<p&&u.get(n+l,e+l)&&a[4]<o;)a[4]++,l++;if(a[4]>=o)return!1;const y=a[0]+a[1]+a[2]+a[3]+a[4];return Math.abs(y-s)<2*s&&zt.foundPatternCross(a)}crossCheckVertical(e,n,o,s){const a=this.image,l=a.getHeight(),u=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(n,h);)u[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(n,h)&&u[1]<=o;)u[1]++,h--;if(h<0||u[1]>o)return NaN;for(;h>=0&&a.get(n,h)&&u[0]<=o;)u[0]++,h--;if(u[0]>o)return NaN;for(h=e+1;h<l&&a.get(n,h);)u[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(n,h)&&u[3]<o;)u[3]++,h++;if(h===l||u[3]>=o)return NaN;for(;h<l&&a.get(n,h)&&u[4]<o;)u[4]++,h++;if(u[4]>=o)return NaN;const p=u[0]+u[1]+u[2]+u[3]+u[4];return 5*Math.abs(p-s)>=2*s?NaN:zt.foundPatternCross(u)?zt.centerFromEnd(u,h):NaN}crossCheckHorizontal(e,n,o,s){const a=this.image,l=a.getWidth(),u=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(h,n);)u[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(h,n)&&u[1]<=o;)u[1]++,h--;if(h<0||u[1]>o)return NaN;for(;h>=0&&a.get(h,n)&&u[0]<=o;)u[0]++,h--;if(u[0]>o)return NaN;for(h=e+1;h<l&&a.get(h,n);)u[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(h,n)&&u[3]<o;)u[3]++,h++;if(h===l||u[3]>=o)return NaN;for(;h<l&&a.get(h,n)&&u[4]<o;)u[4]++,h++;if(u[4]>=o)return NaN;const p=u[0]+u[1]+u[2]+u[3]+u[4];return 5*Math.abs(p-s)>=s?NaN:zt.foundPatternCross(u)?zt.centerFromEnd(u,h):NaN}handlePossibleCenter(e,n,o,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=zt.centerFromEnd(e,o),u=this.crossCheckVertical(n,Math.floor(l),e[2],a);if(!isNaN(u)&&(l=this.crossCheckHorizontal(Math.floor(l),Math.floor(u),e[2],a),!isNaN(l)&&(!s||this.crossCheckDiagonal(Math.floor(u),Math.floor(l),e[2],a)))){const h=a/7;let p=!1;const y=this.possibleCenters;for(let b=0,I=y.length;b<I;b++){const R=y[b];if(R.aboutEquals(h,u,l)){y[b]=R.combineEstimate(u,l,h),p=!0;break}}if(!p){const b=new Jo(l,u,h);y.push(b),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(b)}return!0}return!1}findRowSkip(){if(this.possibleCenters.length<=1)return 0;let n=null;for(const o of this.possibleCenters)if(o.getCount()>=zt.CENTER_QUORUM)if(n==null)n=o;else return this.hasSkipped=!0,Math.floor((Math.abs(n.getX()-o.getX())-Math.abs(n.getY()-o.getY()))/2);return 0}haveMultiplyConfirmedCenters(){let e=0,n=0;const o=this.possibleCenters.length;for(const l of this.possibleCenters)l.getCount()>=zt.CENTER_QUORUM&&(e++,n+=l.getEstimatedModuleSize());if(e<3)return!1;const s=n/o;let a=0;for(const l of this.possibleCenters)a+=Math.abs(l.getEstimatedModuleSize()-s);return a<=.05*n}selectBestPatterns(){const e=this.possibleCenters.length;if(e<3)throw new q;const n=this.possibleCenters;let o;if(e>3){let s=0,a=0;for(const h of this.possibleCenters){const p=h.getEstimatedModuleSize();s+=p,a+=p*p}o=s/e;let l=Math.sqrt(a/e-o*o);n.sort((h,p)=>{const y=Math.abs(p.getEstimatedModuleSize()-o),b=Math.abs(h.getEstimatedModuleSize()-o);return y<b?-1:y>b?1:0});const u=Math.max(.2*o,l);for(let h=0;h<n.length&&n.length>3;h++){const p=n[h];Math.abs(p.getEstimatedModuleSize()-o)>u&&(n.splice(h,1),h--)}}if(n.length>3){let s=0;for(const a of n)s+=a.getEstimatedModuleSize();o=s/n.length,n.sort((a,l)=>{if(l.getCount()===a.getCount()){const u=Math.abs(l.getEstimatedModuleSize()-o),h=Math.abs(a.getEstimatedModuleSize()-o);return u<h?1:u>h?-1:0}else return l.getCount()-a.getCount()}),n.splice(3)}return[n[0],n[1],n[2]]}}zt.CENTER_QUORUM=2,zt.MIN_SKIP=3,zt.MAX_MODULES=57;class Dr{constructor(e){this.image=e}getImage(){return this.image}getResultPointCallback(){return this.resultPointCallback}detect(e){this.resultPointCallback=e==null?null:e.get(B.NEED_RESULT_POINT_CALLBACK);const o=new zt(this.image,this.resultPointCallback).find(e);return this.processFinderPatternInfo(o)}processFinderPatternInfo(e){const n=e.getTopLeft(),o=e.getTopRight(),s=e.getBottomLeft(),a=this.calculateModuleSize(n,o,s);if(a<1)throw new q("No pattern found in proccess finder.");const l=Dr.computeDimension(n,o,s,a),u=Ne.getProvisionalVersionForDimension(l),h=u.getDimensionForVersion()-7;let p=null;if(u.getAlignmentPatternCenters().length>0){const R=o.getX()-n.getX()+s.getX(),U=o.getY()-n.getY()+s.getY(),V=1-3/h,H=Math.floor(n.getX()+V*(R-n.getX())),Q=Math.floor(n.getY()+V*(U-n.getY()));for(let he=4;he<=16;he<<=1)try{p=this.findAlignmentInRegion(a,H,Q,he);break}catch(pe){if(!(pe instanceof q))throw pe}}const y=Dr.createTransform(n,o,s,p,l),b=Dr.sampleGrid(this.image,y,l);let I;return p===null?I=[s,n,o]:I=[s,n,o,p],new Bn(b,I)}static createTransform(e,n,o,s,a){const l=a-3.5;let u,h,p,y;return s!==null?(u=s.getX(),h=s.getY(),p=l-3,y=p):(u=n.getX()-e.getX()+o.getX(),h=n.getY()-e.getY()+o.getY(),p=l,y=l),Ft.quadrilateralToQuadrilateral(3.5,3.5,l,3.5,p,y,3.5,l,e.getX(),e.getY(),n.getX(),n.getY(),u,h,o.getX(),o.getY())}static sampleGrid(e,n,o){return sn.getInstance().sampleGridWithTransform(e,o,o,n)}static computeDimension(e,n,o,s){const a=Xe.round(be.distance(e,n)/s),l=Xe.round(be.distance(e,o)/s);let u=Math.floor((a+l)/2)+7;switch(u&3){case 0:u++;break;case 2:u--;break;case 3:throw new q("Dimensions could be not found.")}return u}calculateModuleSize(e,n,o){return(this.calculateModuleSizeOneWay(e,n)+this.calculateModuleSizeOneWay(e,o))/2}calculateModuleSizeOneWay(e,n){const o=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(e.getX()),Math.floor(e.getY()),Math.floor(n.getX()),Math.floor(n.getY())),s=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(n.getX()),Math.floor(n.getY()),Math.floor(e.getX()),Math.floor(e.getY()));return isNaN(o)?s/7:isNaN(s)?o/7:(o+s)/14}sizeOfBlackWhiteBlackRunBothWays(e,n,o,s){let a=this.sizeOfBlackWhiteBlackRun(e,n,o,s),l=1,u=e-(o-e);u<0?(l=e/(e-u),u=0):u>=this.image.getWidth()&&(l=(this.image.getWidth()-1-e)/(u-e),u=this.image.getWidth()-1);let h=Math.floor(n-(s-n)*l);return l=1,h<0?(l=n/(n-h),h=0):h>=this.image.getHeight()&&(l=(this.image.getHeight()-1-n)/(h-n),h=this.image.getHeight()-1),u=Math.floor(e+(u-e)*l),a+=this.sizeOfBlackWhiteBlackRun(e,n,u,h),a-1}sizeOfBlackWhiteBlackRun(e,n,o,s){const a=Math.abs(s-n)>Math.abs(o-e);if(a){let R=e;e=n,n=R,R=o,o=s,s=R}const l=Math.abs(o-e),u=Math.abs(s-n);let h=-l/2;const p=e<o?1:-1,y=n<s?1:-1;let b=0;const I=o+p;for(let R=e,U=n;R!==I;R+=p){const V=a?U:R,H=a?R:U;if(b===1===this.image.get(V,H)){if(b===2)return Xe.distance(R,U,e,n);b++}if(h+=u,h>0){if(U===s)break;U+=y,h-=l}}return b===2?Xe.distance(o+p,s,e,n):NaN}findAlignmentInRegion(e,n,o,s){const a=Math.floor(s*e),l=Math.max(0,n-a),u=Math.min(this.image.getWidth()-1,n+a);if(u-l<e*3)throw new q("Alignment top exceeds estimated module size.");const h=Math.max(0,o-a),p=Math.min(this.image.getHeight()-1,o+a);if(p-h<e*3)throw new q("Alignment bottom exceeds estimated module size.");return new ho(this.image,l,h,u-l,p-h,e,this.resultPointCallback).find()}}class qn{constructor(){this.decoder=new rd}getDecoder(){return this.decoder}decode(e,n){let o,s;if(n!=null&&n.get(B.PURE_BARCODE)!==void 0){const h=qn.extractPureBits(e.getBlackMatrix());o=this.decoder.decodeBitMatrix(h,n),s=qn.NO_POINTS}else{const h=new Dr(e.getBlackMatrix()).detect(n);o=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}o.getOther()instanceof us&&o.getOther().applyMirroredCorrection(s);const a=new qe(o.getText(),o.getRawBytes(),void 0,s,ie.QR_CODE,void 0),l=o.getByteSegments();l!==null&&a.putMetadata(_e.BYTE_SEGMENTS,l);const u=o.getECLevel();return u!==null&&a.putMetadata(_e.ERROR_CORRECTION_LEVEL,u),o.hasStructuredAppend()&&(a.putMetadata(_e.STRUCTURED_APPEND_SEQUENCE,o.getStructuredAppendSequenceNumber()),a.putMetadata(_e.STRUCTURED_APPEND_PARITY,o.getStructuredAppendParity())),a}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),o=e.getBottomRightOnBit();if(n===null||o===null)throw new q;const s=this.moduleSize(n,e);let a=n[1],l=o[1],u=n[0],h=o[0];if(u>=h||a>=l)throw new q;if(l-a!==h-u&&(h=u+(l-a),h>=e.getWidth()))throw new q;const p=Math.round((h-u+1)/s),y=Math.round((l-a+1)/s);if(p<=0||y<=0)throw new q;if(y!==p)throw new q;const b=Math.floor(s/2);a+=b,u+=b;const I=u+Math.floor((p-1)*s)-h;if(I>0){if(I>b)throw new q;u-=I}const R=a+Math.floor((y-1)*s)-l;if(R>0){if(R>b)throw new q;a-=R}const U=new te(p,y);for(let V=0;V<y;V++){const H=a+Math.floor(V*s);for(let Q=0;Q<p;Q++)e.get(u+Math.floor(Q*s),H)&&U.set(Q,V)}return U}static moduleSize(e,n){const o=n.getHeight(),s=n.getWidth();let a=e[0],l=e[1],u=!0,h=0;for(;a<s&&l<o;){if(u!==n.get(a,l)){if(++h===5)break;u=!u}a++,l++}if(a===s||l===o)throw new q;return(a-e[0])/7}}qn.NO_POINTS=new Array;class Be{PDF417Common(){}static getBitCountSum(e){return Xe.sum(e)}static toIntArray(e){if(e==null||!e.length)return Be.EMPTY_INT_ARRAY;const n=new Int32Array(e.length);let o=0;for(const s of e)n[o++]=s;return n}static getCodeword(e){const n=$.binarySearch(Be.SYMBOL_TABLE,e&262143);return n<0?-1:(Be.CODEWORD_TABLE[n]-1)%Be.NUMBER_OF_CODEWORDS}}Be.NUMBER_OF_CODEWORDS=929,Be.MAX_CODEWORDS_IN_BARCODE=Be.NUMBER_OF_CODEWORDS-1,Be.MIN_ROWS_IN_BARCODE=3,Be.MAX_ROWS_IN_BARCODE=90,Be.MODULES_IN_CODEWORD=17,Be.MODULES_IN_STOP_PATTERN=18,Be.BARS_IN_MODULE=8,Be.EMPTY_INT_ARRAY=new Int32Array([]),Be.SYMBOL_TABLE=Int32Array.from([66142,66170,66206,66236,66290,66292,66350,66382,66396,66454,66470,66476,66594,66600,66614,66626,66628,66632,66640,66654,66662,66668,66682,66690,66718,66720,66748,66758,66776,66798,66802,66804,66820,66824,66832,66846,66848,66876,66880,66936,66950,66956,66968,66992,67006,67022,67036,67042,67044,67048,67062,67118,67150,67164,67214,67228,67256,67294,67322,67350,67366,67372,67398,67404,67416,67438,67474,67476,67490,67492,67496,67510,67618,67624,67650,67656,67664,67678,67686,67692,67706,67714,67716,67728,67742,67744,67772,67782,67788,67800,67822,67826,67828,67842,67848,67870,67872,67900,67904,67960,67974,67992,68016,68030,68046,68060,68066,68068,68072,68086,68104,68112,68126,68128,68156,68160,68216,68336,68358,68364,68376,68400,68414,68448,68476,68494,68508,68536,68546,68548,68552,68560,68574,68582,68588,68654,68686,68700,68706,68708,68712,68726,68750,68764,68792,68802,68804,68808,68816,68830,68838,68844,68858,68878,68892,68920,68976,68990,68994,68996,69e3,69008,69022,69024,69052,69062,69068,69080,69102,69106,69108,69142,69158,69164,69190,69208,69230,69254,69260,69272,69296,69310,69326,69340,69386,69394,69396,69410,69416,69430,69442,69444,69448,69456,69470,69478,69484,69554,69556,69666,69672,69698,69704,69712,69726,69754,69762,69764,69776,69790,69792,69820,69830,69836,69848,69870,69874,69876,69890,69918,69920,69948,69952,70008,70022,70040,70064,70078,70094,70108,70114,70116,70120,70134,70152,70174,70176,70264,70384,70412,70448,70462,70496,70524,70542,70556,70584,70594,70600,70608,70622,70630,70636,70664,70672,70686,70688,70716,70720,70776,70896,71136,71180,71192,71216,71230,71264,71292,71360,71416,71452,71480,71536,71550,71554,71556,71560,71568,71582,71584,71612,71622,71628,71640,71662,71726,71732,71758,71772,71778,71780,71784,71798,71822,71836,71864,71874,71880,71888,71902,71910,71916,71930,71950,71964,71992,72048,72062,72066,72068,72080,72094,72096,72124,72134,72140,72152,72174,72178,72180,72206,72220,72248,72304,72318,72416,72444,72456,72464,72478,72480,72508,72512,72568,72588,72600,72624,72638,72654,72668,72674,72676,72680,72694,72726,72742,72748,72774,72780,72792,72814,72838,72856,72880,72894,72910,72924,72930,72932,72936,72950,72966,72972,72984,73008,73022,73056,73084,73102,73116,73144,73156,73160,73168,73182,73190,73196,73210,73226,73234,73236,73250,73252,73256,73270,73282,73284,73296,73310,73318,73324,73346,73348,73352,73360,73374,73376,73404,73414,73420,73432,73454,73498,73518,73522,73524,73550,73564,73570,73572,73576,73590,73800,73822,73858,73860,73872,73886,73888,73916,73944,73970,73972,73992,74014,74016,74044,74048,74104,74118,74136,74160,74174,74210,74212,74216,74230,74244,74256,74270,74272,74360,74480,74502,74508,74544,74558,74592,74620,74638,74652,74680,74690,74696,74704,74726,74732,74782,74784,74812,74992,75232,75288,75326,75360,75388,75456,75512,75576,75632,75646,75650,75652,75664,75678,75680,75708,75718,75724,75736,75758,75808,75836,75840,75896,76016,76256,76736,76824,76848,76862,76896,76924,76992,77048,77296,77340,77368,77424,77438,77536,77564,77572,77576,77584,77600,77628,77632,77688,77702,77708,77720,77744,77758,77774,77788,77870,77902,77916,77922,77928,77966,77980,78008,78018,78024,78032,78046,78060,78074,78094,78136,78192,78206,78210,78212,78224,78238,78240,78268,78278,78284,78296,78322,78324,78350,78364,78448,78462,78560,78588,78600,78622,78624,78652,78656,78712,78726,78744,78768,78782,78798,78812,78818,78820,78824,78838,78862,78876,78904,78960,78974,79072,79100,79296,79352,79368,79376,79390,79392,79420,79424,79480,79600,79628,79640,79664,79678,79712,79740,79772,79800,79810,79812,79816,79824,79838,79846,79852,79894,79910,79916,79942,79948,79960,79982,79988,80006,80024,80048,80062,80078,80092,80098,80100,80104,80134,80140,80176,80190,80224,80252,80270,80284,80312,80328,80336,80350,80358,80364,80378,80390,80396,80408,80432,80446,80480,80508,80576,80632,80654,80668,80696,80752,80766,80776,80784,80798,80800,80828,80844,80856,80878,80882,80884,80914,80916,80930,80932,80936,80950,80962,80968,80976,80990,80998,81004,81026,81028,81040,81054,81056,81084,81094,81100,81112,81134,81154,81156,81160,81168,81182,81184,81212,81216,81272,81286,81292,81304,81328,81342,81358,81372,81380,81384,81398,81434,81454,81458,81460,81486,81500,81506,81508,81512,81526,81550,81564,81592,81602,81604,81608,81616,81630,81638,81644,81702,81708,81722,81734,81740,81752,81774,81778,81780,82050,82078,82080,82108,82180,82184,82192,82206,82208,82236,82240,82296,82316,82328,82352,82366,82402,82404,82408,82440,82448,82462,82464,82492,82496,82552,82672,82694,82700,82712,82736,82750,82784,82812,82830,82882,82884,82888,82896,82918,82924,82952,82960,82974,82976,83004,83008,83064,83184,83424,83468,83480,83504,83518,83552,83580,83648,83704,83740,83768,83824,83838,83842,83844,83848,83856,83872,83900,83910,83916,83928,83950,83984,84e3,84028,84032,84088,84208,84448,84928,85040,85054,85088,85116,85184,85240,85488,85560,85616,85630,85728,85756,85764,85768,85776,85790,85792,85820,85824,85880,85894,85900,85912,85936,85966,85980,86048,86080,86136,86256,86496,86976,88160,88188,88256,88312,88560,89056,89200,89214,89312,89340,89536,89592,89608,89616,89632,89664,89720,89840,89868,89880,89904,89952,89980,89998,90012,90040,90190,90204,90254,90268,90296,90306,90308,90312,90334,90382,90396,90424,90480,90494,90500,90504,90512,90526,90528,90556,90566,90572,90584,90610,90612,90638,90652,90680,90736,90750,90848,90876,90884,90888,90896,90910,90912,90940,90944,91e3,91014,91020,91032,91056,91070,91086,91100,91106,91108,91112,91126,91150,91164,91192,91248,91262,91360,91388,91584,91640,91664,91678,91680,91708,91712,91768,91888,91928,91952,91966,92e3,92028,92046,92060,92088,92098,92100,92104,92112,92126,92134,92140,92188,92216,92272,92384,92412,92608,92664,93168,93200,93214,93216,93244,93248,93304,93424,93664,93720,93744,93758,93792,93820,93888,93944,93980,94008,94064,94078,94084,94088,94096,94110,94112,94140,94150,94156,94168,94246,94252,94278,94284,94296,94318,94342,94348,94360,94384,94398,94414,94428,94440,94470,94476,94488,94512,94526,94560,94588,94606,94620,94648,94658,94660,94664,94672,94686,94694,94700,94714,94726,94732,94744,94768,94782,94816,94844,94912,94968,94990,95004,95032,95088,95102,95112,95120,95134,95136,95164,95180,95192,95214,95218,95220,95244,95256,95280,95294,95328,95356,95424,95480,95728,95758,95772,95800,95856,95870,95968,95996,96008,96016,96030,96032,96060,96064,96120,96152,96176,96190,96220,96226,96228,96232,96290,96292,96296,96310,96322,96324,96328,96336,96350,96358,96364,96386,96388,96392,96400,96414,96416,96444,96454,96460,96472,96494,96498,96500,96514,96516,96520,96528,96542,96544,96572,96576,96632,96646,96652,96664,96688,96702,96718,96732,96738,96740,96744,96758,96772,96776,96784,96798,96800,96828,96832,96888,97008,97030,97036,97048,97072,97086,97120,97148,97166,97180,97208,97220,97224,97232,97246,97254,97260,97326,97330,97332,97358,97372,97378,97380,97384,97398,97422,97436,97464,97474,97476,97480,97488,97502,97510,97516,97550,97564,97592,97648,97666,97668,97672,97680,97694,97696,97724,97734,97740,97752,97774,97830,97836,97850,97862,97868,97880,97902,97906,97908,97926,97932,97944,97968,97998,98012,98018,98020,98024,98038,98618,98674,98676,98838,98854,98874,98892,98904,98926,98930,98932,98968,99006,99042,99044,99048,99062,99166,99194,99246,99286,99350,99366,99372,99386,99398,99416,99438,99442,99444,99462,99504,99518,99534,99548,99554,99556,99560,99574,99590,99596,99608,99632,99646,99680,99708,99726,99740,99768,99778,99780,99784,99792,99806,99814,99820,99834,99858,99860,99874,99880,99894,99906,99920,99934,99962,99970,99972,99976,99984,99998,1e5,100028,100038,100044,100056,100078,100082,100084,100142,100174,100188,100246,100262,100268,100306,100308,100390,100396,100410,100422,100428,100440,100462,100466,100468,100486,100504,100528,100542,100558,100572,100578,100580,100584,100598,100620,100656,100670,100704,100732,100750,100792,100802,100808,100816,100830,100838,100844,100858,100888,100912,100926,100960,100988,101056,101112,101148,101176,101232,101246,101250,101252,101256,101264,101278,101280,101308,101318,101324,101336,101358,101362,101364,101410,101412,101416,101430,101442,101448,101456,101470,101478,101498,101506,101508,101520,101534,101536,101564,101580,101618,101620,101636,101640,101648,101662,101664,101692,101696,101752,101766,101784,101838,101858,101860,101864,101934,101938,101940,101966,101980,101986,101988,101992,102030,102044,102072,102082,102084,102088,102096,102138,102166,102182,102188,102214,102220,102232,102254,102282,102290,102292,102306,102308,102312,102326,102444,102458,102470,102476,102488,102514,102516,102534,102552,102576,102590,102606,102620,102626,102632,102646,102662,102668,102704,102718,102752,102780,102798,102812,102840,102850,102856,102864,102878,102886,102892,102906,102936,102974,103008,103036,103104,103160,103224,103280,103294,103298,103300,103312,103326,103328,103356,103366,103372,103384,103406,103410,103412,103472,103486,103520,103548,103616,103672,103920,103992,104048,104062,104160,104188,104194,104196,104200,104208,104224,104252,104256,104312,104326,104332,104344,104368,104382,104398,104412,104418,104420,104424,104482,104484,104514,104520,104528,104542,104550,104570,104578,104580,104592,104606,104608,104636,104652,104690,104692,104706,104712,104734,104736,104764,104768,104824,104838,104856,104910,104930,104932,104936,104968,104976,104990,104992,105020,105024,105080,105200,105240,105278,105312,105372,105410,105412,105416,105424,105446,105518,105524,105550,105564,105570,105572,105576,105614,105628,105656,105666,105672,105680,105702,105722,105742,105756,105784,105840,105854,105858,105860,105864,105872,105888,105932,105970,105972,106006,106022,106028,106054,106060,106072,106100,106118,106124,106136,106160,106174,106190,106210,106212,106216,106250,106258,106260,106274,106276,106280,106306,106308,106312,106320,106334,106348,106394,106414,106418,106420,106566,106572,106610,106612,106630,106636,106648,106672,106686,106722,106724,106728,106742,106758,106764,106776,106800,106814,106848,106876,106894,106908,106936,106946,106948,106952,106960,106974,106982,106988,107032,107056,107070,107104,107132,107200,107256,107292,107320,107376,107390,107394,107396,107400,107408,107422,107424,107452,107462,107468,107480,107502,107506,107508,107544,107568,107582,107616,107644,107712,107768,108016,108060,108088,108144,108158,108256,108284,108290,108292,108296,108304,108318,108320,108348,108352,108408,108422,108428,108440,108464,108478,108494,108508,108514,108516,108520,108592,108640,108668,108736,108792,109040,109536,109680,109694,109792,109820,110016,110072,110084,110088,110096,110112,110140,110144,110200,110320,110342,110348,110360,110384,110398,110432,110460,110478,110492,110520,110532,110536,110544,110558,110658,110686,110714,110722,110724,110728,110736,110750,110752,110780,110796,110834,110836,110850,110852,110856,110864,110878,110880,110908,110912,110968,110982,111e3,111054,111074,111076,111080,111108,111112,111120,111134,111136,111164,111168,111224,111344,111372,111422,111456,111516,111554,111556,111560,111568,111590,111632,111646,111648,111676,111680,111736,111856,112096,112152,112224,112252,112320,112440,112514,112516,112520,112528,112542,112544,112588,112686,112718,112732,112782,112796,112824,112834,112836,112840,112848,112870,112890,112910,112924,112952,113008,113022,113026,113028,113032,113040,113054,113056,113100,113138,113140,113166,113180,113208,113264,113278,113376,113404,113416,113424,113440,113468,113472,113560,113614,113634,113636,113640,113686,113702,113708,113734,113740,113752,113778,113780,113798,113804,113816,113840,113854,113870,113890,113892,113896,113926,113932,113944,113968,113982,114016,114044,114076,114114,114116,114120,114128,114150,114170,114194,114196,114210,114212,114216,114242,114244,114248,114256,114270,114278,114306,114308,114312,114320,114334,114336,114364,114380,114420,114458,114478,114482,114484,114510,114524,114530,114532,114536,114842,114866,114868,114970,114994,114996,115042,115044,115048,115062,115130,115226,115250,115252,115278,115292,115298,115300,115304,115318,115342,115394,115396,115400,115408,115422,115430,115436,115450,115478,115494,115514,115526,115532,115570,115572,115738,115758,115762,115764,115790,115804,115810,115812,115816,115830,115854,115868,115896,115906,115912,115920,115934,115942,115948,115962,115996,116024,116080,116094,116098,116100,116104,116112,116126,116128,116156,116166,116172,116184,116206,116210,116212,116246,116262,116268,116282,116294,116300,116312,116334,116338,116340,116358,116364,116376,116400,116414,116430,116444,116450,116452,116456,116498,116500,116514,116520,116534,116546,116548,116552,116560,116574,116582,116588,116602,116654,116694,116714,116762,116782,116786,116788,116814,116828,116834,116836,116840,116854,116878,116892,116920,116930,116936,116944,116958,116966,116972,116986,117006,117048,117104,117118,117122,117124,117136,117150,117152,117180,117190,117196,117208,117230,117234,117236,117304,117360,117374,117472,117500,117506,117508,117512,117520,117536,117564,117568,117624,117638,117644,117656,117680,117694,117710,117724,117730,117732,117736,117750,117782,117798,117804,117818,117830,117848,117874,117876,117894,117936,117950,117966,117986,117988,117992,118022,118028,118040,118064,118078,118112,118140,118172,118210,118212,118216,118224,118238,118246,118266,118306,118312,118338,118352,118366,118374,118394,118402,118404,118408,118416,118430,118432,118460,118476,118514,118516,118574,118578,118580,118606,118620,118626,118628,118632,118678,118694,118700,118730,118738,118740,118830,118834,118836,118862,118876,118882,118884,118888,118902,118926,118940,118968,118978,118980,118984,118992,119006,119014,119020,119034,119068,119096,119152,119166,119170,119172,119176,119184,119198,119200,119228,119238,119244,119256,119278,119282,119284,119324,119352,119408,119422,119520,119548,119554,119556,119560,119568,119582,119584,119612,119616,119672,119686,119692,119704,119728,119742,119758,119772,119778,119780,119784,119798,119920,119934,120032,120060,120256,120312,120324,120328,120336,120352,120384,120440,120560,120582,120588,120600,120624,120638,120672,120700,120718,120732,120760,120770,120772,120776,120784,120798,120806,120812,120870,120876,120890,120902,120908,120920,120946,120948,120966,120972,120984,121008,121022,121038,121058,121060,121064,121078,121100,121112,121136,121150,121184,121212,121244,121282,121284,121288,121296,121318,121338,121356,121368,121392,121406,121440,121468,121536,121592,121656,121730,121732,121736,121744,121758,121760,121804,121842,121844,121890,121922,121924,121928,121936,121950,121958,121978,121986,121988,121992,122e3,122014,122016,122044,122060,122098,122100,122116,122120,122128,122142,122144,122172,122176,122232,122246,122264,122318,122338,122340,122344,122414,122418,122420,122446,122460,122466,122468,122472,122510,122524,122552,122562,122564,122568,122576,122598,122618,122646,122662,122668,122694,122700,122712,122738,122740,122762,122770,122772,122786,122788,122792,123018,123026,123028,123042,123044,123048,123062,123098,123146,123154,123156,123170,123172,123176,123190,123202,123204,123208,123216,123238,123244,123258,123290,123314,123316,123402,123410,123412,123426,123428,123432,123446,123458,123464,123472,123486,123494,123500,123514,123522,123524,123528,123536,123552,123580,123590,123596,123608,123630,123634,123636,123674,123698,123700,123740,123746,123748,123752,123834,123914,123922,123924,123938,123944,123958,123970,123976,123984,123998,124006,124012,124026,124034,124036,124048,124062,124064,124092,124102,124108,124120,124142,124146,124148,124162,124164,124168,124176,124190,124192,124220,124224,124280,124294,124300,124312,124336,124350,124366,124380,124386,124388,124392,124406,124442,124462,124466,124468,124494,124508,124514,124520,124558,124572,124600,124610,124612,124616,124624,124646,124666,124694,124710,124716,124730,124742,124748,124760,124786,124788,124818,124820,124834,124836,124840,124854,124946,124948,124962,124964,124968,124982,124994,124996,125e3,125008,125022,125030,125036,125050,125058,125060,125064,125072,125086,125088,125116,125126,125132,125144,125166,125170,125172,125186,125188,125192,125200,125216,125244,125248,125304,125318,125324,125336,125360,125374,125390,125404,125410,125412,125416,125430,125444,125448,125456,125472,125504,125560,125680,125702,125708,125720,125744,125758,125792,125820,125838,125852,125880,125890,125892,125896,125904,125918,125926,125932,125978,125998,126002,126004,126030,126044,126050,126052,126056,126094,126108,126136,126146,126148,126152,126160,126182,126202,126222,126236,126264,126320,126334,126338,126340,126344,126352,126366,126368,126412,126450,126452,126486,126502,126508,126522,126534,126540,126552,126574,126578,126580,126598,126604,126616,126640,126654,126670,126684,126690,126692,126696,126738,126754,126756,126760,126774,126786,126788,126792,126800,126814,126822,126828,126842,126894,126898,126900,126934,127126,127142,127148,127162,127178,127186,127188,127254,127270,127276,127290,127302,127308,127320,127342,127346,127348,127370,127378,127380,127394,127396,127400,127450,127510,127526,127532,127546,127558,127576,127598,127602,127604,127622,127628,127640,127664,127678,127694,127708,127714,127716,127720,127734,127754,127762,127764,127778,127784,127810,127812,127816,127824,127838,127846,127866,127898,127918,127922,127924,128022,128038,128044,128058,128070,128076,128088,128110,128114,128116,128134,128140,128152,128176,128190,128206,128220,128226,128228,128232,128246,128262,128268,128280,128304,128318,128352,128380,128398,128412,128440,128450,128452,128456,128464,128478,128486,128492,128506,128522,128530,128532,128546,128548,128552,128566,128578,128580,128584,128592,128606,128614,128634,128642,128644,128648,128656,128670,128672,128700,128716,128754,128756,128794,128814,128818,128820,128846,128860,128866,128868,128872,128886,128918,128934,128940,128954,128978,128980,129178,129198,129202,129204,129238,129258,129306,129326,129330,129332,129358,129372,129378,129380,129384,129398,129430,129446,129452,129466,129482,129490,129492,129562,129582,129586,129588,129614,129628,129634,129636,129640,129654,129678,129692,129720,129730,129732,129736,129744,129758,129766,129772,129814,129830,129836,129850,129862,129868,129880,129902,129906,129908,129930,129938,129940,129954,129956,129960,129974,130010]),Be.CODEWORD_TABLE=Int32Array.from([2627,1819,2622,2621,1813,1812,2729,2724,2723,2779,2774,2773,902,896,908,868,865,861,859,2511,873,871,1780,835,2493,825,2491,842,837,844,1764,1762,811,810,809,2483,807,2482,806,2480,815,814,813,812,2484,817,816,1745,1744,1742,1746,2655,2637,2635,2626,2625,2623,2628,1820,2752,2739,2737,2728,2727,2725,2730,2785,2783,2778,2777,2775,2780,787,781,747,739,736,2413,754,752,1719,692,689,681,2371,678,2369,700,697,694,703,1688,1686,642,638,2343,631,2341,627,2338,651,646,643,2345,654,652,1652,1650,1647,1654,601,599,2322,596,2321,594,2319,2317,611,610,608,606,2324,603,2323,615,614,612,1617,1616,1614,1612,616,1619,1618,2575,2538,2536,905,901,898,909,2509,2507,2504,870,867,864,860,2512,875,872,1781,2490,2489,2487,2485,1748,836,834,832,830,2494,827,2492,843,841,839,845,1765,1763,2701,2676,2674,2653,2648,2656,2634,2633,2631,2629,1821,2638,2636,2770,2763,2761,2750,2745,2753,2736,2735,2733,2731,1848,2740,2738,2786,2784,591,588,576,569,566,2296,1590,537,534,526,2276,522,2274,545,542,539,548,1572,1570,481,2245,466,2242,462,2239,492,485,482,2249,496,494,1534,1531,1528,1538,413,2196,406,2191,2188,425,419,2202,415,2199,432,430,427,1472,1467,1464,433,1476,1474,368,367,2160,365,2159,362,2157,2155,2152,378,377,375,2166,372,2165,369,2162,383,381,379,2168,1419,1418,1416,1414,385,1411,384,1423,1422,1420,1424,2461,802,2441,2439,790,786,783,794,2409,2406,2403,750,742,738,2414,756,753,1720,2367,2365,2362,2359,1663,693,691,684,2373,680,2370,702,699,696,704,1690,1687,2337,2336,2334,2332,1624,2329,1622,640,637,2344,634,2342,630,2340,650,648,645,2346,655,653,1653,1651,1649,1655,2612,2597,2595,2571,2568,2565,2576,2534,2529,2526,1787,2540,2537,907,904,900,910,2503,2502,2500,2498,1768,2495,1767,2510,2508,2506,869,866,863,2513,876,874,1782,2720,2713,2711,2697,2694,2691,2702,2672,2670,2664,1828,2678,2675,2647,2646,2644,2642,1823,2639,1822,2654,2652,2650,2657,2771,1855,2765,2762,1850,1849,2751,2749,2747,2754,353,2148,344,342,336,2142,332,2140,345,1375,1373,306,2130,299,2128,295,2125,319,314,311,2132,1354,1352,1349,1356,262,257,2101,253,2096,2093,274,273,267,2107,263,2104,280,278,275,1316,1311,1308,1320,1318,2052,202,2050,2044,2040,219,2063,212,2060,208,2055,224,221,2066,1260,1258,1252,231,1248,229,1266,1264,1261,1268,155,1998,153,1996,1994,1991,1988,165,164,2007,162,2006,159,2003,2e3,172,171,169,2012,166,2010,1186,1184,1182,1179,175,1176,173,1192,1191,1189,1187,176,1194,1193,2313,2307,2305,592,589,2294,2292,2289,578,572,568,2297,580,1591,2272,2267,2264,1547,538,536,529,2278,525,2275,547,544,541,1574,1571,2237,2235,2229,1493,2225,1489,478,2247,470,2244,465,2241,493,488,484,2250,498,495,1536,1533,1530,1539,2187,2186,2184,2182,1432,2179,1430,2176,1427,414,412,2197,409,2195,405,2193,2190,426,424,421,2203,418,2201,431,429,1473,1471,1469,1466,434,1477,1475,2478,2472,2470,2459,2457,2454,2462,803,2437,2432,2429,1726,2443,2440,792,789,785,2401,2399,2393,1702,2389,1699,2411,2408,2405,745,741,2415,758,755,1721,2358,2357,2355,2353,1661,2350,1660,2347,1657,2368,2366,2364,2361,1666,690,687,2374,683,2372,701,698,705,1691,1689,2619,2617,2610,2608,2605,2613,2593,2588,2585,1803,2599,2596,2563,2561,2555,1797,2551,1795,2573,2570,2567,2577,2525,2524,2522,2520,1786,2517,1785,2514,1783,2535,2533,2531,2528,1788,2541,2539,906,903,911,2721,1844,2715,2712,1838,1836,2699,2696,2693,2703,1827,1826,1824,2673,2671,2669,2666,1829,2679,2677,1858,1857,2772,1854,1853,1851,1856,2766,2764,143,1987,139,1986,135,133,131,1984,128,1983,125,1981,138,137,136,1985,1133,1132,1130,112,110,1974,107,1973,104,1971,1969,122,121,119,117,1977,114,1976,124,1115,1114,1112,1110,1117,1116,84,83,1953,81,1952,78,1950,1948,1945,94,93,91,1959,88,1958,85,1955,99,97,95,1961,1086,1085,1083,1081,1078,100,1090,1089,1087,1091,49,47,1917,44,1915,1913,1910,1907,59,1926,56,1925,53,1922,1919,66,64,1931,61,1929,1042,1040,1038,71,1035,70,1032,68,1048,1047,1045,1043,1050,1049,12,10,1869,1867,1864,1861,21,1880,19,1877,1874,1871,28,1888,25,1886,22,1883,982,980,977,974,32,30,991,989,987,984,34,995,994,992,2151,2150,2147,2146,2144,356,355,354,2149,2139,2138,2136,2134,1359,343,341,338,2143,335,2141,348,347,346,1376,1374,2124,2123,2121,2119,1326,2116,1324,310,308,305,2131,302,2129,298,2127,320,318,316,313,2133,322,321,1355,1353,1351,1357,2092,2091,2089,2087,1276,2084,1274,2081,1271,259,2102,256,2100,252,2098,2095,272,269,2108,266,2106,281,279,277,1317,1315,1313,1310,282,1321,1319,2039,2037,2035,2032,1203,2029,1200,1197,207,2053,205,2051,201,2049,2046,2043,220,218,2064,215,2062,211,2059,228,226,223,2069,1259,1257,1254,232,1251,230,1267,1265,1263,2316,2315,2312,2311,2309,2314,2304,2303,2301,2299,1593,2308,2306,590,2288,2287,2285,2283,1578,2280,1577,2295,2293,2291,579,577,574,571,2298,582,581,1592,2263,2262,2260,2258,1545,2255,1544,2252,1541,2273,2271,2269,2266,1550,535,532,2279,528,2277,546,543,549,1575,1573,2224,2222,2220,1486,2217,1485,2214,1482,1479,2238,2236,2234,2231,1496,2228,1492,480,477,2248,473,2246,469,2243,490,487,2251,497,1537,1535,1532,2477,2476,2474,2479,2469,2468,2466,2464,1730,2473,2471,2453,2452,2450,2448,1729,2445,1728,2460,2458,2456,2463,805,804,2428,2427,2425,2423,1725,2420,1724,2417,1722,2438,2436,2434,2431,1727,2444,2442,793,791,788,795,2388,2386,2384,1697,2381,1696,2378,1694,1692,2402,2400,2398,2395,1703,2392,1701,2412,2410,2407,751,748,744,2416,759,757,1807,2620,2618,1806,1805,2611,2609,2607,2614,1802,1801,1799,2594,2592,2590,2587,1804,2600,2598,1794,1793,1791,1789,2564,2562,2560,2557,1798,2554,1796,2574,2572,2569,2578,1847,1846,2722,1843,1842,1840,1845,2716,2714,1835,1834,1832,1830,1839,1837,2700,2698,2695,2704,1817,1811,1810,897,862,1777,829,826,838,1760,1758,808,2481,1741,1740,1738,1743,2624,1818,2726,2776,782,740,737,1715,686,679,695,1682,1680,639,628,2339,647,644,1645,1643,1640,1648,602,600,597,595,2320,593,2318,609,607,604,1611,1610,1608,1606,613,1615,1613,2328,926,924,892,886,899,857,850,2505,1778,824,823,821,819,2488,818,2486,833,831,828,840,1761,1759,2649,2632,2630,2746,2734,2732,2782,2781,570,567,1587,531,527,523,540,1566,1564,476,467,463,2240,486,483,1524,1521,1518,1529,411,403,2192,399,2189,423,416,1462,1457,1454,428,1468,1465,2210,366,363,2158,360,2156,357,2153,376,373,370,2163,1410,1409,1407,1405,382,1402,380,1417,1415,1412,1421,2175,2174,777,774,771,784,732,725,722,2404,743,1716,676,674,668,2363,665,2360,685,1684,1681,626,624,622,2335,620,2333,617,2330,641,635,649,1646,1644,1642,2566,928,925,2530,2527,894,891,888,2501,2499,2496,858,856,854,851,1779,2692,2668,2665,2645,2643,2640,2651,2768,2759,2757,2744,2743,2741,2748,352,1382,340,337,333,1371,1369,307,300,296,2126,315,312,1347,1342,1350,261,258,250,2097,246,2094,271,268,264,1306,1301,1298,276,1312,1309,2115,203,2048,195,2045,191,2041,213,209,2056,1246,1244,1238,225,1234,222,1256,1253,1249,1262,2080,2079,154,1997,150,1995,147,1992,1989,163,160,2004,156,2001,1175,1174,1172,1170,1167,170,1164,167,1185,1183,1180,1177,174,1190,1188,2025,2024,2022,587,586,564,559,556,2290,573,1588,520,518,512,2268,508,2265,530,1568,1565,461,457,2233,450,2230,446,2226,479,471,489,1526,1523,1520,397,395,2185,392,2183,389,2180,2177,410,2194,402,422,1463,1461,1459,1456,1470,2455,799,2433,2430,779,776,773,2397,2394,2390,734,728,724,746,1717,2356,2354,2351,2348,1658,677,675,673,670,667,688,1685,1683,2606,2589,2586,2559,2556,2552,927,2523,2521,2518,2515,1784,2532,895,893,890,2718,2709,2707,2689,2687,2684,2663,2662,2660,2658,1825,2667,2769,1852,2760,2758,142,141,1139,1138,134,132,129,126,1982,1129,1128,1126,1131,113,111,108,105,1972,101,1970,120,118,115,1109,1108,1106,1104,123,1113,1111,82,79,1951,75,1949,72,1946,92,89,86,1956,1077,1076,1074,1072,98,1069,96,1084,1082,1079,1088,1968,1967,48,45,1916,42,1914,39,1911,1908,60,57,54,1923,50,1920,1031,1030,1028,1026,67,1023,65,1020,62,1041,1039,1036,1033,69,1046,1044,1944,1943,1941,11,9,1868,7,1865,1862,1859,20,1878,16,1875,13,1872,970,968,966,963,29,960,26,23,983,981,978,975,33,971,31,990,988,985,1906,1904,1902,993,351,2145,1383,331,330,328,326,2137,323,2135,339,1372,1370,294,293,291,289,2122,286,2120,283,2117,309,303,317,1348,1346,1344,245,244,242,2090,239,2088,236,2085,2082,260,2099,249,270,1307,1305,1303,1300,1314,189,2038,186,2036,183,2033,2030,2026,206,198,2047,194,216,1247,1245,1243,1240,227,1237,1255,2310,2302,2300,2286,2284,2281,565,563,561,558,575,1589,2261,2259,2256,2253,1542,521,519,517,514,2270,511,533,1569,1567,2223,2221,2218,2215,1483,2211,1480,459,456,453,2232,449,474,491,1527,1525,1522,2475,2467,2465,2451,2449,2446,801,800,2426,2424,2421,2418,1723,2435,780,778,775,2387,2385,2382,2379,1695,2375,1693,2396,735,733,730,727,749,1718,2616,2615,2604,2603,2601,2584,2583,2581,2579,1800,2591,2550,2549,2547,2545,1792,2542,1790,2558,929,2719,1841,2710,2708,1833,1831,2690,2688,2686,1815,1809,1808,1774,1756,1754,1737,1736,1734,1739,1816,1711,1676,1674,633,629,1638,1636,1633,1641,598,1605,1604,1602,1600,605,1609,1607,2327,887,853,1775,822,820,1757,1755,1584,524,1560,1558,468,464,1514,1511,1508,1519,408,404,400,1452,1447,1444,417,1458,1455,2208,364,361,358,2154,1401,1400,1398,1396,374,1393,371,1408,1406,1403,1413,2173,2172,772,726,723,1712,672,669,666,682,1678,1675,625,623,621,618,2331,636,632,1639,1637,1635,920,918,884,880,889,849,848,847,846,2497,855,852,1776,2641,2742,2787,1380,334,1367,1365,301,297,1340,1338,1335,1343,255,251,247,1296,1291,1288,265,1302,1299,2113,204,196,192,2042,1232,1230,1224,214,1220,210,1242,1239,1235,1250,2077,2075,151,148,1993,144,1990,1163,1162,1160,1158,1155,161,1152,157,1173,1171,1168,1165,168,1181,1178,2021,2020,2018,2023,585,560,557,1585,516,509,1562,1559,458,447,2227,472,1516,1513,1510,398,396,393,390,2181,386,2178,407,1453,1451,1449,1446,420,1460,2209,769,764,720,712,2391,729,1713,664,663,661,659,2352,656,2349,671,1679,1677,2553,922,919,2519,2516,885,883,881,2685,2661,2659,2767,2756,2755,140,1137,1136,130,127,1125,1124,1122,1127,109,106,102,1103,1102,1100,1098,116,1107,1105,1980,80,76,73,1947,1068,1067,1065,1063,90,1060,87,1075,1073,1070,1080,1966,1965,46,43,40,1912,36,1909,1019,1018,1016,1014,58,1011,55,1008,51,1029,1027,1024,1021,63,1037,1034,1940,1939,1937,1942,8,1866,4,1863,1,1860,956,954,952,949,946,17,14,969,967,964,961,27,957,24,979,976,972,1901,1900,1898,1896,986,1905,1903,350,349,1381,329,327,324,1368,1366,292,290,287,284,2118,304,1341,1339,1337,1345,243,240,237,2086,233,2083,254,1297,1295,1293,1290,1304,2114,190,187,184,2034,180,2031,177,2027,199,1233,1231,1229,1226,217,1223,1241,2078,2076,584,555,554,552,550,2282,562,1586,507,506,504,502,2257,499,2254,515,1563,1561,445,443,441,2219,438,2216,435,2212,460,454,475,1517,1515,1512,2447,798,797,2422,2419,770,768,766,2383,2380,2376,721,719,717,714,731,1714,2602,2582,2580,2548,2546,2543,923,921,2717,2706,2705,2683,2682,2680,1771,1752,1750,1733,1732,1731,1735,1814,1707,1670,1668,1631,1629,1626,1634,1599,1598,1596,1594,1603,1601,2326,1772,1753,1751,1581,1554,1552,1504,1501,1498,1509,1442,1437,1434,401,1448,1445,2206,1392,1391,1389,1387,1384,359,1399,1397,1394,1404,2171,2170,1708,1672,1669,619,1632,1630,1628,1773,1378,1363,1361,1333,1328,1336,1286,1281,1278,248,1292,1289,2111,1218,1216,1210,197,1206,193,1228,1225,1221,1236,2073,2071,1151,1150,1148,1146,152,1143,149,1140,145,1161,1159,1156,1153,158,1169,1166,2017,2016,2014,2019,1582,510,1556,1553,452,448,1506,1500,394,391,387,1443,1441,1439,1436,1450,2207,765,716,713,1709,662,660,657,1673,1671,916,914,879,878,877,882,1135,1134,1121,1120,1118,1123,1097,1096,1094,1092,103,1101,1099,1979,1059,1058,1056,1054,77,1051,74,1066,1064,1061,1071,1964,1963,1007,1006,1004,1002,999,41,996,37,1017,1015,1012,1009,52,1025,1022,1936,1935,1933,1938,942,940,938,935,932,5,2,955,953,950,947,18,943,15,965,962,958,1895,1894,1892,1890,973,1899,1897,1379,325,1364,1362,288,285,1334,1332,1330,241,238,234,1287,1285,1283,1280,1294,2112,188,185,181,178,2028,1219,1217,1215,1212,200,1209,1227,2074,2072,583,553,551,1583,505,503,500,513,1557,1555,444,442,439,436,2213,455,451,1507,1505,1502,796,763,762,760,767,711,710,708,706,2377,718,715,1710,2544,917,915,2681,1627,1597,1595,2325,1769,1749,1747,1499,1438,1435,2204,1390,1388,1385,1395,2169,2167,1704,1665,1662,1625,1623,1620,1770,1329,1282,1279,2109,1214,1207,1222,2068,2065,1149,1147,1144,1141,146,1157,1154,2013,2011,2008,2015,1579,1549,1546,1495,1487,1433,1431,1428,1425,388,1440,2205,1705,658,1667,1664,1119,1095,1093,1978,1057,1055,1052,1062,1962,1960,1005,1003,1e3,997,38,1013,1010,1932,1930,1927,1934,941,939,936,933,6,930,3,951,948,944,1889,1887,1884,1881,959,1893,1891,35,1377,1360,1358,1327,1325,1322,1331,1277,1275,1272,1269,235,1284,2110,1205,1204,1201,1198,182,1195,179,1213,2070,2067,1580,501,1551,1548,440,437,1497,1494,1490,1503,761,709,707,1706,913,912,2198,1386,2164,2161,1621,1766,2103,1208,2058,2054,1145,1142,2005,2002,1999,2009,1488,1429,1426,2200,1698,1659,1656,1975,1053,1957,1954,1001,998,1924,1921,1918,1928,937,934,931,1879,1876,1873,1870,945,1885,1882,1323,1273,1270,2105,1202,1199,1196,1211,2061,2057,1576,1543,1540,1484,1481,1478,1491,1700]);class id{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class We{static detectMultiple(e,n,o){let s=e.getBlackMatrix(),a=We.detect(o,s);return a.length||(s=s.clone(),s.rotate180(),a=We.detect(o,s)),new id(s,a)}static detect(e,n){const o=new Array;let s=0,a=0,l=!1;for(;s<n.getHeight();){const u=We.findVertices(n,s,a);if(u[0]==null&&u[3]==null){if(!l)break;l=!1,a=0;for(const h of o)h[1]!=null&&(s=Math.trunc(Math.max(s,h[1].getY()))),h[3]!=null&&(s=Math.max(s,Math.trunc(h[3].getY())));s+=We.ROW_STEP;continue}if(l=!0,o.push(u),!e)break;u[2]!=null?(a=Math.trunc(u[2].getX()),s=Math.trunc(u[2].getY())):(a=Math.trunc(u[4].getX()),s=Math.trunc(u[4].getY()))}return o}static findVertices(e,n,o){const s=e.getHeight(),a=e.getWidth(),l=new Array(8);return We.copyToResult(l,We.findRowsWithPattern(e,s,a,n,o,We.START_PATTERN),We.INDEXES_START_PATTERN),l[4]!=null&&(o=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),We.copyToResult(l,We.findRowsWithPattern(e,s,a,n,o,We.STOP_PATTERN),We.INDEXES_STOP_PATTERN),l}static copyToResult(e,n,o){for(let s=0;s<o.length;s++)e[o[s]]=n[s]}static findRowsWithPattern(e,n,o,s,a,l){const u=new Array(4);let h=!1;const p=new Int32Array(l.length);for(;s<n;s+=We.ROW_STEP){let b=We.findGuardPattern(e,a,s,o,!1,l,p);if(b!=null){for(;s>0;){const I=We.findGuardPattern(e,a,--s,o,!1,l,p);if(I!=null)b=I;else{s++;break}}u[0]=new be(b[0],s),u[1]=new be(b[1],s),h=!0;break}}let y=s+1;if(h){let b=0,I=Int32Array.from([Math.trunc(u[0].getX()),Math.trunc(u[1].getX())]);for(;y<n;y++){const R=We.findGuardPattern(e,I[0],y,o,!1,l,p);if(R!=null&&Math.abs(I[0]-R[0])<We.MAX_PATTERN_DRIFT&&Math.abs(I[1]-R[1])<We.MAX_PATTERN_DRIFT)I=R,b=0;else{if(b>We.SKIPPED_ROW_COUNT_MAX)break;b++}}y-=b+1,u[2]=new be(I[0],y),u[3]=new be(I[1],y)}return y-s<We.BARCODE_MIN_HEIGHT&&$.fill(u,null),u}static findGuardPattern(e,n,o,s,a,l,u){$.fillWithin(u,0,u.length,0);let h=n,p=0;for(;e.get(h,o)&&h>0&&p++<We.MAX_PIXEL_DRIFT;)h--;let y=h,b=0,I=l.length;for(let R=a;y<s;y++)if(e.get(y,o)!==R)u[b]++;else{if(b===I-1){if(We.patternMatchVariance(u,l,We.MAX_INDIVIDUAL_VARIANCE)<We.MAX_AVG_VARIANCE)return new Int32Array([h,y]);h+=u[0]+u[1],P.arraycopy(u,2,u,0,b-1),u[b-1]=0,u[b]=0,b--}else b++;u[b]=1,R=!R}return b===I-1&&We.patternMatchVariance(u,l,We.MAX_INDIVIDUAL_VARIANCE)<We.MAX_AVG_VARIANCE?new Int32Array([h,y-1]):null}static patternMatchVariance(e,n,o){let s=e.length,a=0,l=0;for(let p=0;p<s;p++)a+=e[p],l+=n[p];if(a<l)return 1/0;let u=a/l;o*=u;let h=0;for(let p=0;p<s;p++){let y=e[p],b=n[p]*u,I=y>b?y-b:b-y;if(I>o)return 1/0;h+=I}return h/a}}We.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),We.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),We.MAX_AVG_VARIANCE=.42,We.MAX_INDIVIDUAL_VARIANCE=.8,We.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),We.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),We.MAX_PIXEL_DRIFT=3,We.MAX_PATTERN_DRIFT=5,We.SKIPPED_ROW_COUNT_MAX=25,We.ROW_STEP=5,We.BARCODE_MIN_HEIGHT=10;class $t{constructor(e,n){if(n.length===0)throw new A;this.field=e;let o=n.length;if(o>1&&n[0]===0){let s=1;for(;s<o&&n[s]===0;)s++;s===o?this.coefficients=new Int32Array([0]):(this.coefficients=new Int32Array(o-s),P.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);if(e===1){let s=0;for(let a of this.coefficients)s=this.field.add(s,a);return s}let n=this.coefficients[0],o=this.coefficients.length;for(let s=1;s<o;s++)n=this.field.add(this.field.multiply(e,n),this.coefficients[s]);return n}add(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,o=e.coefficients;if(n.length>o.length){let l=n;n=o,o=l}let s=new Int32Array(o.length),a=o.length-n.length;P.arraycopy(o,0,s,0,a);for(let l=a;l<o.length;l++)s[l]=this.field.add(n[l-a],o[l]);return new $t(this.field,s)}subtract(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");return e.isZero()?this:this.add(e.negative())}multiply(e){return e instanceof $t?this.multiplyOther(e):this.multiplyScalar(e)}multiplyOther(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");if(this.isZero()||e.isZero())return new $t(this.field,new Int32Array([0]));let n=this.coefficients,o=n.length,s=e.coefficients,a=s.length,l=new Int32Array(o+a-1);for(let u=0;u<o;u++){let h=n[u];for(let p=0;p<a;p++)l[u+p]=this.field.add(l[u+p],this.field.multiply(h,s[p]))}return new $t(this.field,l)}negative(){let e=this.coefficients.length,n=new Int32Array(e);for(let o=0;o<e;o++)n[o]=this.field.subtract(0,this.coefficients[o]);return new $t(this.field,n)}multiplyScalar(e){if(e===0)return new $t(this.field,new Int32Array([0]));if(e===1)return this;let n=this.coefficients.length,o=new Int32Array(n);for(let s=0;s<n;s++)o[s]=this.field.multiply(this.coefficients[s],e);return new $t(this.field,o)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return new $t(this.field,new Int32Array([0]));let o=this.coefficients.length,s=new Int32Array(o+e);for(let a=0;a<o;a++)s[a]=this.field.multiply(this.coefficients[a],n);return new $t(this.field,s)}toString(){let e=new fe;for(let n=this.getDegree();n>=0;n--){let o=this.getCoefficient(n);o!==0&&(o<0?(e.append(" - "),o=-o):e.length()>0&&e.append(" + "),(n===0||o!==1)&&e.append(o),n!==0&&(n===1?e.append("x"):(e.append("x^"),e.append(n))))}return e.toString()}}class sd{add(e,n){return(e+n)%this.modulus}subtract(e,n){return(this.modulus+e-n)%this.modulus}exp(e){return this.expTable[e]}log(e){if(e===0)throw new A;return this.logTable[e]}inverse(e){if(e===0)throw new ye;return this.expTable[this.modulus-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.modulus-1)]}getSize(){return this.modulus}equals(e){return e===this}}class Qo extends sd{constructor(e,n){super(),this.modulus=e,this.expTable=new Int32Array(e),this.logTable=new Int32Array(e);let o=1;for(let s=0;s<e;s++)this.expTable[s]=o,o=o*n%e;for(let s=0;s<e-1;s++)this.logTable[this.expTable[s]]=s;this.zero=new $t(this,new Int32Array([0])),this.one=new $t(this,new Int32Array([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;let o=new Int32Array(e+1);return o[0]=n,new $t(this,o)}}Qo.PDF417_GF=new Qo(Be.NUMBER_OF_CODEWORDS,3);class ds{constructor(){this.field=Qo.PDF417_GF}decode(e,n,o){let s=new $t(this.field,e),a=new Int32Array(n),l=!1;for(let U=n;U>0;U--){let V=s.evaluateAt(this.field.exp(U));a[n-U]=V,V!==0&&(l=!0)}if(!l)return 0;let u=this.field.getOne();if(o!=null)for(const U of o){let V=this.field.exp(e.length-1-U),H=new $t(this.field,new Int32Array([this.field.subtract(0,V),1]));u=u.multiply(H)}let h=new $t(this.field,a),p=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),y=p[0],b=p[1],I=this.findErrorLocations(y),R=this.findErrorMagnitudes(b,y,I);for(let U=0;U<I.length;U++){let V=e.length-1-this.field.log(I[U]);if(V<0)throw T.getChecksumInstance();e[V]=this.field.subtract(e[V],R[U])}return I.length}runEuclideanAlgorithm(e,n,o){if(e.getDegree()<n.getDegree()){let I=e;e=n,n=I}let s=e,a=n,l=this.field.getZero(),u=this.field.getOne();for(;a.getDegree()>=Math.round(o/2);){let I=s,R=l;if(s=a,l=u,s.isZero())throw T.getChecksumInstance();a=I;let U=this.field.getZero(),V=s.getCoefficient(s.getDegree()),H=this.field.inverse(V);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let Q=a.getDegree()-s.getDegree(),he=this.field.multiply(a.getCoefficient(a.getDegree()),H);U=U.add(this.field.buildMonomial(Q,he)),a=a.subtract(s.multiplyByMonomial(Q,he))}u=U.multiply(l).subtract(R).negative()}let h=u.getCoefficient(0);if(h===0)throw T.getChecksumInstance();let p=this.field.inverse(h),y=u.multiply(p),b=a.multiply(p);return[y,b]}findErrorLocations(e){let n=e.getDegree(),o=new Int32Array(n),s=0;for(let a=1;a<this.field.getSize()&&s<n;a++)e.evaluateAt(a)===0&&(o[s]=this.field.inverse(a),s++);if(s!==n)throw T.getChecksumInstance();return o}findErrorMagnitudes(e,n,o){let s=n.getDegree(),a=new Int32Array(s);for(let p=1;p<=s;p++)a[s-p]=this.field.multiply(p,n.getCoefficient(p));let l=new $t(this.field,a),u=o.length,h=new Int32Array(u);for(let p=0;p<u;p++){let y=this.field.inverse(o[p]),b=this.field.subtract(0,e.evaluateAt(y)),I=this.field.inverse(l.evaluateAt(y));h[p]=this.field.multiply(b,I)}return h}}class ar{constructor(e,n,o,s,a){e instanceof ar?this.constructor_2(e):this.constructor_1(e,n,o,s,a)}constructor_1(e,n,o,s,a){const l=n==null||o==null,u=s==null||a==null;if(l&&u)throw new q;l?(n=new be(0,s.getY()),o=new be(0,a.getY())):u&&(s=new be(e.getWidth()-1,n.getY()),a=new be(e.getWidth()-1,o.getY())),this.image=e,this.topLeft=n,this.bottomLeft=o,this.topRight=s,this.bottomRight=a,this.minX=Math.trunc(Math.min(n.getX(),o.getX())),this.maxX=Math.trunc(Math.max(s.getX(),a.getX())),this.minY=Math.trunc(Math.min(n.getY(),s.getY())),this.maxY=Math.trunc(Math.max(o.getY(),a.getY()))}constructor_2(e){this.image=e.image,this.topLeft=e.getTopLeft(),this.bottomLeft=e.getBottomLeft(),this.topRight=e.getTopRight(),this.bottomRight=e.getBottomRight(),this.minX=e.getMinX(),this.maxX=e.getMaxX(),this.minY=e.getMinY(),this.maxY=e.getMaxY()}static merge(e,n){return e==null?n:n==null?e:new ar(e.image,e.topLeft,e.bottomLeft,n.topRight,n.bottomRight)}addMissingRows(e,n,o){let s=this.topLeft,a=this.bottomLeft,l=this.topRight,u=this.bottomRight;if(e>0){let h=o?this.topLeft:this.topRight,p=Math.trunc(h.getY()-e);p<0&&(p=0);let y=new be(h.getX(),p);o?s=y:l=y}if(n>0){let h=o?this.bottomLeft:this.bottomRight,p=Math.trunc(h.getY()+n);p>=this.image.getHeight()&&(p=this.image.getHeight()-1);let y=new be(h.getX(),p);o?a=y:u=y}return new ar(this.image,s,a,l,u)}getMinX(){return this.minX}getMaxX(){return this.maxX}getMinY(){return this.minY}getMaxY(){return this.maxY}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}getBottomLeft(){return this.bottomLeft}getBottomRight(){return this.bottomRight}}class ad{constructor(e,n,o,s){this.columnCount=e,this.errorCorrectionLevel=s,this.rowCountUpperPart=n,this.rowCountLowerPart=o,this.rowCount=n+o}getColumnCount(){return this.columnCount}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getRowCount(){return this.rowCount}getRowCountUpperPart(){return this.rowCountUpperPart}getRowCountLowerPart(){return this.rowCountLowerPart}}class Pr{constructor(){this.buffer=""}static form(e,n){let o=-1;function s(l,u,h,p,y,b){if(l==="%%")return"%";if(n[++o]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(b){case"s":R=n[o];break;case"c":R=n[o][0];break;case"f":R=parseFloat(n[o]).toFixed(l);break;case"p":R=parseFloat(n[o]).toPrecision(l);break;case"e":R=parseFloat(n[o]).toExponential(l);break;case"x":R=parseInt(n[o]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[o],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let U=parseInt(h),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<U;)R=u!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=Pr.form(e,n)}toString(){return this.buffer}}class Br{constructor(e){this.boundingBox=new ar(e),this.codewords=new Array(e.getMaxY()-e.getMinY()+1)}getCodewordNearby(e){let n=this.getCodeword(e);if(n!=null)return n;for(let o=1;o<Br.MAX_NEARBY_DISTANCE;o++){let s=this.imageRowToCodewordIndex(e)-o;if(s>=0&&(n=this.codewords[s],n!=null)||(s=this.imageRowToCodewordIndex(e)+o,s<this.codewords.length&&(n=this.codewords[s],n!=null)))return n}return null}imageRowToCodewordIndex(e){return e-this.boundingBox.getMinY()}setCodeword(e,n){this.codewords[this.imageRowToCodewordIndex(e)]=n}getCodeword(e){return this.codewords[this.imageRowToCodewordIndex(e)]}getBoundingBox(){return this.boundingBox}getCodewords(){return this.codewords}toString(){const e=new Pr;let n=0;for(const o of this.codewords){if(o==null){e.format("%3d: | %n",n++);continue}e.format("%3d: %3d|%3d%n",n++,o.getRowNumber(),o.getValue())}return e.toString()}}Br.MAX_NEARBY_DISTANCE=5;class Lr{constructor(){this.values=new Map}setValue(e){e=Math.trunc(e);let n=this.values.get(e);n==null&&(n=0),n++,this.values.set(e,n)}getValue(){let e=-1,n=new Array;for(const[o,s]of this.values.entries()){const a={getKey:()=>o,getValue:()=>s};a.getValue()>e?(e=a.getValue(),n=[],n.push(a.getKey())):a.getValue()===e&&n.push(a.getKey())}return Be.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class fs extends Br{constructor(e,n){super(e),this._isLeft=n}setRowNumbers(){for(let e of this.getCodewords())e?.setRowNumberAsRowIndicatorColumn()}adjustCompleteIndicatorColumnRowNumbers(e){let n=this.getCodewords();this.setRowNumbers(),this.removeIncorrectCodewords(n,e);let o=this.getBoundingBox(),s=this._isLeft?o.getTopLeft():o.getTopRight(),a=this._isLeft?o.getBottomLeft():o.getBottomRight(),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),u=this.imageRowToCodewordIndex(Math.trunc(a.getY())),h=-1,p=1,y=0;for(let b=l;b<u;b++){if(n[b]==null)continue;let I=n[b],R=I.getRowNumber()-h;if(R===0)y++;else if(R===1)p=Math.max(p,y),y=1,h=I.getRowNumber();else if(R<0||I.getRowNumber()>=e.getRowCount()||R>b)n[b]=null;else{let U;p>2?U=(p-2)*R:U=R;let V=U>=b;for(let H=1;H<=U&&!V;H++)V=n[b-H]!=null;V?n[b]=null:(h=I.getRowNumber(),y=1)}}}getRowHeights(){let e=this.getBarcodeMetadata();if(e==null)return null;this.adjustIncompleteIndicatorColumnRowNumbers(e);let n=new Int32Array(e.getRowCount());for(let o of this.getCodewords())if(o!=null){let s=o.getRowNumber();if(s>=n.length)continue;n[s]++}return n}adjustIncompleteIndicatorColumnRowNumbers(e){let n=this.getBoundingBox(),o=this._isLeft?n.getTopLeft():n.getTopRight(),s=this._isLeft?n.getBottomLeft():n.getBottomRight(),a=this.imageRowToCodewordIndex(Math.trunc(o.getY())),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),u=this.getCodewords(),h=-1;for(let p=a;p<l;p++){if(u[p]==null)continue;let y=u[p];y.setRowNumberAsRowIndicatorColumn();let b=y.getRowNumber()-h;b===0||(b===1?h=y.getRowNumber():y.getRowNumber()>=e.getRowCount()?u[p]=null:h=y.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Lr,o=new Lr,s=new Lr,a=new Lr;for(let u of e){if(u==null)continue;u.setRowNumberAsRowIndicatorColumn();let h=u.getValue()%30,p=u.getRowNumber();switch(this._isLeft||(p+=2),p%3){case 0:o.setValue(h*3+1);break;case 1:a.setValue(h/3),s.setValue(h%3);break;case 2:n.setValue(h+1);break}}if(n.getValue().length===0||o.getValue().length===0||s.getValue().length===0||a.getValue().length===0||n.getValue()[0]<1||o.getValue()[0]+s.getValue()[0]<Be.MIN_ROWS_IN_BARCODE||o.getValue()[0]+s.getValue()[0]>Be.MAX_ROWS_IN_BARCODE)return null;let l=new ad(n.getValue()[0],o.getValue()[0],s.getValue()[0],a.getValue()[0]);return this.removeIncorrectCodewords(e,l),l}removeIncorrectCodewords(e,n){for(let o=0;o<e.length;o++){let s=e[o];if(e[o]==null)continue;let a=s.getValue()%30,l=s.getRowNumber();if(l>n.getRowCount()){e[o]=null;continue}switch(this._isLeft||(l+=2),l%3){case 0:a*3+1!==n.getRowCountUpperPart()&&(e[o]=null);break;case 1:(Math.trunc(a/3)!==n.getErrorCorrectionLevel()||a%3!==n.getRowCountLowerPart())&&(e[o]=null);break;case 2:a+1!==n.getColumnCount()&&(e[o]=null);break}}}isLeft(){return this._isLeft}toString(){return"IsLeft: "+this._isLeft+`
68
+ `+super.toString()}}class Fr{constructor(e,n){this.ADJUST_ROW_NUMBER_SKIP=2,this.barcodeMetadata=e,this.barcodeColumnCount=e.getColumnCount(),this.boundingBox=n,this.detectionResultColumns=new Array(this.barcodeColumnCount+2)}getDetectionResultColumns(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]),this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);let e=Be.MAX_CODEWORDS_IN_BARCODE,n;do n=e,e=this.adjustRowNumbersAndGetCount();while(e>0&&e<n);return this.detectionResultColumns}adjustIndicatorColumnRowNumbers(e){e?.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata)}adjustRowNumbersAndGetCount(){let e=this.adjustRowNumbersByRow();if(e===0)return 0;for(let n=1;n<this.barcodeColumnCount+1;n++){let o=this.detectionResultColumns[n].getCodewords();for(let s=0;s<o.length;s++)o[s]!=null&&(o[s].hasValidRowNumber()||this.adjustRowNumbers(n,s,o))}return e}adjustRowNumbersByRow(){return this.adjustRowNumbersFromBothRI(),this.adjustRowNumbersFromLRI()+this.adjustRowNumbersFromRRI()}adjustRowNumbersFromBothRI(){if(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null)return;let e=this.detectionResultColumns[0].getCodewords(),n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let o=0;o<e.length;o++)if(e[o]!=null&&n[o]!=null&&e[o].getRowNumber()===n[o].getRowNumber())for(let s=1;s<=this.barcodeColumnCount;s++){let a=this.detectionResultColumns[s].getCodewords()[o];a!=null&&(a.setRowNumber(e[o].getRowNumber()),a.hasValidRowNumber()||(this.detectionResultColumns[s].getCodewords()[o]=null))}}adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null)return 0;let e=0,n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let o=0;o<n.length;o++){if(n[o]==null)continue;let s=n[o].getRowNumber(),a=0;for(let l=this.barcodeColumnCount+1;l>0&&a<this.ADJUST_ROW_NUMBER_SKIP;l--){let u=this.detectionResultColumns[l].getCodewords()[o];u!=null&&(a=Fr.adjustRowNumberIfValid(s,a,u),u.hasValidRowNumber()||e++)}}return e}adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null)return 0;let e=0,n=this.detectionResultColumns[0].getCodewords();for(let o=0;o<n.length;o++){if(n[o]==null)continue;let s=n[o].getRowNumber(),a=0;for(let l=1;l<this.barcodeColumnCount+1&&a<this.ADJUST_ROW_NUMBER_SKIP;l++){let u=this.detectionResultColumns[l].getCodewords()[o];u!=null&&(a=Fr.adjustRowNumberIfValid(s,a,u),u.hasValidRowNumber()||e++)}}return e}static adjustRowNumberIfValid(e,n,o){return o==null||o.hasValidRowNumber()||(o.isValidRowNumber(e)?(o.setRowNumber(e),n=0):++n),n}adjustRowNumbers(e,n,o){if(!this.detectionResultColumns[e-1])return;let s=o[n],a=this.detectionResultColumns[e-1].getCodewords(),l=a;this.detectionResultColumns[e+1]!=null&&(l=this.detectionResultColumns[e+1].getCodewords());let u=new Array(14);u[2]=a[n],u[3]=l[n],n>0&&(u[0]=o[n-1],u[4]=a[n-1],u[5]=l[n-1]),n>1&&(u[8]=o[n-2],u[10]=a[n-2],u[11]=l[n-2]),n<o.length-1&&(u[1]=o[n+1],u[6]=a[n+1],u[7]=l[n+1]),n<o.length-2&&(u[9]=o[n+2],u[12]=a[n+2],u[13]=l[n+2]);for(let h of u)if(Fr.adjustRowNumber(s,h))return}static adjustRowNumber(e,n){return n==null?!1:n.hasValidRowNumber()&&n.getBucket()===e.getBucket()?(e.setRowNumber(n.getRowNumber()),!0):!1}getBarcodeColumnCount(){return this.barcodeColumnCount}getBarcodeRowCount(){return this.barcodeMetadata.getRowCount()}getBarcodeECLevel(){return this.barcodeMetadata.getErrorCorrectionLevel()}setBoundingBox(e){this.boundingBox=e}getBoundingBox(){return this.boundingBox}setDetectionResultColumn(e,n){this.detectionResultColumns[e]=n}getDetectionResultColumn(e){return this.detectionResultColumns[e]}toString(){let e=this.detectionResultColumns[0];e==null&&(e=this.detectionResultColumns[this.barcodeColumnCount+1]);let n=new Pr;for(let o=0;o<e.getCodewords().length;o++){n.format("CW %3d:",o);for(let s=0;s<this.barcodeColumnCount+2;s++){if(this.detectionResultColumns[s]==null){n.format(" | ");continue}let a=this.detectionResultColumns[s].getCodewords()[o];if(a==null){n.format(" | ");continue}n.format(" %3d|%3d",a.getRowNumber(),a.getValue())}n.format("%n")}return n.toString()}}class Ur{constructor(e,n,o,s){this.rowNumber=Ur.BARCODE_ROW_UNKNOWN,this.startX=Math.trunc(e),this.endX=Math.trunc(n),this.bucket=Math.trunc(o),this.value=Math.trunc(s)}hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber)}isValidRowNumber(e){return e!==Ur.BARCODE_ROW_UNKNOWN&&this.bucket===e%3*3}setRowNumberAsRowIndicatorColumn(){this.rowNumber=Math.trunc(Math.trunc(this.value/30)*3+Math.trunc(this.bucket/3))}getWidth(){return this.endX-this.startX}getStartX(){return this.startX}getEndX(){return this.endX}getBucket(){return this.bucket}getValue(){return this.value}getRowNumber(){return this.rowNumber}setRowNumber(e){this.rowNumber=e}toString(){return this.rowNumber+"|"+this.value}}Ur.BARCODE_ROW_UNKNOWN=-1;class en{static initialize(){for(let e=0;e<Be.SYMBOL_TABLE.length;e++){let n=Be.SYMBOL_TABLE[e],o=n&1;for(let s=0;s<Be.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===o;)a+=1,n>>=1;o=n&1,en.RATIOS_TABLE[e]||(en.RATIOS_TABLE[e]=new Array(Be.BARS_IN_MODULE)),en.RATIOS_TABLE[e][Be.BARS_IN_MODULE-s-1]=Math.fround(a/Be.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=en.getDecodedCodewordValue(en.sampleBitCounts(e));return n!==-1?n:en.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=Xe.sum(e),o=new Int32Array(Be.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<Be.MODULES_IN_CODEWORD;l++){let u=n/(2*Be.MODULES_IN_CODEWORD)+l*n/Be.MODULES_IN_CODEWORD;a+e[s]<=u&&(a+=e[s],s++),o[s]++}return o}static getDecodedCodewordValue(e){let n=en.getBitValue(e);return Be.getCodeword(n)===-1?-1:n}static getBitValue(e){let n=0;for(let o=0;o<e.length;o++)for(let s=0;s<e[o];s++)n=n<<1|(o%2===0?1:0);return Math.trunc(n)}static getClosestDecodedValue(e){let n=Xe.sum(e),o=new Array(Be.BARS_IN_MODULE);if(n>1)for(let l=0;l<o.length;l++)o[l]=Math.fround(e[l]/n);let s=In.MAX_VALUE,a=-1;this.bSymbolTableReady||en.initialize();for(let l=0;l<en.RATIOS_TABLE.length;l++){let u=0,h=en.RATIOS_TABLE[l];for(let p=0;p<Be.BARS_IN_MODULE;p++){let y=Math.fround(h[p]-o[p]);if(u+=Math.fround(y*y),u>=s)break}u<s&&(s=u,a=Be.SYMBOL_TABLE[l])}return a}}en.bSymbolTableReady=!1,en.RATIOS_TABLE=new Array(Be.SYMBOL_TABLE.length).map(C=>new Array(Be.BARS_IN_MODULE));class hs{constructor(){this.segmentCount=-1,this.fileSize=-1,this.timestamp=-1,this.checksum=-1}getSegmentIndex(){return this.segmentIndex}setSegmentIndex(e){this.segmentIndex=e}getFileId(){return this.fileId}setFileId(e){this.fileId=e}getOptionalData(){return this.optionalData}setOptionalData(e){this.optionalData=e}isLastSegment(){return this.lastSegment}setLastSegment(e){this.lastSegment=e}getSegmentCount(){return this.segmentCount}setSegmentCount(e){this.segmentCount=e}getSender(){return this.sender||null}setSender(e){this.sender=e}getAddressee(){return this.addressee||null}setAddressee(e){this.addressee=e}getFileName(){return this.fileName}setFileName(e){this.fileName=e}getFileSize(){return this.fileSize}setFileSize(e){this.fileSize=e}getChecksum(){return this.checksum}setChecksum(e){this.checksum=e}getTimestamp(){return this.timestamp}setTimestamp(e){this.timestamp=e}}class ps{static parseLong(e,n=void 0){return parseInt(e,n)}}class ms extends g{}ms.kind="NullPointerException";class ld{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,o){if(e==null)throw new ms;if(n<0||n>e.length||o<0||n+o>e.length||n+o<0)throw new M;if(o===0)return;for(let s=0;s<o;s++)this.write(e[n+s])}flush(){}close(){}}class cd extends g{}class ud extends ld{constructor(e=32){if(super(),this.count=0,e<0)throw new A("Negative initial size: "+e);this.buf=new Uint8Array(e)}ensureCapacity(e){e-this.buf.length>0&&this.grow(e)}grow(e){let o=this.buf.length<<1;if(o-e<0&&(o=e),o<0){if(e<0)throw new cd;o=F.MAX_VALUE}this.buf=$.copyOfUint8Array(this.buf,o)}write(e){this.ensureCapacity(this.count+1),this.buf[this.count]=e,this.count+=1}writeBytesOffset(e,n,o){if(n<0||n>e.length||o<0||n+o-e.length>0)throw new M;this.ensureCapacity(this.count+o),P.arraycopy(e,n,this.buf,this.count,o),this.count+=o}writeTo(e){e.writeBytesOffset(this.buf,0,this.count)}reset(){this.count=0}toByteArray(){return $.copyOfUint8Array(this.buf,this.count)}size(){return this.count}toString(e){return e?typeof e=="string"?this.toString_string(e):this.toString_number(e):this.toString_void()}toString_void(){return new String(this.buf).toString()}toString_string(e){return new String(this.buf).toString()}toString_number(e){return new String(this.buf).toString()}close(){}}var ut;(function(C){C[C.ALPHA=0]="ALPHA",C[C.LOWER=1]="LOWER",C[C.MIXED=2]="MIXED",C[C.PUNCT=3]="PUNCT",C[C.ALPHA_SHIFT=4]="ALPHA_SHIFT",C[C.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(ut||(ut={}));function gs(){if(typeof window<"u")return window.BigInt||null;if(typeof To<"u")return To.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let po;function Xn(C){if(typeof po>"u"&&(po=gs()),po===null)throw new Error("BigInt is not supported!");return po(C)}function dd(){let C=[];C[0]=Xn(1);let e=Xn(900);C[1]=e;for(let n=2;n<16;n++)C[n]=C[n-1]*e;return C}class K{static decode(e,n){let o=new fe(""),s=z.ISO8859_1;o.enableDecoding(s);let a=1,l=e[a++],u=new hs;for(;a<e[0];){switch(l){case K.TEXT_COMPACTION_MODE_LATCH:a=K.textCompaction(e,a,o);break;case K.BYTE_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:a=K.byteCompaction(l,e,s,a,o);break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:o.append(e[a++]);break;case K.NUMERIC_COMPACTION_MODE_LATCH:a=K.numericCompaction(e,a,o);break;case K.ECI_CHARSET:z.getCharacterSetECIByValue(e[a++]);break;case K.ECI_GENERAL_PURPOSE:a+=2;break;case K.ECI_USER_DEFINED:a++;break;case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:a=K.decodeMacroBlock(e,a,u);break;case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:throw new L;default:a--,a=K.textCompaction(e,a,o);break}if(a<e.length)l=e[a++];else throw L.getFormatInstance()}if(o.length()===0)throw L.getFormatInstance();let h=new Pe(null,o.toString(),null,n);return h.setOther(u),h}static decodeMacroBlock(e,n,o){if(n+K.NUMBER_OF_SEQUENCE_CODEWORDS>e[0])throw L.getFormatInstance();let s=new Int32Array(K.NUMBER_OF_SEQUENCE_CODEWORDS);for(let u=0;u<K.NUMBER_OF_SEQUENCE_CODEWORDS;u++,n++)s[u]=e[n];o.setSegmentIndex(F.parseInt(K.decodeBase900toBase10(s,K.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new fe;n=K.textCompaction(e,n,a),o.setFileId(a.toString());let l=-1;for(e[n]===K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<e[0];)switch(e[n]){case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,e[n]){case K.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let u=new fe;n=K.textCompaction(e,n+1,u),o.setFileName(u.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new fe;n=K.textCompaction(e,n+1,h),o.setSender(h.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new fe;n=K.textCompaction(e,n+1,p),o.setAddressee(p.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new fe;n=K.numericCompaction(e,n+1,y),o.setSegmentCount(F.parseInt(y.toString()));break;case K.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let b=new fe;n=K.numericCompaction(e,n+1,b),o.setTimestamp(ps.parseLong(b.toString()));break;case K.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new fe;n=K.numericCompaction(e,n+1,I),o.setChecksum(F.parseInt(I.toString()));break;case K.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let R=new fe;n=K.numericCompaction(e,n+1,R),o.setFileSize(ps.parseLong(R.toString()));break;default:throw L.getFormatInstance()}break;case K.MACRO_PDF417_TERMINATOR:n++,o.setLastSegment(!0);break;default:throw L.getFormatInstance()}if(l!==-1){let u=n-l;o.isLastSegment()&&u--,o.setOptionalData($.copyOfRange(e,l,l+u))}return n}static textCompaction(e,n,o){let s=new Int32Array((e[0]-n)*2),a=new Int32Array((e[0]-n)*2),l=0,u=!1;for(;n<e[0]&&!u;){let h=e[n++];if(h<K.TEXT_COMPACTION_MODE_LATCH)s[l]=h/30,s[l+1]=h%30,l+=2;else switch(h){case K.TEXT_COMPACTION_MODE_LATCH:s[l++]=K.TEXT_COMPACTION_MODE_LATCH;break;case K.BYTE_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.NUMERIC_COMPACTION_MODE_LATCH:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:n--,u=!0;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s[l]=K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,h=e[n++],a[l]=h,l++;break}}return K.decodeTextCompaction(s,a,l,o),n}static decodeTextCompaction(e,n,o,s){let a=ut.ALPHA,l=ut.ALPHA,u=0;for(;u<o;){let h=e[u],p="";switch(a){case ut.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case K.LL:a=ut.LOWER;break;case K.ML:a=ut.MIXED;break;case K.PS:l=a,a=ut.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case K.AS:l=a,a=ut.ALPHA_SHIFT;break;case K.ML:a=ut.MIXED;break;case K.PS:l=a,a=ut.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.MIXED:if(h<K.PL)p=K.MIXED_CHARS[h];else switch(h){case K.PL:a=ut.PUNCT;break;case 26:p=" ";break;case K.LL:a=ut.LOWER;break;case K.AL:a=ut.ALPHA;break;case K.PS:l=a,a=ut.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.PUNCT:if(h<K.PAL)p=K.PUNCT_CHARS[h];else switch(h){case K.PAL:a=ut.ALPHA;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.ALPHA_SHIFT:if(a=l,h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.PUNCT_SHIFT:if(a=l,h<K.PAL)p=K.PUNCT_CHARS[h];else switch(h){case K.PAL:a=ut.ALPHA;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break}p!==""&&s.append(p),u++}}static byteCompaction(e,n,o,s,a){let l=new ud,u=0,h=0,p=!1;switch(e){case K.BYTE_COMPACTION_MODE_LATCH:let y=new Int32Array(6),b=n[s++];for(;s<n[0]&&!p;)switch(y[u++]=b,h=900*h+b,b=n[s++],b){case K.TEXT_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH:case K.NUMERIC_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:s--,p=!0;break;default:if(u%5===0&&u>0){for(let I=0;I<6;++I)l.write(Number(Xn(h)>>Xn(8*(5-I))));h=0,u=0}break}s===n[0]&&b<K.TEXT_COMPACTION_MODE_LATCH&&(y[u++]=b);for(let I=0;I<u;I++)l.write(y[I]);break;case K.BYTE_COMPACTION_MODE_LATCH_6:for(;s<n[0]&&!p;){let I=n[s++];if(I<K.TEXT_COMPACTION_MODE_LATCH)u++,h=900*h+I;else switch(I){case K.TEXT_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH:case K.NUMERIC_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:s--,p=!0;break}if(u%5===0&&u>0){for(let R=0;R<6;++R)l.write(Number(Xn(h)>>Xn(8*(5-R))));h=0,u=0}}break}return a.append(G.decode(l.toByteArray(),o)),s}static numericCompaction(e,n,o){let s=0,a=!1,l=new Int32Array(K.MAX_NUMERIC_CODEWORDS);for(;n<e[0]&&!a;){let u=e[n++];if(n===e[0]&&(a=!0),u<K.TEXT_COMPACTION_MODE_LATCH)l[s]=u,s++;else switch(u){case K.TEXT_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:n--,a=!0;break}(s%K.MAX_NUMERIC_CODEWORDS===0||u===K.NUMERIC_COMPACTION_MODE_LATCH||a)&&s>0&&(o.append(K.decodeBase900toBase10(l,s)),s=0)}return n}static decodeBase900toBase10(e,n){let o=Xn(0);for(let a=0;a<n;a++)o+=K.EXP900[n-a-1]*Xn(e[a]);let s=o.toString();if(s.charAt(0)!=="1")throw new L;return s.substring(1)}}K.TEXT_COMPACTION_MODE_LATCH=900,K.BYTE_COMPACTION_MODE_LATCH=901,K.NUMERIC_COMPACTION_MODE_LATCH=902,K.BYTE_COMPACTION_MODE_LATCH_6=924,K.ECI_USER_DEFINED=925,K.ECI_GENERAL_PURPOSE=926,K.ECI_CHARSET=927,K.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,K.MACRO_PDF417_TERMINATOR=922,K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,K.MAX_NUMERIC_CODEWORDS=15,K.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,K.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,K.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,K.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,K.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,K.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,K.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,K.PL=25,K.LL=27,K.AS=27,K.ML=28,K.AL=28,K.PS=29,K.PAL=29,K.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,:
69
+ -.$/"|*()?{}'`,K.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",K.EXP900=gs()?dd():[],K.NUMBER_OF_SEQUENCE_CODEWORDS=2;class Ge{constructor(){}static decode(e,n,o,s,a,l,u){let h=new ar(e,n,o,s,a),p=null,y=null,b;for(let U=!0;;U=!1){if(n!=null&&(p=Ge.getRowIndicatorColumn(e,h,n,!0,l,u)),s!=null&&(y=Ge.getRowIndicatorColumn(e,h,s,!1,l,u)),b=Ge.merge(p,y),b==null)throw q.getNotFoundInstance();let V=b.getBoundingBox();if(U&&V!=null&&(V.getMinY()<h.getMinY()||V.getMaxY()>h.getMaxY()))h=V;else break}b.setBoundingBox(h);let I=b.getBarcodeColumnCount()+1;b.setDetectionResultColumn(0,p),b.setDetectionResultColumn(I,y);let R=p!=null;for(let U=1;U<=I;U++){let V=R?U:I-U;if(b.getDetectionResultColumn(V)!==void 0)continue;let H;V===0||V===I?H=new fs(h,V===0):H=new Br(h),b.setDetectionResultColumn(V,H);let Q=-1,he=Q;for(let pe=h.getMinY();pe<=h.getMaxY();pe++){if(Q=Ge.getStartColumn(b,V,pe,R),Q<0||Q>h.getMaxX()){if(he===-1)continue;Q=he}let ce=Ge.detectCodeword(e,h.getMinX(),h.getMaxX(),R,Q,pe,l,u);ce!=null&&(H.setCodeword(pe,ce),he=Q,l=Math.min(l,ce.getWidth()),u=Math.max(u,ce.getWidth()))}}return Ge.createDecoderResult(b)}static merge(e,n){if(e==null&&n==null)return null;let o=Ge.getBarcodeMetadata(e,n);if(o==null)return null;let s=ar.merge(Ge.adjustBoundingBox(e),Ge.adjustBoundingBox(n));return new Fr(o,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let o=Ge.getMax(n),s=0;for(let u of n)if(s+=o-u,u>0)break;let a=e.getCodewords();for(let u=0;s>0&&a[u]==null;u++)s--;let l=0;for(let u=n.length-1;u>=0&&(l+=o-n[u],!(n[u]>0));u--);for(let u=a.length-1;l>0&&a[u]==null;u--)l--;return e.getBoundingBox().addMissingRows(s,l,e.isLeft())}static getMax(e){let n=-1;for(let o of e)n=Math.max(n,o);return n}static getBarcodeMetadata(e,n){let o;if(e==null||(o=e.getBarcodeMetadata())==null)return n==null?null:n.getBarcodeMetadata();let s;return n==null||(s=n.getBarcodeMetadata())==null?o:o.getColumnCount()!==s.getColumnCount()&&o.getErrorCorrectionLevel()!==s.getErrorCorrectionLevel()&&o.getRowCount()!==s.getRowCount()?null:o}static getRowIndicatorColumn(e,n,o,s,a,l){let u=new fs(n,s);for(let h=0;h<2;h++){let p=h===0?1:-1,y=Math.trunc(Math.trunc(o.getX()));for(let b=Math.trunc(Math.trunc(o.getY()));b<=n.getMaxY()&&b>=n.getMinY();b+=p){let I=Ge.detectCodeword(e,0,e.getWidth(),s,y,b,a,l);I!=null&&(u.setCodeword(b,I),s?y=I.getStartX():y=I.getEndX())}}return u}static adjustCodewordCount(e,n){let o=n[0][1],s=o.getValue(),a=e.getBarcodeColumnCount()*e.getBarcodeRowCount()-Ge.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>Be.MAX_CODEWORDS_IN_BARCODE)throw q.getNotFoundInstance();o.setValue(a)}else s[0]!==a&&o.setValue(a)}static createDecoderResult(e){let n=Ge.createBarcodeMatrix(e);Ge.adjustCodewordCount(e,n);let o=new Array,s=new Int32Array(e.getBarcodeRowCount()*e.getBarcodeColumnCount()),a=[],l=new Array;for(let h=0;h<e.getBarcodeRowCount();h++)for(let p=0;p<e.getBarcodeColumnCount();p++){let y=n[h][p+1].getValue(),b=h*e.getBarcodeColumnCount()+p;y.length===0?o.push(b):y.length===1?s[b]=y[0]:(l.push(b),a.push(y))}let u=new Array(a.length);for(let h=0;h<u.length;h++)u[h]=a[h];return Ge.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,Be.toIntArray(o),Be.toIntArray(l),u)}static createDecoderResultFromAmbiguousValues(e,n,o,s,a){let l=new Int32Array(s.length),u=100;for(;u-- >0;){for(let h=0;h<l.length;h++)n[s[h]]=a[h][l[h]];try{return Ge.decodeCodewords(n,e,o)}catch(h){if(!(h instanceof T))throw h}if(l.length===0)throw T.getChecksumInstance();for(let h=0;h<l.length;h++)if(l[h]<a[h].length-1){l[h]++;break}else if(l[h]=0,h===l.length-1)throw T.getChecksumInstance()}throw T.getChecksumInstance()}static createBarcodeMatrix(e){let n=Array.from({length:e.getBarcodeRowCount()},()=>new Array(e.getBarcodeColumnCount()+2));for(let s=0;s<n.length;s++)for(let a=0;a<n[s].length;a++)n[s][a]=new Lr;let o=0;for(let s of e.getDetectionResultColumns()){if(s!=null){for(let a of s.getCodewords())if(a!=null){let l=a.getRowNumber();if(l>=0){if(l>=n.length)continue;n[l][o].setValue(a.getValue())}}}o++}return n}static isValidBarcodeColumn(e,n){return n>=0&&n<=e.getBarcodeColumnCount()+1}static getStartColumn(e,n,o,s){let a=s?1:-1,l=null;if(Ge.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodeword(o)),l!=null)return s?l.getEndX():l.getStartX();if(l=e.getDetectionResultColumn(n).getCodewordNearby(o),l!=null)return s?l.getStartX():l.getEndX();if(Ge.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(o)),l!=null)return s?l.getEndX():l.getStartX();let u=0;for(;Ge.isValidBarcodeColumn(e,n-a);){n-=a;for(let h of e.getDetectionResultColumn(n).getCodewords())if(h!=null)return(s?h.getEndX():h.getStartX())+a*u*(h.getEndX()-h.getStartX());u++}return s?e.getBoundingBox().getMinX():e.getBoundingBox().getMaxX()}static detectCodeword(e,n,o,s,a,l,u,h){a=Ge.adjustCodewordStartColumn(e,n,o,s,a,l);let p=Ge.getModuleBitCount(e,n,o,s,a,l);if(p==null)return null;let y,b=Xe.sum(p);if(s)y=a+b;else{for(let U=0;U<p.length/2;U++){let V=p[U];p[U]=p[p.length-1-U],p[p.length-1-U]=V}y=a,a=y-b}if(!Ge.checkCodewordSkew(b,u,h))return null;let I=en.getDecodedValue(p),R=Be.getCodeword(I);return R===-1?null:new Ur(a,y,Ge.getCodewordBucketNumber(I),R)}static getModuleBitCount(e,n,o,s,a,l){let u=a,h=new Int32Array(8),p=0,y=s?1:-1,b=s;for(;(s?u<o:u>=n)&&p<h.length;)e.get(u,l)===b?(h[p]++,u+=y):(p++,b=!b);return p===h.length||u===(s?o:n)&&p===h.length-1?h:null}static getNumberOfECCodeWords(e){return 2<<e}static adjustCodewordStartColumn(e,n,o,s,a,l){let u=a,h=s?-1:1;for(let p=0;p<2;p++){for(;(s?u>=n:u<o)&&s===e.get(u,l);){if(Math.abs(a-u)>Ge.CODEWORD_SKEW_SIZE)return a;u+=h}h=-h,s=!s}return u}static checkCodewordSkew(e,n,o){return n-Ge.CODEWORD_SKEW_SIZE<=e&&e<=o+Ge.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,o){if(e.length===0)throw L.getFormatInstance();let s=1<<n+1,a=Ge.correctErrors(e,o,s);Ge.verifyCodewordCount(e,s);let l=K.decode(e,""+n);return l.setErrorsCorrected(a),l.setErasures(o.length),l}static correctErrors(e,n,o){if(n!=null&&n.length>o/2+Ge.MAX_ERRORS||o<0||o>Ge.MAX_EC_CODEWORDS)throw T.getChecksumInstance();return Ge.errorCorrection.decode(e,o,n)}static verifyCodewordCount(e,n){if(e.length<4)throw L.getFormatInstance();let o=e[0];if(o>e.length)throw L.getFormatInstance();if(o===0)if(n<e.length)e[0]=e.length-n;else throw L.getFormatInstance()}static getBitCountForCodeword(e){let n=new Int32Array(8),o=0,s=n.length-1;for(;!((e&1)!==o&&(o=e&1,s--,s<0));)n[s]++,e>>=1;return n}static getCodewordBucketNumber(e){return e instanceof Int32Array?this.getCodewordBucketNumber_Int32Array(e):this.getCodewordBucketNumber_number(e)}static getCodewordBucketNumber_number(e){return Ge.getCodewordBucketNumber(Ge.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new Pr;for(let o=0;o<e.length;o++){n.format("Row %2d: ",o);for(let s=0;s<e[o].length;s++){let a=e[o][s];a.getValue().length===0?n.format(" ",null):n.format("%4d(%2d)",a.getValue()[0],a.getConfidence(a.getValue()[0]))}n.format("%n")}return n.toString()}}Ge.CODEWORD_SKEW_SIZE=2,Ge.MAX_ERRORS=3,Ge.MAX_EC_CODEWORDS=512,Ge.errorCorrection=new ds;class jt{decode(e,n=null){let o=jt.decode(e,n,!1);if(o==null||o.length===0||o[0]==null)throw q.getNotFoundInstance();return o[0]}decodeMultiple(e,n=null){try{return jt.decode(e,n,!0)}catch(o){throw o instanceof L||o instanceof T?q.getNotFoundInstance():o}}static decode(e,n,o){const s=new Array,a=We.detectMultiple(e,n,o);for(const l of a.getPoints()){const u=Ge.decode(a.getBits(),l[4],l[5],l[6],l[7],jt.getMinCodewordWidth(l),jt.getMaxCodewordWidth(l)),h=new qe(u.getText(),u.getRawBytes(),void 0,l,ie.PDF_417);h.putMetadata(_e.ERROR_CORRECTION_LEVEL,u.getECLevel());const p=u.getOther();p!=null&&h.putMetadata(_e.PDF417_EXTRA_METADATA,p),s.push(h)}return s.map(l=>l)}static getMaxWidth(e,n){return e==null||n==null?0:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMinWidth(e,n){return e==null||n==null?F.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(jt.getMaxWidth(e[0],e[4]),jt.getMaxWidth(e[6],e[2])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN),Math.max(jt.getMaxWidth(e[1],e[5]),jt.getMaxWidth(e[7],e[3])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(jt.getMinWidth(e[0],e[4]),jt.getMinWidth(e[6],e[2])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN),Math.min(jt.getMinWidth(e[1],e[5]),jt.getMinWidth(e[7],e[3])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN)))}reset(){}}class mo extends g{}mo.kind="ReaderException";class xs{constructor(e,n){this.verbose=e===!0,n&&this.setHints(n)}decode(e,n){return n&&this.setHints(n),this.decodeInternal(e)}decodeWithState(e){return(this.readers===null||this.readers===void 0)&&this.setHints(null),this.decodeInternal(e)}setHints(e){this.hints=e;const n=!c(e)&&e.get(B.TRY_HARDER)===!0,o=c(e)?null:e.get(B.POSSIBLE_FORMATS),s=new Array;if(!c(o)){const a=o.some(l=>l===ie.UPC_A||l===ie.UPC_E||l===ie.EAN_13||l===ie.EAN_8||l===ie.CODABAR||l===ie.CODE_39||l===ie.CODE_93||l===ie.CODE_128||l===ie.ITF||l===ie.RSS_14||l===ie.RSS_EXPANDED);a&&!n&&s.push(new br(e,this.verbose)),o.includes(ie.QR_CODE)&&s.push(new qn),o.includes(ie.DATA_MATRIX)&&s.push(new Gn),o.includes(ie.AZTEC)&&s.push(new Ln),o.includes(ie.PDF_417)&&s.push(new jt),a&&n&&s.push(new br(e,this.verbose))}s.length===0&&(n||s.push(new br(e,this.verbose)),s.push(new qn),s.push(new Gn),s.push(new Ln),s.push(new jt),n&&s.push(new br(e,this.verbose))),this.readers=s}reset(){if(this.readers!==null)for(const e of this.readers)e.reset()}decodeInternal(e){if(this.readers===null)throw new mo("No readers where selected, nothing can be read.");for(const n of this.readers)try{return n.decode(e,this.hints)}catch(o){if(o instanceof mo)continue}throw new q("No MultiFormat Readers were able to detect the code.")}}class fd extends Ze{constructor(e=null,n=500){const o=new xs;o.setHints(e),super(o,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class hd extends Ze{constructor(e=500){super(new jt,e)}}class pd extends Ze{constructor(e=500){super(new qn,e)}}var ei;(function(C){C[C.ERROR_CORRECTION=0]="ERROR_CORRECTION",C[C.CHARACTER_SET=1]="CHARACTER_SET",C[C.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",C[C.MIN_SIZE=3]="MIN_SIZE",C[C.MAX_SIZE=4]="MAX_SIZE",C[C.MARGIN=5]="MARGIN",C[C.PDF417_COMPACT=6]="PDF417_COMPACT",C[C.PDF417_COMPACTION=7]="PDF417_COMPACTION",C[C.PDF417_DIMENSIONS=8]="PDF417_DIMENSIONS",C[C.AZTEC_LAYERS=9]="AZTEC_LAYERS",C[C.QR_VERSION=10]="QR_VERSION"})(ei||(ei={}));var Bt=ei;class ti{constructor(e){this.field=e,this.cachedGenerators=[],this.cachedGenerators.push(new J(e,Int32Array.from([1])))}buildGenerator(e){const n=this.cachedGenerators;if(e>=n.length){let o=n[n.length-1];const s=this.field;for(let a=n.length;a<=e;a++){const l=o.multiply(new J(s,Int32Array.from([1,s.exp(a-1+s.getGeneratorBase())])));n.push(l),o=l}}return n[e]}encode(e,n){if(n===0)throw new A("No error correction bytes");const o=e.length-n;if(o<=0)throw new A("No data bytes provided");const s=this.buildGenerator(n),a=new Int32Array(o);P.arraycopy(e,0,a,0,o);let l=new J(this.field,a);l=l.multiplyByMonomial(n,1);const h=l.divide(s)[1].getCoefficients(),p=n-h.length;for(let y=0;y<p;y++)e[o+y]=0;P.arraycopy(h,0,e,o+p,h.length)}}class Nt{constructor(){}static applyMaskPenaltyRule1(e){return Nt.applyMaskPenaltyRule1Internal(e,!0)+Nt.applyMaskPenaltyRule1Internal(e,!1)}static applyMaskPenaltyRule2(e){let n=0;const o=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a-1;l++){const u=o[l];for(let h=0;h<s-1;h++){const p=u[h];p===u[h+1]&&p===o[l+1][h]&&p===o[l+1][h+1]&&n++}}return Nt.N2*n}static applyMaskPenaltyRule3(e){let n=0;const o=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a;l++)for(let u=0;u<s;u++){const h=o[l];u+6<s&&h[u]===1&&h[u+1]===0&&h[u+2]===1&&h[u+3]===1&&h[u+4]===1&&h[u+5]===0&&h[u+6]===1&&(Nt.isWhiteHorizontal(h,u-4,u)||Nt.isWhiteHorizontal(h,u+7,u+11))&&n++,l+6<a&&o[l][u]===1&&o[l+1][u]===0&&o[l+2][u]===1&&o[l+3][u]===1&&o[l+4][u]===1&&o[l+5][u]===0&&o[l+6][u]===1&&(Nt.isWhiteVertical(o,u,l-4,l)||Nt.isWhiteVertical(o,u,l+7,l+11))&&n++}return n*Nt.N3}static isWhiteHorizontal(e,n,o){n=Math.max(n,0),o=Math.min(o,e.length);for(let s=n;s<o;s++)if(e[s]===1)return!1;return!0}static isWhiteVertical(e,n,o,s){o=Math.max(o,0),s=Math.min(s,e.length);for(let a=o;a<s;a++)if(e[a][n]===1)return!1;return!0}static applyMaskPenaltyRule4(e){let n=0;const o=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let h=0;h<a;h++){const p=o[h];for(let y=0;y<s;y++)p[y]===1&&n++}const l=e.getHeight()*e.getWidth();return Math.floor(Math.abs(n*2-l)*10/l)*Nt.N4}static getDataMaskBit(e,n,o){let s,a;switch(e){case 0:s=o+n&1;break;case 1:s=o&1;break;case 2:s=n%3;break;case 3:s=(o+n)%3;break;case 4:s=Math.floor(o/2)+Math.floor(n/3)&1;break;case 5:a=o*n,s=(a&1)+a%3;break;case 6:a=o*n,s=(a&1)+a%3&1;break;case 7:a=o*n,s=a%3+(o+n&1)&1;break;default:throw new A("Invalid mask pattern: "+e)}return s===0}static applyMaskPenaltyRule1Internal(e,n){let o=0;const s=n?e.getHeight():e.getWidth(),a=n?e.getWidth():e.getHeight(),l=e.getArray();for(let u=0;u<s;u++){let h=0,p=-1;for(let y=0;y<a;y++){const b=n?l[u][y]:l[y][u];b===p?h++:(h>=5&&(o+=Nt.N1+(h-5)),h=1,p=b)}h>=5&&(o+=Nt.N1+(h-5))}return o}}Nt.N1=3,Nt.N2=3,Nt.N3=40,Nt.N4=10;class go{constructor(e,n){this.width=e,this.height=n;const o=new Array(n);for(let s=0;s!==n;s++)o[s]=new Uint8Array(e);this.bytes=o}getHeight(){return this.height}getWidth(){return this.width}get(e,n){return this.bytes[n][e]}getArray(){return this.bytes}setNumber(e,n,o){this.bytes[n][e]=o}setBoolean(e,n,o){this.bytes[n][e]=o?1:0}clear(e){for(const n of this.bytes)$.fill(n,e)}equals(e){if(!(e instanceof go))return!1;const n=e;if(this.width!==n.width||this.height!==n.height)return!1;for(let o=0,s=this.height;o<s;++o){const a=this.bytes[o],l=n.bytes[o];for(let u=0,h=this.width;u<h;++u)if(a[u]!==l[u])return!1}return!0}toString(){const e=new fe;for(let n=0,o=this.height;n<o;++n){const s=this.bytes[n];for(let a=0,l=this.width;a<l;++a)switch(s[a]){case 0:e.append(" 0");break;case 1:e.append(" 1");break;default:e.append(" ");break}e.append(`
70
+ `)}return e.toString()}}class lr{constructor(){this.maskPattern=-1}getMode(){return this.mode}getECLevel(){return this.ecLevel}getVersion(){return this.version}getMaskPattern(){return this.maskPattern}getMatrix(){return this.matrix}toString(){const e=new fe;return e.append(`<<
66
71
  `),e.append(" mode: "),e.append(this.mode?this.mode.toString():"null"),e.append(`
67
72
  ecLevel: `),e.append(this.ecLevel?this.ecLevel.toString():"null"),e.append(`
68
73
  version: `),e.append(this.version?this.version.toString():"null"),e.append(`
@@ -71,9 +76,9 @@ ${this.tempPrompt}
71
76
  `),e.append(this.matrix.toString())):e.append(`
72
77
  matrix: null
73
78
  `),e.append(`>>
74
- `),e.toString()}setMode(e){this.mode=e}setECLevel(e){this.ecLevel=e}setVersion(e){this.version=e}setMaskPattern(e){this.maskPattern=e}setMatrix(e){this.matrix=e}static isValidMaskPattern(e){return e>=0&&e<ar.NUM_MASK_PATTERNS}}ar.NUM_MASK_PATTERNS=8;class ot extends x{}ot.kind="WriterException";class Re{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,i,s,a){Re.clearMatrix(a),Re.embedBasicPatterns(i,a),Re.embedTypeInfo(n,s,a),Re.maybeEmbedVersionInfo(i,a),Re.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){Re.embedPositionDetectionPatternsAndSeparators(n),Re.embedDarkDotAtLeftBottomCorner(n),Re.maybeEmbedPositionAdjustmentPatterns(e,n),Re.embedTimingPatterns(n)}static embedTypeInfo(e,n,i){const s=new ee;Re.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const d=s.get(s.getSize()-1-a),h=Re.TYPE_INFO_COORDINATES[a],p=h[0],y=h[1];if(i.setBoolean(p,y,d),a<8){const E=i.getWidth()-a-1;i.setBoolean(E,8,d)}else{const I=i.getHeight()-7+(a-8);i.setBoolean(8,I,d)}}}static maybeEmbedVersionInfo(e,n){if(e.getVersionNumber()<7)return;const i=new ee;Re.makeVersionInfoBits(e,i);let s=17;for(let a=0;a<6;++a)for(let l=0;l<3;++l){const d=i.get(s);s--,n.setBoolean(a,n.getHeight()-11+l,d),n.setBoolean(n.getHeight()-11+l,a,d)}}static embedDataBits(e,n,i){let s=0,a=-1,l=i.getWidth()-1,d=i.getHeight()-1;for(;l>0;){for(l===6&&(l-=1);d>=0&&d<i.getHeight();){for(let h=0;h<2;++h){const p=l-h;if(!Re.isEmpty(i.get(p,d)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&At.getDataMaskBit(n,p,d)&&(y=!y),i.setBoolean(p,d,y)}d+=a}a=-a,d+=a,l-=2}if(s!==e.getSize())throw new ot("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-z.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new v("0 polynomial");const i=Re.findMSBSet(n);for(e<<=i-1;Re.findMSBSet(e)>=i;)e^=n<<Re.findMSBSet(e)-i;return e}static makeTypeInfoBits(e,n,i){if(!ar.isValidMaskPattern(n))throw new ot("Invalid mask pattern");const s=e.getBits()<<3|n;i.appendBits(s,5);const a=Re.calculateBCHCode(s,Re.TYPE_INFO_POLY);i.appendBits(a,10);const l=new ee;if(l.appendBits(Re.TYPE_INFO_MASK_PATTERN,15),i.xor(l),i.getSize()!==15)throw new ot("should not happen but we got: "+i.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const i=Re.calculateBCHCode(e.getVersionNumber(),Re.VERSION_INFO_POLY);if(n.appendBits(i,12),n.getSize()!==18)throw new ot("should not happen but we got: "+n.getSize())}static isEmpty(e){return e===255}static embedTimingPatterns(e){for(let n=8;n<e.getWidth()-8;++n){const i=(n+1)%2;Re.isEmpty(e.get(n,6))&&e.setNumber(n,6,i),Re.isEmpty(e.get(6,n))&&e.setNumber(6,n,i)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new ot;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,i){for(let s=0;s<8;++s){if(!Re.isEmpty(i.get(e+s,n)))throw new ot;i.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,i){for(let s=0;s<7;++s){if(!Re.isEmpty(i.get(e,n+s)))throw new ot;i.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,i){for(let s=0;s<5;++s){const a=Re.POSITION_ADJUSTMENT_PATTERN[s];for(let l=0;l<5;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPattern(e,n,i){for(let s=0;s<7;++s){const a=Re.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=Re.POSITION_DETECTION_PATTERN[0].length;Re.embedPositionDetectionPattern(0,0,e),Re.embedPositionDetectionPattern(e.getWidth()-n,0,e),Re.embedPositionDetectionPattern(0,e.getWidth()-n,e);const i=8;Re.embedHorizontalSeparationPattern(0,i-1,e),Re.embedHorizontalSeparationPattern(e.getWidth()-i,i-1,e),Re.embedHorizontalSeparationPattern(0,e.getWidth()-i,e);const s=7;Re.embedVerticalSeparationPattern(s,0,e),Re.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),Re.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const i=e.getVersionNumber()-1,s=Re.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[i];for(let a=0,l=s.length;a!==l;a++){const d=s[a];if(d>=0)for(let h=0;h!==l;h++){const p=s[h];p>=0&&Re.isEmpty(n.get(p,d))&&Re.embedPositionAdjustmentPattern(p-2,d-2,n)}}}}Re.POSITION_DETECTION_PATTERN=Array.from([Int32Array.from([1,1,1,1,1,1,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,1,1,1,1,1,1])]),Re.POSITION_ADJUSTMENT_PATTERN=Array.from([Int32Array.from([1,1,1,1,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,0,1,0,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,1,1,1,1])]),Re.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE=Array.from([Int32Array.from([-1,-1,-1,-1,-1,-1,-1]),Int32Array.from([6,18,-1,-1,-1,-1,-1]),Int32Array.from([6,22,-1,-1,-1,-1,-1]),Int32Array.from([6,26,-1,-1,-1,-1,-1]),Int32Array.from([6,30,-1,-1,-1,-1,-1]),Int32Array.from([6,34,-1,-1,-1,-1,-1]),Int32Array.from([6,22,38,-1,-1,-1,-1]),Int32Array.from([6,24,42,-1,-1,-1,-1]),Int32Array.from([6,26,46,-1,-1,-1,-1]),Int32Array.from([6,28,50,-1,-1,-1,-1]),Int32Array.from([6,30,54,-1,-1,-1,-1]),Int32Array.from([6,32,58,-1,-1,-1,-1]),Int32Array.from([6,34,62,-1,-1,-1,-1]),Int32Array.from([6,26,46,66,-1,-1,-1]),Int32Array.from([6,26,48,70,-1,-1,-1]),Int32Array.from([6,26,50,74,-1,-1,-1]),Int32Array.from([6,30,54,78,-1,-1,-1]),Int32Array.from([6,30,56,82,-1,-1,-1]),Int32Array.from([6,30,58,86,-1,-1,-1]),Int32Array.from([6,34,62,90,-1,-1,-1]),Int32Array.from([6,28,50,72,94,-1,-1]),Int32Array.from([6,26,50,74,98,-1,-1]),Int32Array.from([6,30,54,78,102,-1,-1]),Int32Array.from([6,28,54,80,106,-1,-1]),Int32Array.from([6,32,58,84,110,-1,-1]),Int32Array.from([6,30,58,86,114,-1,-1]),Int32Array.from([6,34,62,90,118,-1,-1]),Int32Array.from([6,26,50,74,98,122,-1]),Int32Array.from([6,30,54,78,102,126,-1]),Int32Array.from([6,26,52,78,104,130,-1]),Int32Array.from([6,30,56,82,108,134,-1]),Int32Array.from([6,34,60,86,112,138,-1]),Int32Array.from([6,30,58,86,114,142,-1]),Int32Array.from([6,34,62,90,118,146,-1]),Int32Array.from([6,30,54,78,102,126,150]),Int32Array.from([6,24,50,76,102,128,154]),Int32Array.from([6,28,54,80,106,132,158]),Int32Array.from([6,32,58,84,110,136,162]),Int32Array.from([6,26,54,82,110,138,166]),Int32Array.from([6,30,58,86,114,142,170])]),Re.TYPE_INFO_COORDINATES=Array.from([Int32Array.from([8,0]),Int32Array.from([8,1]),Int32Array.from([8,2]),Int32Array.from([8,3]),Int32Array.from([8,4]),Int32Array.from([8,5]),Int32Array.from([8,7]),Int32Array.from([8,8]),Int32Array.from([7,8]),Int32Array.from([5,8]),Int32Array.from([4,8]),Int32Array.from([3,8]),Int32Array.from([2,8]),Int32Array.from([1,8]),Int32Array.from([0,8])]),Re.VERSION_INFO_POLY=7973,Re.TYPE_INFO_POLY=1335,Re.TYPE_INFO_MASK_PATTERN=21522;class td{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class dt{constructor(){}static calculateMaskPenalty(e){return At.applyMaskPenaltyRule1(e)+At.applyMaskPenaltyRule2(e)+At.applyMaskPenaltyRule3(e)+At.applyMaskPenaltyRule4(e)}static encode(e,n,i=null){let s=dt.DEFAULT_BYTE_MODE_ENCODING;const a=i!==null&&i.get(Dt.CHARACTER_SET)!==void 0;a&&(s=i.get(Dt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),d=new ee;if(l===Ne.BYTE&&(a||dt.DEFAULT_BYTE_MODE_ENCODING!==s)){const ce=S.getCharacterSetECIByName(s);ce!==void 0&&this.appendECI(ce,d)}this.appendModeInfo(l,d);const h=new ee;this.appendBytes(e,l,h,s);let p;if(i!==null&&i.get(Dt.QR_VERSION)!==void 0){const ce=Number.parseInt(i.get(Dt.QR_VERSION).toString(),10);p=Ie.getVersionForNumber(ce);const ae=this.calculateBitsNeeded(l,d,h,p);if(!this.willFit(ae,p,n))throw new ot("Data too big for requested version")}else p=this.recommendVersion(n,l,d,h);const y=new ee;y.appendBitArray(d);const E=l===Ne.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(E,p,l,y),y.appendBitArray(h);const I=p.getECBlocksForLevel(n),k=p.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(k,y);const L=this.interleaveWithECBytes(y,p.getTotalCodewords(),k,I.getNumBlocks()),F=new ar;F.setECLevel(n),F.setMode(l),F.setVersion(p);const H=p.getDimensionForVersion(),Y=new di(H,H),le=this.chooseMaskPattern(L,n,p,Y);return F.setMaskPattern(le),Re.buildMatrix(L,n,p,le,Y),F.setMatrix(Y),F}static recommendVersion(e,n,i,s){const a=this.calculateBitsNeeded(n,i,s,Ie.getVersionForNumber(1)),l=this.chooseVersion(a,e),d=this.calculateBitsNeeded(n,i,s,l);return this.chooseVersion(d,e)}static calculateBitsNeeded(e,n,i,s){return n.getSize()+e.getCharacterCountBits(s)+i.getSize()}static getAlphanumericCode(e){return e<dt.ALPHANUMERIC_TABLE.length?dt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(S.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Ne.KANJI;let i=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const d=e.charAt(a);if(dt.isDigit(d))i=!0;else if(this.getAlphanumericCode(d.charCodeAt(0))!==-1)s=!0;else return Ne.BYTE}return s?Ne.ALPHANUMERIC:i?Ne.NUMERIC:Ne.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=ye.encode(e,S.SJIS)}catch{return!1}const i=n.length;if(i%2!==0)return!1;for(let s=0;s<i;s+=2){const a=n[s]&255;if((a<129||a>159)&&(a<224||a>235))return!1}return!0}static chooseMaskPattern(e,n,i,s){let a=Number.MAX_SAFE_INTEGER,l=-1;for(let d=0;d<ar.NUM_MASK_PATTERNS;d++){Re.buildMatrix(e,n,i,d,s);let h=this.calculateMaskPenalty(s);h<a&&(a=h,l=d)}return l}static chooseVersion(e,n){for(let i=1;i<=40;i++){const s=Ie.getVersionForNumber(i);if(dt.willFit(e,s,n))return s}throw new ot("Data too big")}static willFit(e,n,i){const s=n.getTotalCodewords(),l=n.getECBlocksForLevel(i).getTotalECCodewords(),d=s-l,h=(e+7)/8;return d>=h}static terminateBits(e,n){const i=e*8;if(n.getSize()>i)throw new ot("data bits cannot fit in the QR Code"+n.getSize()+" > "+i);for(let l=0;l<4&&n.getSize()<i;++l)n.appendBit(!1);const s=n.getSize()&7;if(s>0)for(let l=s;l<8;l++)n.appendBit(!1);const a=e-n.getSizeInBytes();for(let l=0;l<a;++l)n.appendBits((l&1)===0?236:17,8);if(n.getSize()!==i)throw new ot("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,i,s,a,l){if(s>=i)throw new ot("Block ID too large");const d=e%i,h=i-d,p=Math.floor(e/i),y=p+1,E=Math.floor(n/i),I=E+1,k=p-E,L=y-I;if(k!==L)throw new ot("EC bytes mismatch");if(i!==h+d)throw new ot("RS blocks mismatch");if(e!==(E+k)*h+(I+L)*d)throw new ot("Total bytes mismatch");s<h?(a[0]=E,l[0]=k):(a[0]=I,l[0]=L)}static interleaveWithECBytes(e,n,i,s){if(e.getSizeInBytes()!==i)throw new ot("Number of bits and data bytes does not match");let a=0,l=0,d=0;const h=new Array;for(let y=0;y<s;++y){const E=new Int32Array(1),I=new Int32Array(1);dt.getNumDataBytesAndNumECBytesForBlockID(n,i,s,y,E,I);const k=E[0],L=new Uint8Array(k);e.toBytes(8*a,L,0,k);const F=dt.generateECBytes(L,I[0]);h.push(new td(L,F)),l=Math.max(l,k),d=Math.max(d,F.length),a+=E[0]}if(i!==a)throw new ot("Data bytes does not match offset");const p=new ee;for(let y=0;y<l;++y)for(const E of h){const I=E.getDataBytes();y<I.length&&p.appendBits(I[y],8)}for(let y=0;y<d;++y)for(const E of h){const I=E.getErrorCorrectionBytes();y<I.length&&p.appendBits(I[y],8)}if(n!==p.getSizeInBytes())throw new ot("Interleaving error: "+n+" and "+p.getSizeInBytes()+" differ.");return p}static generateECBytes(e,n){const i=e.length,s=new Int32Array(i+n);for(let l=0;l<i;l++)s[l]=e[l]&255;new Yi(be.QR_CODE_FIELD_256).encode(s,n);const a=new Uint8Array(n);for(let l=0;l<n;l++)a[l]=s[i+l];return a}static appendModeInfo(e,n){n.appendBits(e.getBits(),4)}static appendLengthInfo(e,n,i,s){const a=i.getCharacterCountBits(n);if(e>=1<<a)throw new ot(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,i,s){switch(n){case Ne.NUMERIC:dt.appendNumericBytes(e,i);break;case Ne.ALPHANUMERIC:dt.appendAlphanumericBytes(e,i);break;case Ne.BYTE:dt.append8BitBytes(e,i,s);break;case Ne.KANJI:dt.appendKanjiBytes(e,i);break;default:throw new ot("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=dt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getDigit(e.charAt(s));if(s+2<i){const l=dt.getDigit(e.charAt(s+1)),d=dt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+d,10),s+=3}else if(s+1<i){const l=dt.getDigit(e.charAt(s+1));n.appendBits(a*10+l,7),s+=2}else n.appendBits(a,4),s++}}static appendAlphanumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new ot;if(s+1<i){const l=dt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new ot;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,i){let s;try{s=ye.encode(e,i)}catch(a){throw new ot(a)}for(let a=0,l=s.length;a!==l;a++){const d=s[a];n.appendBits(d,8)}}static appendKanjiBytes(e,n){let i;try{i=ye.encode(e,S.SJIS)}catch(a){throw new ot(a)}const s=i.length;for(let a=0;a<s;a+=2){const l=i[a]&255,d=i[a+1]&255,h=l<<8&4294967295|d;let p=-1;if(h>=33088&&h<=40956?p=h-33088:h>=57408&&h<=60351&&(p=h-49472),p===-1)throw new ot("Invalid byte sequence");const y=(p>>8)*192+(p&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(Ne.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}dt.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]),dt.DEFAULT_BYTE_MODE_ENCODING=S.UTF8.getName();class lr{write(e,n,i,s=null){if(e.length===0)throw new v("Found empty contents");if(n<0||i<0)throw new v("Requested dimensions are too small: "+n+"x"+i);let a=ct.L,l=lr.QUIET_ZONE_SIZE;s!==null&&(s.get(Dt.ERROR_CORRECTION)!==void 0&&(a=ct.fromString(s.get(Dt.ERROR_CORRECTION).toString())),s.get(Dt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Dt.MARGIN).toString(),10)));const d=dt.encode(e,a,s);return this.renderResult(d,n,i,l)}writeToDom(e,n,i,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,i,s,a);e&&e.appendChild(l)}renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Wt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),E=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(E/p)),k=Math.floor((y-l*I)/2),L=Math.floor((E-d*I)/2),F=this.createSVGElement(y,E);for(let H=0,Y=L;H<d;H++,Y+=I)for(let le=0,ce=k;le<l;le++,ce+=I)if(a.get(le,H)===1){const ae=this.createSvgRectElement(ce,Y,I,I);F.appendChild(ae)}return F}createSVGElement(e,n){const i=document.createElementNS(lr.SVG_NS,"svg");return i.setAttributeNS(null,"height",e.toString()),i.setAttributeNS(null,"width",n.toString()),i}createSvgRectElement(e,n,i,s){const a=document.createElementNS(lr.SVG_NS,"rect");return a.setAttributeNS(null,"x",e.toString()),a.setAttributeNS(null,"y",n.toString()),a.setAttributeNS(null,"height",i.toString()),a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"fill","#000000"),a}}lr.QUIET_ZONE_SIZE=4,lr.SVG_NS="http://www.w3.org/2000/svg";class br{encode(e,n,i,s,a){if(e.length===0)throw new v("Found empty contents");if(n!==Ce.QR_CODE)throw new v("Can only encode QR_CODE, but got "+n);if(i<0||s<0)throw new v(`Requested dimensions are too small: ${i}x${s}`);let l=ct.L,d=br.QUIET_ZONE_SIZE;a!==null&&(a.get(Dt.ERROR_CORRECTION)!==void 0&&(l=ct.fromString(a.get(Dt.ERROR_CORRECTION).toString())),a.get(Dt.MARGIN)!==void 0&&(d=Number.parseInt(a.get(Dt.MARGIN).toString(),10)));const h=dt.encode(e,l,a);return br.renderResult(h,i,s,d)}static renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Wt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),E=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(E/p)),k=Math.floor((y-l*I)/2),L=Math.floor((E-d*I)/2),F=new Me(y,E);for(let H=0,Y=L;H<d;H++,Y+=I)for(let le=0,ce=k;le<l;le++,ce+=I)a.get(le,H)===1&&F.setRegion(ce,Y,I,I);return F}}br.QUIET_ZONE_SIZE=4;class nd{encode(e,n,i,s,a){let l;switch(n){case Ce.QR_CODE:l=new br;break;default:throw new v("No encoder available for format "+n)}return l.encode(e,n,i,s,a)}}class kn extends Q{constructor(e,n,i,s,a,l,d,h){if(super(l,d),this.yuvData=e,this.dataWidth=n,this.dataHeight=i,this.left=s,this.top=a,s+l>n||a+d>i)throw new v("Crop rectangle does not fit within image data.");h&&this.reverseHorizontal(l,d)}getRow(e,n){if(e<0||e>=this.getHeight())throw new v("Requested row is outside the image: "+e);const i=this.getWidth();(n==null||n.length<i)&&(n=new Uint8ClampedArray(i));const s=(e+this.top)*this.dataWidth+this.left;return D.arraycopy(this.yuvData,s,n,0,i),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.yuvData;const i=e*n,s=new Uint8ClampedArray(i);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return D.arraycopy(this.yuvData,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;D.arraycopy(this.yuvData,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new kn(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,i,s,!1)}renderThumbnail(){const e=this.getWidth()/kn.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/kn.THUMBNAIL_SCALE_FACTOR,i=new Int32Array(e*n),s=this.yuvData;let a=this.top*this.dataWidth+this.left;for(let l=0;l<n;l++){const d=l*e;for(let h=0;h<e;h++){const p=s[a+h*kn.THUMBNAIL_SCALE_FACTOR]&255;i[d+h]=4278190080|p*65793}a+=this.dataWidth*kn.THUMBNAIL_SCALE_FACTOR}return i}getThumbnailWidth(){return this.getWidth()/kn.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/kn.THUMBNAIL_SCALE_FACTOR}reverseHorizontal(e,n){const i=this.yuvData;for(let s=0,a=this.top*this.dataWidth+this.left;s<n;s++,a+=this.dataWidth){const l=a+e/2;for(let d=a,h=a+e-1;d<l;d++,h--){const p=i[d];i[d]=i[h],i[h]=p}}}invert(){return new me(this)}}kn.THUMBNAIL_SCALE_FACTOR=2;class Ki extends Q{constructor(e,n,i,s,a,l,d){if(super(n,i),this.dataWidth=s,this.dataHeight=a,this.left=l,this.top=d,e.BYTES_PER_ELEMENT===4){const h=n*i,p=new Uint8ClampedArray(h);for(let y=0;y<h;y++){const E=e[y],I=E>>16&255,k=E>>7&510,L=E&255;p[y]=(I+k+L)/4&255}this.luminances=p}else this.luminances=e;if(s===void 0&&(this.dataWidth=n),a===void 0&&(this.dataHeight=i),l===void 0&&(this.left=0),d===void 0&&(this.top=0),this.left+n>this.dataWidth||this.top+i>this.dataHeight)throw new v("Crop rectangle does not fit within image data.")}getRow(e,n){if(e<0||e>=this.getHeight())throw new v("Requested row is outside the image: "+e);const i=this.getWidth();(n==null||n.length<i)&&(n=new Uint8ClampedArray(i));const s=(e+this.top)*this.dataWidth+this.left;return D.arraycopy(this.luminances,s,n,0,i),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.luminances;const i=e*n,s=new Uint8ClampedArray(i);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return D.arraycopy(this.luminances,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;D.arraycopy(this.luminances,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new Ki(this.luminances,i,s,this.dataWidth,this.dataHeight,this.left+e,this.top+n)}invert(){return new me(this)}}class hs extends S{static forName(e){return this.getCharacterSetECIByName(e)}}class Ji{}Ji.ISO_8859_1=S.ISO8859_1;class ps{isCompact(){return this.compact}setCompact(e){this.compact=e}getSize(){return this.size}setSize(e){this.size=e}getLayers(){return this.layers}setLayers(e){this.layers=e}getCodeWords(){return this.codeWords}setCodeWords(e){this.codeWords=e}getMatrix(){return this.matrix}setMatrix(e){this.matrix=e}}class ms{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class rd{constructor(e){this.previous=e}getPrevious(){return this.previous}}class Er extends rd{constructor(e,n,i){super(e),this.value=n,this.bitCount=i}appendTo(e,n){e.appendBits(this.value,this.bitCount)}add(e,n){return new Er(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new Er(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+z.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class Qi extends Er{constructor(e,n,i){super(e,0,0),this.binaryShiftStart=n,this.binaryShiftByteCount=i}appendTo(e,n){for(let i=0;i<this.binaryShiftByteCount;i++)(i===0||i===31&&this.binaryShiftByteCount<=62)&&(e.appendBits(31,5),this.binaryShiftByteCount>62?e.appendBits(this.binaryShiftByteCount-31,16):i===0?e.appendBits(Math.min(this.binaryShiftByteCount,31),5):e.appendBits(this.binaryShiftByteCount-31,5)),e.appendBits(n[this.binaryShiftStart+i],8)}addBinaryShift(e,n){return new Qi(this,e,n)}toString(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"}}function id(b,e,n){return new Qi(b,e,n)}function Lr(b,e,n){return new Er(b,e,n)}const od=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Kn=0,fi=1,gn=2,gs=3,Rn=4,sd=new Er(null,0,0),eo=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(9<<16)+480+14,0,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(4<<16)+14,(9<<16)+448+28,0,(9<<16)+448+29,932798]),Int32Array.from([(5<<16)+29,(5<<16)+28,656318,0,(5<<16)+30]),Int32Array.from([(5<<16)+31,656380,656382,656381,0])];function ad(b){for(let e of b)Z.fill(e,-1);return b[Kn][Rn]=0,b[fi][Rn]=0,b[fi][Kn]=28,b[gs][Rn]=0,b[gn][Rn]=0,b[gn][Kn]=15,b}const xs=ad(Z.createInt32Array(6,6));class Mn{constructor(e,n,i,s){this.token=e,this.mode=n,this.binaryShiftByteCount=i,this.bitCount=s}getMode(){return this.mode}getToken(){return this.token}getBinaryShiftByteCount(){return this.binaryShiftByteCount}getBitCount(){return this.bitCount}latchAndAppend(e,n){let i=this.bitCount,s=this.token;if(e!==this.mode){let l=eo[this.mode][e];s=Lr(s,l&65535,l>>16),i+=l>>16}let a=e===gn?4:5;return s=Lr(s,n,a),new Mn(s,e,0,i+a)}shiftAndAppend(e,n){let i=this.token,s=this.mode===gn?4:5;return i=Lr(i,xs[this.mode][e],s),i=Lr(i,n,5),new Mn(i,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,i=this.mode,s=this.bitCount;if(this.mode===Rn||this.mode===gn){let d=eo[i][Kn];n=Lr(n,d&65535,d>>16),s+=d>>16,i=Kn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Mn(n,i,this.binaryShiftByteCount+1,s+a);return l.binaryShiftByteCount===2078&&(l=l.endBinaryShift(e+1)),l}endBinaryShift(e){if(this.binaryShiftByteCount===0)return this;let n=this.token;return n=id(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Mn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(eo[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Mn.calculateBinaryShiftCost(e)-Mn.calculateBinaryShiftCost(this):this.binaryShiftByteCount>e.binaryShiftByteCount&&e.binaryShiftByteCount>0&&(n+=10),n<=e.bitCount}toBitArray(e){let n=[];for(let s=this.endBinaryShift(e.length).token;s!==null;s=s.getPrevious())n.unshift(s);let i=new ee;for(const s of n)s.appendTo(i,e);return i}toString(){return re.format("%s bits=%d bytes=%d",od[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Mn.INITIAL_STATE=new Mn(sd,Kn,0,0);function ld(b){const e=re.getCharCode(" "),n=re.getCharCode("."),i=re.getCharCode(",");b[Kn][e]=1;const s=re.getCharCode("Z"),a=re.getCharCode("A");for(let I=a;I<=s;I++)b[Kn][I]=I-a+2;b[fi][e]=1;const l=re.getCharCode("z"),d=re.getCharCode("a");for(let I=d;I<=l;I++)b[fi][I]=I-d+2;b[gn][e]=1;const h=re.getCharCode("9"),p=re.getCharCode("0");for(let I=p;I<=h;I++)b[gn][I]=I-p+2;b[gn][i]=12,b[gn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
75
- `,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)b[gs][re.getCharCode(y[I])]=I;const E=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<E.length;I++)re.getCharCode(E[I])>0&&(b[Rn][re.getCharCode(E[I])]=I);return b}const to=ld(Z.createInt32Array(5,256));class Fr{constructor(e){this.text=e}encode(){const e=re.getCharCode(" "),n=re.getCharCode(`
76
- `);let i=ms.singletonList(Mn.INITIAL_STATE);for(let a=0;a<this.text.length;a++){let l,d=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case re.getCharCode("\r"):l=d===n?2:0;break;case re.getCharCode("."):l=d===e?3:0;break;case re.getCharCode(","):l=d===e?4:0;break;case re.getCharCode(":"):l=d===e?5:0;break;default:l=0}l>0?(i=Fr.updateStateListForPair(i,a,l),a++):i=this.updateStateListForChar(i,a)}return ms.min(i,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const i=[];for(let s of e)this.updateStateForChar(s,n,i);return Fr.simplifyStates(i)}updateStateForChar(e,n,i){let s=this.text[n]&255,a=to[e.getMode()][s]>0,l=null;for(let d=0;d<=Rn;d++){let h=to[d][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||d===e.getMode()||d===gn){const p=l.latchAndAppend(d,h);i.push(p)}if(!a&&xs[e.getMode()][d]>=0){const p=l.shiftAndAppend(d,h);i.push(p)}}}if(e.getBinaryShiftByteCount()>0||to[e.getMode()][s]===0){let d=e.addBinaryShiftChar(n);i.push(d)}}static updateStateListForPair(e,n,i){const s=[];for(let a of e)this.updateStateForPair(a,n,i,s);return this.simplifyStates(s)}static updateStateForPair(e,n,i,s){let a=e.endBinaryShift(n);if(s.push(a.latchAndAppend(Rn,i)),e.getMode()!==Rn&&s.push(a.shiftAndAppend(Rn,i)),i===3||i===4){let l=a.latchAndAppend(gn,16-i).latchAndAppend(gn,1);s.push(l)}if(e.getBinaryShiftByteCount()>0){let l=e.addBinaryShiftChar(n).addBinaryShiftChar(n+1);s.push(l)}}static simplifyStates(e){let n=[];for(const i of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(i)){s=!1;break}i.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(i)}return n}}class Ge{constructor(){}static encodeBytes(e){return Ge.encode(e,Ge.DEFAULT_EC_PERCENT,Ge.DEFAULT_AZTEC_LAYERS)}static encode(e,n,i){let s=new Fr(e).encode(),a=z.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,d,h,p,y,E;if(i!==Ge.DEFAULT_AZTEC_LAYERS){if(d=i<0,h=Math.abs(i),h>(d?Ge.MAX_NB_BITS_COMPACT:Ge.MAX_NB_BITS))throw new v(re.format("Illegal value %s for layers",i));p=Ge.totalBitsInLayer(h,d),y=Ge.WORD_SIZE[h];let ae=p-p%y;if(E=Ge.stuffBits(s,y),E.getSize()+a>ae)throw new v("Data to large for user specified layer");if(d&&E.getSize()>y*64)throw new v("Data to large for user specified layer")}else{y=0,E=null;for(let ae=0;;ae++){if(ae>Ge.MAX_NB_BITS)throw new v("Data too large for an Aztec code");if(d=ae<=3,h=d?ae+1:ae,p=Ge.totalBitsInLayer(h,d),l>p)continue;(E==null||y!==Ge.WORD_SIZE[h])&&(y=Ge.WORD_SIZE[h],E=Ge.stuffBits(s,y));let We=p-p%y;if(!(d&&E.getSize()>y*64)&&E.getSize()+a<=We)break}}let I=Ge.generateCheckWords(E,p,y),k=E.getSize()/y,L=Ge.generateModeMessage(d,h,k),F=(d?11:14)+h*4,H=new Int32Array(F),Y;if(d){Y=F;for(let ae=0;ae<H.length;ae++)H[ae]=ae}else{Y=F+1+2*z.truncDivision(z.truncDivision(F,2)-1,15);let ae=z.truncDivision(F,2),We=z.truncDivision(Y,2);for(let Fe=0;Fe<ae;Fe++){let nn=Fe+z.truncDivision(Fe,15);H[ae-Fe-1]=We-nn-1,H[ae+Fe]=We+nn+1}}let le=new Me(Y);for(let ae=0,We=0;ae<h;ae++){let Fe=(h-ae)*4+(d?9:12);for(let nn=0;nn<Fe;nn++){let yn=nn*2;for(let rn=0;rn<2;rn++)I.get(We+yn+rn)&&le.set(H[ae*2+rn],H[ae*2+nn]),I.get(We+Fe*2+yn+rn)&&le.set(H[ae*2+nn],H[F-1-ae*2-rn]),I.get(We+Fe*4+yn+rn)&&le.set(H[F-1-ae*2-rn],H[F-1-ae*2-nn]),I.get(We+Fe*6+yn+rn)&&le.set(H[F-1-ae*2-nn],H[ae*2+rn])}We+=Fe*8}if(Ge.drawModeMessage(le,d,Y,L),d)Ge.drawBullsEye(le,z.truncDivision(Y,2),5);else{Ge.drawBullsEye(le,z.truncDivision(Y,2),7);for(let ae=0,We=0;ae<z.truncDivision(F,2)-1;ae+=15,We+=16)for(let Fe=z.truncDivision(Y,2)&1;Fe<Y;Fe+=2)le.set(z.truncDivision(Y,2)-We,Fe),le.set(z.truncDivision(Y,2)+We,Fe),le.set(Fe,z.truncDivision(Y,2)-We),le.set(Fe,z.truncDivision(Y,2)+We)}let ce=new ps;return ce.setCompact(d),ce.setSize(Y),ce.setLayers(h),ce.setCodeWords(k),ce.setMatrix(le),ce}static drawBullsEye(e,n,i){for(let s=0;s<i;s+=2)for(let a=n-s;a<=n+s;a++)e.set(a,n-s),e.set(a,n+s),e.set(n-s,a),e.set(n+s,a);e.set(n-i,n-i),e.set(n-i+1,n-i),e.set(n-i,n-i+1),e.set(n+i,n-i),e.set(n+i,n-i+1),e.set(n+i,n+i-1)}static generateModeMessage(e,n,i){let s=new ee;return e?(s.appendBits(n-1,2),s.appendBits(i-1,6),s=Ge.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(i-1,11),s=Ge.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,i,s){let a=z.truncDivision(i,2);if(n)for(let l=0;l<7;l++){let d=a-3+l;s.get(l)&&e.set(d,a-5),s.get(l+7)&&e.set(a+5,d),s.get(20-l)&&e.set(d,a+5),s.get(27-l)&&e.set(a-5,d)}else for(let l=0;l<10;l++){let d=a-5+l+z.truncDivision(l,5);s.get(l)&&e.set(d,a-7),s.get(l+10)&&e.set(a+7,d),s.get(29-l)&&e.set(d,a+7),s.get(39-l)&&e.set(a-7,d)}}static generateCheckWords(e,n,i){let s=e.getSize()/i,a=new Yi(Ge.getGF(i)),l=z.truncDivision(n,i),d=Ge.bitsToWords(e,i,l);a.encode(d,l-s);let h=n%i,p=new ee;p.appendBits(0,h);for(const y of Array.from(d))p.appendBits(y,i);return p}static bitsToWords(e,n,i){let s=new Int32Array(i),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let d=0;for(let h=0;h<n;h++)d|=e.get(a*n+h)?1<<n-h-1:0;s[a]=d}return s}static getGF(e){switch(e){case 4:return be.AZTEC_PARAM;case 6:return be.AZTEC_DATA_6;case 8:return be.AZTEC_DATA_8;case 10:return be.AZTEC_DATA_10;case 12:return be.AZTEC_DATA_12;default:throw new v("Unsupported word size "+e)}}static stuffBits(e,n){let i=new ee,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let d=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(d|=1<<n-1-h);(d&a)===a?(i.appendBits(d&a,n),l--):(d&a)===0?(i.appendBits(d|1,n),l--):i.appendBits(d,n)}return i}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Ge.DEFAULT_EC_PERCENT=33,Ge.DEFAULT_AZTEC_LAYERS=0,Ge.MAX_NB_BITS=32,Ge.MAX_NB_BITS_COMPACT=4,Ge.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);class hi{encode(e,n,i,s){return this.encodeWithHints(e,n,i,s,null)}encodeWithHints(e,n,i,s,a){let l=Ji.ISO_8859_1,d=Ge.DEFAULT_EC_PERCENT,h=Ge.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Dt.CHARACTER_SET)&&(l=hs.forName(a.get(Dt.CHARACTER_SET).toString())),a.has(Dt.ERROR_CORRECTION)&&(d=z.parseInt(a.get(Dt.ERROR_CORRECTION).toString())),a.has(Dt.AZTEC_LAYERS)&&(h=z.parseInt(a.get(Dt.AZTEC_LAYERS).toString()))),hi.encodeLayers(e,n,i,s,l,d,h)}static encodeLayers(e,n,i,s,a,l,d){if(n!==Ce.AZTEC)throw new v("Can only encode AZTEC, but got "+n);let h=Ge.encode(re.getBytes(e,a),l,d);return hi.renderResult(h,i,s)}static renderResult(e,n,i){let s=e.getMatrix();if(s==null)throw new Wt;let a=s.getWidth(),l=s.getHeight(),d=Math.max(n,a),h=Math.max(i,l),p=Math.min(d/a,h/l),y=(d-a*p)/2,E=(h-l*p)/2,I=new Me(d,h);for(let k=0,L=E;k<l;k++,L+=p)for(let F=0,H=y;F<a;F++,H+=p)s.get(F,k)&&I.setRegion(H,L,p,p);return I}}o.AbstractExpandedDecoder=zi,o.ArgumentException=A,o.ArithmeticException=yt,o.AztecCode=ps,o.AztecCodeReader=lt,o.AztecCodeWriter=hi,o.AztecDecoder=Xe,o.AztecDetector=qe,o.AztecDetectorResult=Hn,o.AztecEncoder=Ge,o.AztecHighLevelEncoder=Fr,o.AztecPoint=oe,o.BarcodeFormat=Ce,o.Binarizer=M,o.BinaryBitmap=P,o.BitArray=ee,o.BitMatrix=Me,o.BitSource=Hi,o.BrowserAztecCodeReader=xr,o.BrowserBarcodeReader=Uu,o.BrowserCodeReader=vt,o.BrowserDatamatrixCodeReader=Vu,o.BrowserMultiFormatReader=Ju,o.BrowserPDF417Reader=Qu,o.BrowserQRCodeReader=ed,o.BrowserQRCodeSvgWriter=lr,o.CharacterSetECI=S,o.ChecksumException=O,o.Code128Reader=he,o.Code39Reader=Nt,o.DataMatrixDecodedBitStreamParser=Gn,o.DataMatrixReader=Xn,o.DecodeHintType=V,o.DecoderResult=Ht,o.DefaultGridSampler=rr,o.DetectorResult=Bn,o.EAN13Reader=Ln,o.EncodeHintType=Dt,o.Exception=x,o.FormatException=U,o.GenericGF=be,o.GenericGFPoly=Oe,o.GlobalHistogramBinarizer=ge,o.GridSampler=Wn,o.GridSamplerInstance=R,o.HTMLCanvasElementLuminanceSource=fe,o.HybridBinarizer=ne,o.ITFReader=nt,o.IllegalArgumentException=v,o.IllegalStateException=Wt,o.InvertedLuminanceSource=me,o.LuminanceSource=Q,o.MathUtils=Ze,o.MultiFormatOneDReader=vr,o.MultiFormatReader=fs,o.MultiFormatWriter=nd,o.NotFoundException=$,o.OneDReader=bt,o.PDF417DecodedBitStreamParser=q,o.PDF417DecoderErrorCorrection=ss,o.PDF417Reader=Zt,o.PDF417ResultMetadata=ls,o.PerspectiveTransform=Bt,o.PlanarYUVLuminanceSource=kn,o.QRCodeByteMatrix=di,o.QRCodeDataMask=pn,o.QRCodeDecodedBitStreamParser=wt,o.QRCodeDecoderErrorCorrectionLevel=ct,o.QRCodeDecoderFormatInformation=Gt,o.QRCodeEncoder=dt,o.QRCodeEncoderQRCode=ar,o.QRCodeMaskUtil=At,o.QRCodeMatrixUtil=Re,o.QRCodeMode=Ne,o.QRCodeReader=qn,o.QRCodeVersion=Ie,o.QRCodeWriter=br,o.RGBLuminanceSource=Ki,o.RSS14Reader=Et,o.RSSExpandedReader=se,o.ReaderException=ui,o.ReedSolomonDecoder=In,o.ReedSolomonEncoder=Yi,o.ReedSolomonException=Xt,o.Result=Ee,o.ResultMetadataType=Ue,o.ResultPoint=ve,o.StringUtils=re,o.UnsupportedOperationException=Te,o.VideoInputDevice=ie,o.WhiteRectangleDetector=Jt,o.WriterException=ot,o.ZXingArrays=Z,o.ZXingCharset=hs,o.ZXingInteger=z,o.ZXingStandardCharsets=Ji,o.ZXingStringBuilder=xe,o.ZXingStringEncoding=ye,o.ZXingSystem=D,o.createAbstractExpandedDecoder=is,Object.defineProperty(o,"__esModule",{value:!0})}))})(Hr,Hr.exports)),Hr.exports}var ft=Ny();const Oy=Sy(ft),ky=pd({__proto__:null,default:Oy},[ft]);var tl=(function(){function t(r,o,c){if(this.formatMap=new Map([[_e.QR_CODE,ft.BarcodeFormat.QR_CODE],[_e.AZTEC,ft.BarcodeFormat.AZTEC],[_e.CODABAR,ft.BarcodeFormat.CODABAR],[_e.CODE_39,ft.BarcodeFormat.CODE_39],[_e.CODE_93,ft.BarcodeFormat.CODE_93],[_e.CODE_128,ft.BarcodeFormat.CODE_128],[_e.DATA_MATRIX,ft.BarcodeFormat.DATA_MATRIX],[_e.MAXICODE,ft.BarcodeFormat.MAXICODE],[_e.ITF,ft.BarcodeFormat.ITF],[_e.EAN_13,ft.BarcodeFormat.EAN_13],[_e.EAN_8,ft.BarcodeFormat.EAN_8],[_e.PDF_417,ft.BarcodeFormat.PDF_417],[_e.RSS_14,ft.BarcodeFormat.RSS_14],[_e.RSS_EXPANDED,ft.BarcodeFormat.RSS_EXPANDED],[_e.UPC_A,ft.BarcodeFormat.UPC_A],[_e.UPC_E,ft.BarcodeFormat.UPC_E],[_e.UPC_EAN_EXTENSION,ft.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!ky)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=o,this.logger=c;var u=this.createZXingFormats(r),f=new Map;f.set(ft.DecodeHintType.POSSIBLE_FORMATS,u),f.set(ft.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var o=this;return new Promise(function(c,u){try{c(o.decode(r))}catch(f){u(f)}})},t.prototype.decode=function(r){var o=new ft.MultiFormatReader(this.verbose,this.hints),c=new ft.HTMLCanvasElementLuminanceSource(r),u=new ft.BinaryBitmap(new ft.HybridBinarizer(c)),f=o.decode(u);return{text:f.text,format:ku.create(this.toHtml5QrcodeSupportedFormats(f.format)),debugData:this.createDebugData()}},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(o,c,u){r.set(o,c)}),r},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createZXingFormats=function(r){for(var o=[],c=0,u=r;c<u.length;c++){var f=u[c];this.formatMap.has(f)?o.push(this.formatMap.get(f)):this.logger.logError("".concat(f," is not supported by")+"ZXingHtml5QrcodeShim")}return o},t.prototype.createDebugData=function(){return{decoderName:"zxing-js"}},t})(),Ry=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function g(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},My=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(A){return C([x,A])}}function C(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},nl=(function(){function t(r,o,c){if(this.formatMap=new Map([[_e.QR_CODE,"qr_code"],[_e.AZTEC,"aztec"],[_e.CODABAR,"codabar"],[_e.CODE_39,"code_39"],[_e.CODE_93,"code_93"],[_e.CODE_128,"code_128"],[_e.DATA_MATRIX,"data_matrix"],[_e.ITF,"itf"],[_e.EAN_13,"ean_13"],[_e.EAN_8,"ean_8"],[_e.PDF_417,"pdf417"],[_e.UPC_A,"upc_a"],[_e.UPC_E,"upc_e"]]),this.reverseFormatMap=this.createReverseFormatMap(),!t.isSupported())throw"Use html5qrcode.min.js without edit, Use BarcodeDetectorDelegate only if it isSupported();";this.verbose=o,this.logger=c;var u=this.createBarcodeDetectorFormats(r);if(this.detector=new BarcodeDetector(u),!this.detector)throw"BarcodeDetector detector not supported"}return t.isSupported=function(){if(!("BarcodeDetector"in window))return!1;var r=new BarcodeDetector({formats:["qr_code"]});return typeof r<"u"},t.prototype.decodeAsync=function(r){return Ry(this,void 0,void 0,function(){var o,c;return My(this,function(u){switch(u.label){case 0:return[4,this.detector.detect(r)];case 1:if(o=u.sent(),!o||o.length===0)throw"No barcode or QR code detected.";return c=this.selectLargestBarcode(o),[2,{text:c.rawValue,format:ku.create(this.toHtml5QrcodeSupportedFormats(c.format)),debugData:this.createDebugData()}]}})})},t.prototype.selectLargestBarcode=function(r){for(var o=null,c=0,u=0,f=r;u<f.length;u++){var m=f[u],g=m.boundingBox.width*m.boundingBox.height;g>c&&(c=g,o=m)}if(!o)throw"No largest barcode found";return o},t.prototype.createBarcodeDetectorFormats=function(r){for(var o=[],c=0,u=r;c<u.length;c++){var f=u[c];this.formatMap.has(f)?o.push(this.formatMap.get(f)):this.logger.warn("".concat(f," is not supported by")+"BarcodeDetectorDelegate")}return{formats:o}},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(o,c,u){r.set(o,c)}),r},t.prototype.createDebugData=function(){return{decoderName:"BarcodeDetector"}},t})(),rl=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function g(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},il=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(A){return C([x,A])}}function C(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Dy=(function(){function t(r,o,c,u){this.EXECUTIONS_TO_REPORT_PERFORMANCE=100,this.executions=0,this.executionResults=[],this.wasPrimaryDecoderUsedInLastDecode=!1,this.verbose=c,o&&nl.isSupported()?(this.primaryDecoder=new nl(r,c,u),this.secondaryDecoder=new tl(r,c,u)):this.primaryDecoder=new tl(r,c,u)}return t.prototype.decodeAsync=function(r){return rl(this,void 0,void 0,function(){var o;return il(this,function(c){switch(c.label){case 0:o=performance.now(),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,this.getDecoder().decodeAsync(r)];case 2:return[2,c.sent()];case 3:return this.possiblyLogPerformance(o),[7];case 4:return[2]}})})},t.prototype.decodeRobustlyAsync=function(r){return rl(this,void 0,void 0,function(){var o,c;return il(this,function(u){switch(u.label){case 0:o=performance.now(),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,this.primaryDecoder.decodeAsync(r)];case 2:return[2,u.sent()];case 3:if(c=u.sent(),this.secondaryDecoder)return[2,this.secondaryDecoder.decodeAsync(r)];throw c;case 4:return this.possiblyLogPerformance(o),[7];case 5:return[2]}})})},t.prototype.getDecoder=function(){return this.secondaryDecoder?this.wasPrimaryDecoderUsedInLastDecode===!1?(this.wasPrimaryDecoderUsedInLastDecode=!0,this.primaryDecoder):(this.wasPrimaryDecoderUsedInLastDecode=!1,this.secondaryDecoder):this.primaryDecoder},t.prototype.possiblyLogPerformance=function(r){if(this.verbose){var o=performance.now()-r;this.executionResults.push(o),this.executions++,this.possiblyFlushPerformanceReport()}},t.prototype.possiblyFlushPerformanceReport=function(){if(!(this.executions<this.EXECUTIONS_TO_REPORT_PERFORMANCE)){for(var r=0,o=0,c=this.executionResults;o<c.length;o++){var u=c[o];r+=u}var f=r/this.executionResults.length;console.log("".concat(f," ms for ").concat(this.executionResults.length," last runs.")),this.executions=0,this.executionResults=[]}},t})(),Qo=(function(){var t=function(r,o){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,u){c.__proto__=u}||function(c,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(c[f]=u[f])},t(r,o)};return function(r,o){if(typeof o!="function"&&o!==null)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");t(r,o);function c(){this.constructor=r}r.prototype=o===null?Object.create(o):(c.prototype=o.prototype,new c)}})(),ki=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function g(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},Ri=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(A){return C([x,A])}}function C(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Mu=(function(){function t(r,o){this.name=r,this.track=o}return t.prototype.isSupported=function(){return this.track.getCapabilities?this.name in this.track.getCapabilities():!1},t.prototype.apply=function(r){var o={};o[this.name]=r;var c={advanced:[o]};return this.track.applyConstraints(c)},t.prototype.value=function(){var r=this.track.getSettings();if(this.name in r){var o=r[this.name];return o}return null},t})(),Py=(function(t){Qo(r,t);function r(o,c){return t.call(this,o,c)||this}return r.prototype.min=function(){return this.getCapabilities().min},r.prototype.max=function(){return this.getCapabilities().max},r.prototype.step=function(){return this.getCapabilities().step},r.prototype.apply=function(o){var c={};c[this.name]=o;var u={advanced:[c]};return this.track.applyConstraints(u)},r.prototype.getCapabilities=function(){this.failIfNotSupported();var o=this.track.getCapabilities(),c=o[this.name];return{min:c.min,max:c.max,step:c.step}},r.prototype.failIfNotSupported=function(){if(!this.isSupported())throw new Error("".concat(this.name," capability not supported"))},r})(Mu),By=(function(t){Qo(r,t);function r(o){return t.call(this,"zoom",o)||this}return r})(Py),Ly=(function(t){Qo(r,t);function r(o){return t.call(this,"torch",o)||this}return r})(Mu),Fy=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new By(this.track)},t.prototype.torchFeature=function(){return new Ly(this.track)},t})(),Uy=(function(){function t(r,o,c){this.isClosed=!1,this.parentElement=r,this.mediaStream=o,this.callbacks=c,this.surface=this.createVideoElement(this.parentElement.clientWidth),r.append(this.surface)}return t.prototype.createVideoElement=function(r){var o=document.createElement("video");return o.style.width="".concat(r,"px"),o.style.display="block",o.muted=!0,o.setAttribute("muted","true"),o.playsInline=!0,o},t.prototype.setupSurface=function(){var r=this;this.surface.onabort=function(){throw"RenderedCameraImpl video surface onabort() called"},this.surface.onerror=function(){throw"RenderedCameraImpl video surface onerror() called"};var o=function(){var c=r.surface.clientWidth,u=r.surface.clientHeight;r.callbacks.onRenderSurfaceReady(c,u),r.surface.removeEventListener("playing",o)};this.surface.addEventListener("playing",o),this.surface.srcObject=this.mediaStream,this.surface.play()},t.create=function(r,o,c,u){return ki(this,void 0,void 0,function(){var f,m;return Ri(this,function(g){switch(g.label){case 0:return f=new t(r,o,u),c.aspectRatio?(m={aspectRatio:c.aspectRatio},[4,f.getFirstTrackOrFail().applyConstraints(m)]):[3,2];case 1:g.sent(),g.label=2;case 2:return f.setupSurface(),[2,f]}})})},t.prototype.failIfClosed=function(){if(this.isClosed)throw"The RenderedCamera has already been closed."},t.prototype.getFirstTrackOrFail=function(){if(this.failIfClosed(),this.mediaStream.getVideoTracks().length===0)throw"No video tracks found";return this.mediaStream.getVideoTracks()[0]},t.prototype.pause=function(){this.failIfClosed(),this.surface.pause()},t.prototype.resume=function(r){this.failIfClosed();var o=this,c=function(){setTimeout(r,200),o.surface.removeEventListener("playing",c)};this.surface.addEventListener("playing",c),this.surface.play()},t.prototype.isPaused=function(){return this.failIfClosed(),this.surface.paused},t.prototype.getSurface=function(){return this.failIfClosed(),this.surface},t.prototype.getRunningTrackCapabilities=function(){return this.getFirstTrackOrFail().getCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getFirstTrackOrFail().getSettings()},t.prototype.applyVideoConstraints=function(r){return ki(this,void 0,void 0,function(){return Ri(this,function(o){if("aspectRatio"in r)throw"Changing 'aspectRatio' in run-time is not yet supported.";return[2,this.getFirstTrackOrFail().applyConstraints(r)]})})},t.prototype.close=function(){if(this.isClosed)return Promise.resolve();var r=this;return new Promise(function(o,c){var u=r.mediaStream.getVideoTracks(),f=u.length,m=0;r.mediaStream.getVideoTracks().forEach(function(g){r.mediaStream.removeTrack(g),g.stop(),++m,m>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),o())})})},t.prototype.getCapabilities=function(){return new Fy(this.getFirstTrackOrFail())},t})(),zy=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,o,c){return ki(this,void 0,void 0,function(){return Ri(this,function(u){return[2,Uy.create(r,this.mediaStream,o,c)]})})},t.create=function(r){return ki(this,void 0,void 0,function(){var o,c;return Ri(this,function(u){switch(u.label){case 0:if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return o={audio:!1,video:r},[4,navigator.mediaDevices.getUserMedia(o)];case 1:return c=u.sent(),[2,new t(c)]}})})},t})(),ol=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function g(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},sl=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(A){return C([x,A])}}function C(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Vy=(function(){function t(){}return t.failIfNotSupported=function(){return ol(this,void 0,void 0,function(){return sl(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return ol(this,void 0,void 0,function(){return sl(this,function(o){return[2,zy.create(r)]})})},t})(),Zy=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function g(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},$y=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(A){return C([x,A])}}function C(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Hy=(function(){function t(){}return t.retrieve=function(){if(navigator.mediaDevices)return t.getCamerasFromMediaDevices();var r=MediaStreamTrack;return MediaStreamTrack&&r.getSources?t.getCamerasFromMediaStreamTrack():t.rejectWithError()},t.rejectWithError=function(){var r=Nr.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Nr.insecureContextCameraQueryError()),Promise.reject(r)},t.isHttpsOrLocalhost=function(){if(location.protocol==="https:")return!0;var r=location.host.split(":")[0];return r==="127.0.0.1"||r==="localhost"},t.getCamerasFromMediaDevices=function(){return Zy(this,void 0,void 0,function(){var r,o,c,u,f,m,g;return $y(this,function(C){switch(C.label){case 0:return r=function(x){for(var A=x.getVideoTracks(),v=0,P=A;v<P.length;v++){var O=P[v];O.enabled=!1,O.stop(),x.removeTrack(O)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return o=C.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=C.sent(),u=[],f=0,m=c;f<m.length;f++)g=m[f],g.kind==="videoinput"&&u.push({id:g.deviceId,label:g.label});return r(o),[2,u]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,o){var c=function(f){for(var m=[],g=0,C=f;g<C.length;g++){var x=C[g];x.kind==="video"&&m.push({id:x.id,label:x.label})}r(m)},u=MediaStreamTrack;u.getSources(c)})},t})(),It;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(It||(It={}));var Wy=(function(){function t(){this.state=It.NOT_STARTED,this.onGoingTransactionNewState=It.UNKNOWN}return t.prototype.directTransition=function(r){this.failIfTransitionOngoing(),this.validateTransition(r),this.state=r},t.prototype.startTransition=function(r){return this.failIfTransitionOngoing(),this.validateTransition(r),this.onGoingTransactionNewState=r,this},t.prototype.execute=function(){if(this.onGoingTransactionNewState===It.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=It.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===It.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=It.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==It.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case It.UNKNOWN:throw"Transition from unknown is not allowed";case It.NOT_STARTED:this.failIfNewStateIs(r,[It.PAUSED]);break;case It.SCANNING:break;case It.PAUSED:break}},t.prototype.failIfNewStateIs=function(r,o){for(var c=0,u=o;c<u.length;c++){var f=u[c];if(r===f)throw"Cannot transition from ".concat(this.state," to ").concat(r)}},t})(),jy=(function(){function t(r){this.stateManager=r}return t.prototype.startTransition=function(r){return this.stateManager.startTransition(r)},t.prototype.directTransition=function(r){this.stateManager.directTransition(r)},t.prototype.getState=function(){return this.stateManager.getState()},t.prototype.canScanFile=function(){return this.stateManager.getState()===It.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==It.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===It.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===It.PAUSED},t})(),Gy=(function(){function t(){}return t.create=function(){return new jy(new Wy)},t})(),Xy=(function(){var t=function(r,o){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,u){c.__proto__=u}||function(c,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(c[f]=u[f])},t(r,o)};return function(r,o){if(typeof o!="function"&&o!==null)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");t(r,o);function c(){this.constructor=r}r.prototype=o===null?Object.create(o):(c.prototype=o.prototype,new c)}})(),ln=(function(t){Xy(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.DEFAULT_WIDTH=300,r.DEFAULT_WIDTH_OFFSET=2,r.FILE_SCAN_MIN_HEIGHT=300,r.FILE_SCAN_HIDDEN_CANVAS_PADDING=100,r.MIN_QR_BOX_SIZE=50,r.SHADED_LEFT=1,r.SHADED_RIGHT=2,r.SHADED_TOP=3,r.SHADED_BOTTOM=4,r.SHADED_REGION_ELEMENT_ID="qr-shaded-region",r.VERBOSE=!1,r.BORDER_SHADER_DEFAULT_COLOR="#ffffff",r.BORDER_SHADER_MATCH_COLOR="rgb(90, 193, 56)",r})(Ey),qy=(function(){function t(r,o){this.logger=o,this.fps=ln.SCAN_DEFAULT_FPS,r?(r.fps&&(this.fps=r.fps),this.disableFlip=r.disableFlip===!0,this.qrbox=r.qrbox,this.aspectRatio=r.aspectRatio,this.videoConstraints=r.videoConstraints):this.disableFlip=ln.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Ru.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!Fn(this.qrbox)},t.create=function(r,o){return new t(r,o)},t})(),al=(function(){function t(r,o){if(this.element=null,this.canvasElement=null,this.scannerPausedUiElement=null,this.hasBorderShaders=null,this.borderShaders=null,this.qrMatch=null,this.renderedCamera=null,this.qrRegion=null,this.context=null,this.lastScanImageFile=null,this.isScanning=!1,!document.getElementById(r))throw"HTML Element with id=".concat(r," not found");this.elementId=r,this.verbose=!1;var c;typeof o=="boolean"?this.verbose=o===!0:o&&(c=o,this.verbose=c.verbose===!0,c.experimentalFeatures),this.logger=new Iy(this.verbose),this.qrcode=new Dy(this.getSupportedFormats(o),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Gy.create()}return t.prototype.start=function(r,o,c,u){var f=this;if(!r)throw"cameraIdOrConfig is required";if(!c||typeof c!="function")throw"qrCodeSuccessCallback is required and should be a function.";var m;u?m=u:m=this.verbose?this.logger.log:function(){};var g=qy.create(o,this.logger);this.clearElement();var C=!1;g.videoConstraints&&(g.isMediaStreamConstraintsValid()?C=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var x=C,A=document.getElementById(this.elementId);A.clientWidth?A.clientWidth:ln.DEFAULT_WIDTH,A.style.position="relative",this.shouldScan=!0,this.element=A;var v=this,P=this.stateManagerProxy.startTransition(It.SCANNING);return new Promise(function(O,M){var D=x?g.videoConstraints:v.createVideoConstraints(r);if(!D){P.cancel(),M("videoConstraints should be defined");return}var B={};(!x||g.aspectRatio)&&(B.aspectRatio=g.aspectRatio);var G={onRenderSurfaceReady:function(Z,z){v.setupUi(Z,z,g),v.isScanning=!0,v.foreverScan(g,c,m)}};Vy.failIfNotSupported().then(function(Z){Z.create(D).then(function(z){return z.render(f.element,B,G).then(function(ee){v.renderedCamera=ee,P.execute(),O(null)}).catch(function(ee){P.cancel(),M(ee)})}).catch(function(z){P.cancel(),M(Nr.errorGettingUserMedia(z))})}).catch(function(Z){P.cancel(),M(Nr.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(It.PAUSED),this.showPausedState(),(Fn(r)||r!==!0)&&(r=!1),r&&this.renderedCamera&&this.renderedCamera.pause()},t.prototype.resume=function(){if(!this.stateManagerProxy.isPaused())throw"Cannot result, scanner is not paused.";if(!this.renderedCamera)throw"renderedCamera doesn't exist while trying resume()";var r=this,o=function(){r.stateManagerProxy.directTransition(It.SCANNING),r.hidePausedState()};if(!this.renderedCamera.isPaused()){o();return}this.renderedCamera.resume(function(){o()})},t.prototype.getState=function(){return this.stateManagerProxy.getState()},t.prototype.stop=function(){var r=this;if(!this.stateManagerProxy.isScanning())throw"Cannot stop, scanner is not running or paused.";var o=this.stateManagerProxy.startTransition(It.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(ln.SHADED_REGION_ELEMENT_ID);f&&r.element.removeChild(f)}},u=this;return this.renderedCamera.close().then(function(){return u.renderedCamera=null,u.element&&(u.element.removeChild(u.canvasElement),u.canvasElement=null),c(),u.qrRegion&&(u.qrRegion=null),u.context&&(u.context=null),o.execute(),u.hidePausedState(),u.isScanning=!1,Promise.resolve()})},t.prototype.scanFile=function(r,o){return this.scanFileV2(r,o).then(function(c){return c.decodedText})},t.prototype.scanFileV2=function(r,o){var c=this;if(!r||!(r instanceof File))throw"imageFile argument is mandatory and should be instance of File. Use 'event.target.files[0]'.";if(Fn(o)&&(o=!0),!this.stateManagerProxy.canScanFile())throw"Cannot start file scan - ongoing camera scan";return new Promise(function(u,f){c.possiblyCloseLastScanImageFile(),c.clearElement(),c.lastScanImageFile=URL.createObjectURL(r);var m=new Image;m.onload=function(){var g=m.width,C=m.height,x=document.getElementById(c.elementId),A=x.clientWidth?x.clientWidth:ln.DEFAULT_WIDTH,v=Math.max(x.clientHeight?x.clientHeight:C,ln.FILE_SCAN_MIN_HEIGHT),P=c.computeCanvasDrawConfig(g,C,A,v);if(o){var O=c.createCanvasElement(A,v,"qr-canvas-visible");O.style.display="inline-block",x.appendChild(O);var M=O.getContext("2d");if(!M)throw"Unable to get 2d context from canvas";M.canvas.width=A,M.canvas.height=v,M.drawImage(m,0,0,g,C,P.x,P.y,P.width,P.height)}var D=ln.FILE_SCAN_HIDDEN_CANVAS_PADDING,B=Math.max(m.width,P.width),G=Math.max(m.height,P.height),Z=B+2*D,z=G+2*D,ee=c.createCanvasElement(Z,z);x.appendChild(ee);var K=ee.getContext("2d");if(!K)throw"Unable to get 2d context from canvas";K.canvas.width=Z,K.canvas.height=z,K.drawImage(m,0,0,g,C,D,D,B,G);try{c.qrcode.decodeRobustlyAsync(ee).then(function(V){u(Qa.createFromQrcodeResult(V))}).catch(f)}catch(V){f("QR code parse error, error = ".concat(V))}},m.onerror=f,m.onabort=f,m.onstalled=f,m.onsuspend=f,m.src=URL.createObjectURL(r)})},t.prototype.clear=function(){this.clearElement()},t.getCameras=function(){return Hy.retrieve()},t.prototype.getRunningTrackCapabilities=function(){return this.getRenderedCameraOrFail().getRunningTrackCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getRenderedCameraOrFail().getRunningTrackSettings()},t.prototype.getRunningTrackCameraCapabilities=function(){return this.getRenderedCameraOrFail().getCapabilities()},t.prototype.applyVideoConstraints=function(r){if(r){if(!Ru.isMediaStreamConstraintsValid(r,this.logger))throw"invalid videoConstaints passed, check logs for more details"}else throw"videoConstaints is required argument.";return this.getRenderedCameraOrFail().applyVideoConstraints(r)},t.prototype.getRenderedCameraOrFail=function(){if(this.renderedCamera==null)throw"Scanning is not in running state, call this API only when QR code scanning using camera is in running state.";return this.renderedCamera},t.prototype.getSupportedFormats=function(r){var o=[_e.QR_CODE,_e.AZTEC,_e.CODABAR,_e.CODE_39,_e.CODE_93,_e.CODE_128,_e.DATA_MATRIX,_e.MAXICODE,_e.ITF,_e.EAN_13,_e.EAN_8,_e.PDF_417,_e.RSS_14,_e.RSS_EXPANDED,_e.UPC_A,_e.UPC_E,_e.UPC_EAN_EXTENSION];if(!r||typeof r=="boolean"||!r.formatsToSupport)return o;if(!Array.isArray(r.formatsToSupport))throw"configOrVerbosityFlag.formatsToSupport should be undefined or an array.";if(r.formatsToSupport.length===0)throw"Atleast 1 formatsToSupport is needed.";for(var c=[],u=0,f=r.formatsToSupport;u<f.length;u++){var m=f[u];by(m)?c.push(m):this.logger.warn("Invalid format: ".concat(m," passed in config, ignoring."))}if(c.length===0)throw"None of formatsToSupport match supported values.";return c},t.prototype.getUseBarCodeDetectorIfSupported=function(r){if(Fn(r))return!0;if(!Fn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(Fn(r.experimentalFeatures))return!0;var o=r.experimentalFeatures;return Fn(o.useBarCodeDetectorIfSupported)?!0:o.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,o,c){var u=this,f=c.qrbox;this.validateQrboxConfig(f);var m=this.toQrdimensions(r,o,f),g=function(x){if(x<ln.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(ln.MIN_QR_BOX_SIZE,"px.")},C=function(x){return x>r&&(u.logger.warn("`qrbox.width` or `qrbox` is larger than the width of the root element. The width will be truncated to the width of root element."),x=r),x};g(m.width),g(m.height),m.width=C(m.width)},t.prototype.validateQrboxConfig=function(r){if(typeof r!="number"&&typeof r!="function"&&(r.width===void 0||r.height===void 0))throw"Invalid instance of QrDimensions passed for 'config.qrbox'. Both 'width' and 'height' should be set."},t.prototype.toQrdimensions=function(r,o,c){if(typeof c=="number")return{width:c,height:c};if(typeof c=="function")try{return c(r,o)}catch(u){throw new Error("qrbox config was passed as a function but it failed with unknown error"+u)}return c},t.prototype.setupUi=function(r,o,c){c.isShadedBoxEnabled()&&this.validateQrboxSize(r,o,c);var u=Fn(c.qrbox)?{width:r,height:o}:c.qrbox;this.validateQrboxConfig(u);var f=this.toQrdimensions(r,o,u);f.height>o&&this.logger.warn("[Html5Qrcode] config.qrbox has height that isgreater than the height of the video stream. Shading will be ignored");var m=c.isShadedBoxEnabled()&&f.height<=o,g={x:0,y:0,width:r,height:o},C=m?this.getShadedRegionBounds(r,o,f):g,x=this.createCanvasElement(C.width,C.height),A={willReadFrequently:!0},v=x.getContext("2d",A);v.canvas.width=C.width,v.canvas.height=C.height,this.element.append(x),m&&this.possiblyInsertShadingElement(this.element,r,o,f),this.createScannerPausedUiElement(this.element),this.qrRegion=C,this.context=v,this.canvasElement=x},t.prototype.createScannerPausedUiElement=function(r){var o=document.createElement("div");o.innerText=Nr.scannerPaused(),o.style.display="none",o.style.position="absolute",o.style.top="0px",o.style.zIndex="1",o.style.background="rgba(9, 9, 9, 0.46)",o.style.color="#FFECEC",o.style.textAlign="center",o.style.width="100%",r.appendChild(o),this.scannerPausedUiElement=o},t.prototype.scanContext=function(r,o){var c=this;return this.stateManagerProxy.isPaused()?Promise.resolve(!1):this.qrcode.decodeAsync(this.canvasElement).then(function(u){return r(u.text,Qa.createFromQrcodeResult(u)),c.possiblyUpdateShaders(!0),!0}).catch(function(u){c.possiblyUpdateShaders(!1);var f=Nr.codeParseError(u);return o(f,Ay.createFrom(f)),!1})},t.prototype.foreverScan=function(r,o,c){var u=this;if(this.shouldScan&&this.renderedCamera){var f=this.renderedCamera.getSurface(),m=f.videoWidth/f.clientWidth,g=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var C=this.qrRegion.width*m,x=this.qrRegion.height*g,A=this.qrRegion.x*m,v=this.qrRegion.y*g;this.context.drawImage(f,A,v,C,x,0,0,this.qrRegion.width,this.qrRegion.height);var P=function(){u.foreverScanTimeout=setTimeout(function(){u.foreverScan(r,o,c)},u.getTimeoutFps(r.fps))};this.scanContext(o,c).then(function(O){!O&&r.disableFlip!==!0?(u.context.translate(u.context.canvas.width,0),u.context.scale(-1,1),u.scanContext(o,c).finally(function(){P()})):P()}).catch(function(O){u.logger.logError("Error happend while scanning context",O),P()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var o="facingMode",c="deviceId",u={user:!0,environment:!0},f="exact",m=function(M){if(M in u)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(M,"'")},g=Object.keys(r);if(g.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(g.length," keys");var C=Object.keys(r)[0];if(C!==o&&C!==c)throw"Only '".concat(o,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(C===o){var x=r.facingMode;if(typeof x=="string"){if(m(x))return{facingMode:x}}else if(typeof x=="object")if(f in x){if(m(x["".concat(f)]))return{facingMode:{exact:x["".concat(f)]}}}else throw"'facingMode' should be string or object with"+" ".concat(f," as key.");else{var A=typeof x;throw"Invalid type of 'facingMode' = ".concat(A)}}else{var v=r.deviceId;if(typeof v=="string")return{deviceId:v};if(typeof v=="object"){if(f in v)return{deviceId:{exact:v["".concat(f)]}};throw"'deviceId' should be string or object with"+" ".concat(f," as key.")}else{var P=typeof v;throw"Invalid type of 'deviceId' = ".concat(P)}}}var O=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(O)},t.prototype.computeCanvasDrawConfig=function(r,o,c,u){if(r<=c&&o<=u){var f=(c-r)/2,m=(u-o)/2;return{x:f,y:m,width:r,height:o}}else{var g=r,C=o;return r>c&&(o=c/r*o,r=c),o>u&&(r=u/o*r,o=u),this.logger.log("Image downsampled from "+"".concat(g,"X").concat(C)+" to ".concat(r,"X").concat(o,".")),this.computeCanvasDrawConfig(r,o,c,u)}},t.prototype.clearElement=function(){if(this.stateManagerProxy.isScanning())throw"Cannot clear while scan is ongoing, close it first.";var r=document.getElementById(this.elementId);r&&(r.innerHTML="")},t.prototype.possiblyUpdateShaders=function(r){this.qrMatch!==r&&(this.hasBorderShaders&&this.borderShaders&&this.borderShaders.length&&this.borderShaders.forEach(function(o){o.style.backgroundColor=r?ln.BORDER_SHADER_MATCH_COLOR:ln.BORDER_SHADER_DEFAULT_COLOR}),this.qrMatch=r)},t.prototype.possiblyCloseLastScanImageFile=function(){this.lastScanImageFile&&(URL.revokeObjectURL(this.lastScanImageFile),this.lastScanImageFile=null)},t.prototype.createCanvasElement=function(r,o,c){var u=r,f=o,m=document.createElement("canvas");return m.style.width="".concat(u,"px"),m.style.height="".concat(f,"px"),m.style.display="none",m.id=Fn(c)?"qr-canvas":c,m},t.prototype.getShadedRegionBounds=function(r,o,c){if(c.width>r||c.height>o)throw"'config.qrbox' dimensions should not be greater than the dimensions of the root HTML element.";return{x:(r-c.width)/2,y:(o-c.height)/2,width:c.width,height:c.height}},t.prototype.possiblyInsertShadingElement=function(r,o,c,u){if(!(o-u.width<1||c-u.height<1)){var f=document.createElement("div");f.style.position="absolute";var m=(o-u.width)/2,g=(c-u.height)/2;if(f.style.borderLeft="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderRight="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderTop="".concat(g,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(g,"px solid rgba(0, 0, 0, 0.48)"),f.style.boxSizing="border-box",f.style.top="0px",f.style.bottom="0px",f.style.left="0px",f.style.right="0px",f.id="".concat(ln.SHADED_REGION_ELEMENT_ID),o-u.width<11||c-u.height<11)this.hasBorderShaders=!1;else{var C=5,x=40;this.insertShaderBorders(f,x,C,-C,null,0,!0),this.insertShaderBorders(f,x,C,-C,null,0,!1),this.insertShaderBorders(f,x,C,null,-C,0,!0),this.insertShaderBorders(f,x,C,null,-C,0,!1),this.insertShaderBorders(f,C,x+C,-C,null,-C,!0),this.insertShaderBorders(f,C,x+C,null,-C,-C,!0),this.insertShaderBorders(f,C,x+C,-C,null,-C,!1),this.insertShaderBorders(f,C,x+C,null,-C,-C,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,o,c,u,f,m,g){var C=document.createElement("div");C.style.position="absolute",C.style.backgroundColor=ln.BORDER_SHADER_DEFAULT_COLOR,C.style.width="".concat(o,"px"),C.style.height="".concat(c,"px"),u!==null&&(C.style.top="".concat(u,"px")),f!==null&&(C.style.bottom="".concat(f,"px")),g?C.style.left="".concat(m,"px"):C.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(C),r.appendChild(C)},t.prototype.showPausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="block"},t.prototype.hidePausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="none"},t.prototype.getTimeoutFps=function(r){return 1e3/r},t})(),ll;(function(t){t[t.STATUS_DEFAULT=0]="STATUS_DEFAULT",t[t.STATUS_SUCCESS=1]="STATUS_SUCCESS",t[t.STATUS_WARNING=2]="STATUS_WARNING",t[t.STATUS_REQUESTING_PERMISSION=3]="STATUS_REQUESTING_PERMISSION"})(ll||(ll={}));const Yy={class:"scan-code"},Ky={class:"btn"},Jy={class:"left-back"},Qy=_.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const o=r,c=hd.IconScan(),u=_.reactive({html5QrCode:null}),f=_.ref(!1),m=()=>{if(!u.html5QrCode){Je("摄像头无访问权限!");return}f.value=!0,u.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[ei.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},v=>{try{const O=new URL(v).searchParams.get("sessionId");O?o("scanSuccess",O):Je("无效的二维码")}catch{Je("无效的二维码")}A()}).catch(v=>{console.log(v),Je({message:"二维码识别失败",duration:3e3})})},g=()=>{x().then(()=>{m()})},C=()=>{A()},x=()=>al.getCameras().then(v=>{v&&v.length&&(u.html5QrCode=new al("reader"))}).catch(()=>{Je({message:"摄像头无访问权限!",duration:3e3})}),A=()=>{u.html5QrCode&&u.html5QrCode.stop().then(v=>{console.log("停止扫码",v)}).catch(v=>{console.log(v),Je("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{u.html5QrCode&&u.html5QrCode.isScanning&&A()}),(v,P)=>{const O=Jo;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref(Ut.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:P[0]||(P[0]=M=>g())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",Yy,[P[1]||(P[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",Ky,[_.createElementVNode("div",Jy,[_.createVNode(O,{name:"arrow-left",onClick:C})])])],512),[[_.vShow,f.value]])]))])}}}),ew=nr(Qy,[["__scopeId","data-v-2d988579"]]);function es(t,r,o){const c=_.computed(()=>t?Array.isArray(t)?t:t.value:[]),u=()=>{const A=c.value;if(A.length===0)return"";if(r){const P=typeof r=="string"?r:r.value;if(P&&A.some(O=>O.id===P))return P}const v=A.find(P=>P.isDefault);return v?v.id:A[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(A=>A.id===f.value))&&(f.value=u());else{let A;r&&typeof r=="string"&&(A=r),f=_.ref(A&&c.value.some(v=>v.id===A)?A:u())}(!m||o)&&_.watch(f,A=>{o&&o(A)});const g=_.computed(()=>c.value.find(A=>A.id===f.value)),C=_.computed(()=>c.value);return{selectedModelId:f,selectedModel:g,availableModels:C,setSelectedModel:A=>{c.value.find(P=>P.id===A)?f.value=A:console.warn(`[useModel] Model not found: ${A}`)}}}const tw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const nw=Object.prototype.toString,rw=t=>nw.call(t)==="[object Object]",Ei=()=>{};function po(t){return Array.isArray(t)?t:[t]}function iw(t,r,o){return _.watch(t,r,{...o,immediate:!0})}const Du=tw?window:void 0;function Wr(t){var r;const o=_.toValue(t);return(r=o?.$el)!==null&&r!==void 0?r:o}function mo(...t){const r=(c,u,f,m)=>(c.addEventListener(u,f,m),()=>c.removeEventListener(u,f,m)),o=_.computed(()=>{const c=po(_.toValue(t[0])).filter(u=>u!=null);return c.every(u=>typeof u!="string")?c:void 0});return iw(()=>{var c,u;return[(c=(u=o.value)===null||u===void 0?void 0:u.map(f=>Wr(f)))!==null&&c!==void 0?c:[Du].filter(f=>f!=null),po(_.toValue(o.value?t[1]:t[0])),po(_.unref(o.value?t[2]:t[1])),_.toValue(o.value?t[3]:t[2])]},([c,u,f,m],g,C)=>{if(!c?.length||!u?.length||!f?.length)return;const x=rw(m)?{...m}:m,A=c.flatMap(v=>u.flatMap(P=>f.map(O=>r(v,P,O,x))));C(()=>{A.forEach(v=>v())})},{flush:"post"})}function ow(t,r,o={}){const{window:c=Du,ignore:u=[],capture:f=!0,detectIframe:m=!1,controls:g=!1}=o;if(!c)return g?{stop:Ei,cancel:Ei,trigger:Ei}:Ei;let C=!0;const x=B=>_.toValue(u).some(G=>{if(typeof G=="string")return Array.from(c.document.querySelectorAll(G)).some(Z=>Z===B.target||B.composedPath().includes(Z));{const Z=Wr(G);return Z&&(B.target===Z||B.composedPath().includes(Z))}});function A(B){const G=_.toValue(B);return G&&G.$.subTree.shapeFlag===16}function v(B,G){const Z=_.toValue(B),z=Z.$.subTree&&Z.$.subTree.children;return z==null||!Array.isArray(z)?!1:z.some(ee=>ee.el===G.target||G.composedPath().includes(ee.el))}const P=B=>{const G=Wr(t);if(B.target!=null&&!(!(G instanceof Element)&&A(t)&&v(t,B))&&!(!G||G===B.target||B.composedPath().includes(G))){if("detail"in B&&B.detail===0&&(C=!x(B)),!C){C=!0;return}r(B)}};let O=!1;const M=[mo(c,"click",B=>{O||(O=!0,setTimeout(()=>{O=!1},0),P(B))},{passive:!0,capture:f}),mo(c,"pointerdown",B=>{const G=Wr(t);C=!x(B)&&!!(G&&!B.composedPath().includes(G))},{passive:!0}),m&&mo(c,"blur",B=>{setTimeout(()=>{var G;const Z=Wr(t);((G=c.document.activeElement)===null||G===void 0?void 0:G.tagName)==="IFRAME"&&!Z?.contains(c.document.activeElement)&&r(B)},0)},{passive:!0})].filter(Boolean),D=()=>M.forEach(B=>B());return g?{stop:D,cancel:()=>{C=!1},trigger:B=>{C=!0,P(B),C=!1}}:D}const sw=["data-active","disabled"],aw=_.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,o)=>(_.openBlock(),_.createElementBlock("button",{class:_.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[_.renderSlot(r.$slots,"default",{},void 0,!0)],10,sw))}}),ts=nr(aw,[["__scopeId","data-v-6f582cce"]]),lw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function cw(t,r){return _.openBlock(),_.createElementBlock("svg",lw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),_.createElementVNode("path",{id:"矢量 90",d:"M13.683 2.26904C12.5753 1.16177 10.344 1.47577 8.02582 2.86527C5.70758 1.47576 3.47637 1.16179 2.36913 2.26904C1.2619 3.37646 1.57573 5.60771 2.96524 7.92589C1.57573 10.2441 1.2619 12.4754 2.36913 13.5827C3.47637 14.6901 5.7078 14.3762 8.02599 12.9867C10.344 14.3762 12.5752 14.6901 13.6825 13.5827C14.7901 12.4754 14.4761 10.2441 13.0866 7.92594C14.4761 5.60775 14.7902 3.37646 13.683 2.26904ZM10.8544 5.09764C11.4667 5.70995 12.0076 6.34819 12.4699 6.99044C12.7244 6.52061 12.9268 6.06037 13.077 5.60959C13.2948 4.95652 13.3832 4.38597 13.3426 3.89769C13.3089 3.49437 13.1869 3.18725 12.9754 2.97631C12.7645 2.76513 12.4574 2.64282 12.0541 2.60912C11.5658 2.56835 10.9955 2.65698 10.3422 2.87475C9.89153 3.02497 9.43121 3.22735 8.96135 3.48197C9.60365 3.94428 10.242 4.48527 10.8544 5.09764ZM5.70991 2.87475C6.16049 3.02494 6.62073 3.22729 7.09051 3.48185C6.44826 3.94412 5.81002 4.48507 5.19771 5.09739C4.58523 5.70982 4.04417 6.34819 3.58181 6.99055C3.32716 6.52071 3.1248 6.06037 2.97459 5.60959C2.75682 4.95677 2.66844 4.38597 2.70897 3.89769C2.74266 3.49437 2.86522 3.18725 3.07615 2.97631C3.28709 2.76513 3.59421 2.64282 3.99753 2.60912C4.4858 2.5686 5.0566 2.65698 5.70991 2.87475ZM5.90473 5.80466Q4.89236 6.81738 4.14938 7.92595C4.64428 8.66515 5.2294 9.3722 5.90473 10.0473C6.57966 10.7222 7.28696 11.3074 8.02584 11.8027C8.76507 11.3074 9.47197 10.7222 10.1474 10.0473C10.8222 9.37218 11.4074 8.66511 11.9027 7.92588Q11.1597 6.81736 10.1474 5.80466C9.47203 5.12956 8.7652 4.54447 8.02604 4.04937C7.28683 4.54447 6.5796 5.12956 5.90473 5.80466ZM7.99992 6.90011C7.44768 6.90011 6.99993 7.34787 6.99993 7.90011C6.99993 8.45235 7.44768 8.9001 7.99992 8.9001C8.55216 8.9001 8.99991 8.45235 8.99991 7.90011C8.99991 7.34787 8.55216 6.90011 7.99992 6.90011ZM10.3422 12.9772C9.89161 12.827 9.43138 12.6246 8.96148 12.37C9.60377 11.9077 10.242 11.3667 10.8544 10.7543C11.4667 10.142 12.0077 9.50369 12.4699 8.8614C12.7245 9.33127 12.9268 9.79154 13.077 10.2421C13.2948 10.8952 13.3832 11.4658 13.3426 11.954C13.3089 12.3574 13.1864 12.6647 12.9754 12.8757C12.7645 13.0866 12.4574 13.2089 12.0541 13.2426C11.5658 13.2834 10.995 13.195 10.3422 12.9772ZM2.97459 10.2421C3.12478 9.7914 3.32733 9.3312 3.58196 8.86141C4.04428 9.50369 4.5853 10.142 5.19771 10.7543C5.81003 11.3667 6.44827 11.9077 7.09052 12.37C6.62074 12.6246 6.16049 12.827 5.70991 12.9772C5.0566 13.195 4.48629 13.2834 3.99802 13.2426C3.5947 13.2089 3.28709 13.0866 3.07615 12.8757C2.86522 12.6647 2.74315 12.3574 2.70946 11.954C2.66844 11.4658 2.75682 10.8952 2.97459 10.2421Z",fill:"rgb(89,89,89)","fill-rule":"evenodd"},null,-1)])])}const uw={render:cw},dw={class:"button-text"},fw={class:"dropdown-menu__items"},hw=["onClick"],pw=_.defineComponent({__name:"ModelSwitch",props:_.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,o=_.useModel(t,"selectedModelId"),c=_.computed(()=>{const O=r.modelConfigs;return O?Array.isArray(O)?O:O.value:[]}),{selectedModel:u,availableModels:f,setSelectedModel:m}=es(c,o),g=_.ref(!1),C=O=>{m(O),A()},x=()=>{g.value=!g.value},A=()=>{g.value=!1},v=_.ref(null),P=_.ref(null);return ow(P,()=>{A()},{ignore:[v]}),(O,M)=>(_.openBlock(),_.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:v},[_.createVNode(ts,{size:"small",class:"action-button",rounded:"",onClick:x},{default:_.withCtx(()=>[(_.openBlock(),_.createBlock(_.resolveDynamicComponent(_.unref(u)?.icon),{width:16,height:16,class:"selected-model__icon"})),_.createElementVNode("span",dw,_.toDisplayString(_.unref(u)?.label),1),_.createVNode(_.unref(uw),{width:16,height:16})]),_:1}),_.createVNode(_.Transition,{name:"dropdown"},{default:_.withCtx(()=>[g.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:P},[_.createElementVNode("div",fw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),D=>(_.openBlock(),_.createElementBlock("div",{key:D.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":D.id===o.value}]),onClick:_.withModifiers(B=>C(D.id),["stop"])},[D.icon?(_.openBlock(),_.createBlock(_.resolveDynamicComponent(D.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):_.createCommentVNode("",!0),_.createElementVNode("span",null,_.toDisplayString(D.label),1)],10,hw))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),g.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:A})):_.createCommentVNode("",!0)],512))}}),mw=nr(pw,[["__scopeId","data-v-475491fd"]]),gw={key:0,class:"active-count"},xw=_.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,o=_.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,u)=>(_.openBlock(),_.createBlock(ts,{size:"small",class:"action-button",active:o.value>0,rounded:"",onClick:u[0]||(u[0]=f=>c.$emit("click"))},{default:_.withCtx(()=>[_.createVNode(_.unref(Or.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),u[1]||(u[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),o.value>0?(_.openBlock(),_.createElementBlock("span",gw,_.toDisplayString(o.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),yw=nr(xw,[["__scopeId","data-v-c2a16c66"]]),ww={"data-v-99394ae9":"",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",width:"16.000000",height:"16.000000",fill:"none",customFrame:"#000000",size:"16"};function _w(t,r){return _.openBlock(),_.createElementBlock("svg",ww,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),_.createElementVNode("path",{id:"矢量 154",d:"M7.41014 2.09741L7.67112 2.70606C7.68333 2.73438 7.70579 2.75684 7.73411 2.76905L8.34275 3.02979C8.43968 3.0713 8.43968 3.20875 8.34275 3.25025L7.73411 3.51124C7.70579 3.52345 7.68333 3.54591 7.67112 3.57423L7.41014 4.18288C7.36863 4.2798 7.23118 4.2798 7.18968 4.18288L6.92894 3.57423C6.91673 3.54591 6.89427 3.52345 6.86595 3.51124L6.25731 3.25025C6.16039 3.20875 6.16039 3.0713 6.25731 3.02979L6.86595 2.76905C6.89427 2.75684 6.91673 2.73438 6.92894 2.70606L7.18968 2.09741C7.23118 2.00049 7.36863 2.00049 7.41014 2.09741ZM4.57006 11.9625L7.27611 8.09746L9.69944 4.63674L10.592 3.36207C10.6899 3.22218 10.8017 3.09864 10.9272 2.99122C11.0529 2.88404 11.1926 2.79297 11.3459 2.71802C11.4992 2.64332 11.657 2.58936 11.8191 2.5564C11.9809 2.52369 12.1472 2.51172 12.3176 2.52051C12.5315 2.53174 12.7336 2.57373 12.9238 2.64649C13.0678 2.70118 13.205 2.77369 13.3354 2.86353C13.4651 2.95289 13.5813 3.05445 13.6836 3.16822C13.8064 3.3047 13.9094 3.45851 13.9929 3.6299C14.0766 3.80128 14.1342 3.97731 14.1662 4.15773C14.1928 4.30861 14.2014 4.46267 14.1919 4.61989C14.1823 4.7781 14.1547 4.93069 14.1096 5.07791C14.0495 5.27249 13.958 5.45755 13.8352 5.63309L7.81321 14.2335Q7.66985 14.4382 7.48649 14.5965Q7.4825 14.6 7.4785 14.6034Q7.29063 14.7641 7.06102 14.8766C6.90794 14.9513 6.75072 15.0052 6.5891 15.0384C6.42748 15.0714 6.2617 15.0836 6.09154 15.0751C5.87743 15.0643 5.67504 15.0226 5.48436 14.9503C5.34008 14.8956 5.20287 14.8233 5.07201 14.7335C4.94213 14.6444 4.82592 14.5428 4.72313 14.4291C4.60033 14.2928 4.49682 14.1388 4.41308 13.9674C4.32934 13.7958 4.27123 13.6197 4.23925 13.4391C4.21239 13.2882 4.20385 13.1339 4.21313 12.9767C4.22265 12.8184 4.24999 12.6656 4.2954 12.5184C4.35546 12.3233 4.44701 12.138 4.57006 11.9625ZM4.7185 4.67361L4.18383 3.42579C4.11449 3.26441 3.88549 3.26441 3.81616 3.42579L3.28149 4.67361C3.26123 4.72073 3.22363 4.75832 3.17651 4.77859L1.92871 5.31326C1.76733 5.3826 1.76733 5.6116 1.92871 5.68094L3.17651 6.21561C3.22363 6.23587 3.26123 6.27347 3.28149 6.32059L3.81616 7.56841C3.88549 7.73003 4.11449 7.73003 4.18383 7.56841L4.7185 6.32059C4.73876 6.27347 4.77636 6.23587 4.82348 6.21561L6.07128 5.68094C6.23265 5.6116 6.23265 5.3826 6.07128 5.31326L4.82348 4.77859C4.77636 4.75832 4.73876 4.72073 4.7185 4.67361ZM5.38915 12.536C5.32006 12.6346 5.27099 12.7384 5.24169 12.8475C5.22533 12.9088 5.21532 12.9718 5.21141 13.0362C5.20726 13.1063 5.21044 13.1751 5.22094 13.2428C5.23583 13.3402 5.2661 13.4354 5.31151 13.5282C5.35692 13.6209 5.41332 13.7032 5.48095 13.775C5.52806 13.8248 5.58031 13.8695 5.63817 13.9093C5.69139 13.9459 5.7473 13.9764 5.80565 14.0011C5.9099 14.0453 6.02196 14.0702 6.14208 14.0763C6.2263 14.0807 6.30834 14.0746 6.38841 14.0582C6.46825 14.0418 6.54613 14.015 6.62181 13.9781C6.69749 13.941 6.76634 13.8961 6.8286 13.8429C6.89061 13.7899 6.94578 13.7289 6.99412 13.6598L11.9415 6.59405L10.3381 5.46789L5.38915 12.536ZM10.9168 4.6415L12.5202 5.76762L13.0161 5.05935C13.0849 4.96096 13.134 4.85745 13.1633 4.74831C13.1797 4.68703 13.1897 4.62429 13.1936 4.55959C13.198 4.48977 13.1948 4.42092 13.1843 4.35329C13.1694 4.25588 13.1394 4.16091 13.0942 4.06813C13.0488 3.97536 12.9926 3.89308 12.925 3.8213C12.8781 3.7715 12.8259 3.72682 12.7683 3.68703C12.7148 3.6504 12.6591 3.61964 12.6008 3.59474C12.4968 3.55079 12.385 3.5254 12.2651 3.5193C12.1806 3.51466 12.0984 3.52076 12.0183 3.53688C11.9382 3.55324 11.8601 3.57985 11.7841 3.61696C11.7082 3.65407 11.6391 3.69899 11.5771 3.75221C11.5149 3.80519 11.4594 3.86647 11.4111 3.93556L10.9168 4.6415Z",fill:"currentColor","fill-rule":"evenodd"},null,-1)])])}const vw={render:_w},Cw=_.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=_.useModel(t,"genuiEnabled"),o=()=>{r.value=!r.value};return(c,u)=>(_.openBlock(),_.createBlock(ts,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:o},{default:_.withCtx(()=>[_.createVNode(_.unref(vw),{width:16,height:16}),u[0]||(u[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),bw=nr(Cw,[["__scopeId","data-v-7f3b0372"]]),Ew={class:"bubble-image-wrapper"},Aw=["src"],Iw=["src"],Sw=_.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=_.ref(!1),o=_.ref(null),c=()=>{r.value=!0},u=()=>{r.value=!1};return _.watch(r,f=>{f&&_.nextTick(()=>{o.value?.focus()})}),(f,m)=>(_.openBlock(),_.createElementBlock("div",Ew,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,Aw),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[r.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:u,onKeydown:_.withKeys(u,["esc"])},[_.createElementVNode("button",{ref_key:"closeButtonRef",ref:o,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:u},[...m[1]||(m[1]=[_.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[_.createElementVNode("path",{d:"M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z",fill:"currentColor"})],-1)])],512),_.createElementVNode("div",{class:"preview-content",onClick:m[0]||(m[0]=_.withModifiers(()=>{},["stop"]))},[_.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,Iw)])],32)):_.createCommentVNode("",!0)]))]))}}),Tw=nr(Sw,[["__scopeId","data-v-91c75579"]]),Nw=`
79
+ `),e.toString()}setMode(e){this.mode=e}setECLevel(e){this.ecLevel=e}setVersion(e){this.version=e}setMaskPattern(e){this.maskPattern=e}setMatrix(e){this.matrix=e}static isValidMaskPattern(e){return e>=0&&e<lr.NUM_MASK_PATTERNS}}lr.NUM_MASK_PATTERNS=8;class dt extends g{}dt.kind="WriterException";class De{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,o,s,a){De.clearMatrix(a),De.embedBasicPatterns(o,a),De.embedTypeInfo(n,s,a),De.maybeEmbedVersionInfo(o,a),De.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){De.embedPositionDetectionPatternsAndSeparators(n),De.embedDarkDotAtLeftBottomCorner(n),De.maybeEmbedPositionAdjustmentPatterns(e,n),De.embedTimingPatterns(n)}static embedTypeInfo(e,n,o){const s=new re;De.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const u=s.get(s.getSize()-1-a),h=De.TYPE_INFO_COORDINATES[a],p=h[0],y=h[1];if(o.setBoolean(p,y,u),a<8){const b=o.getWidth()-a-1;o.setBoolean(b,8,u)}else{const I=o.getHeight()-7+(a-8);o.setBoolean(8,I,u)}}}static maybeEmbedVersionInfo(e,n){if(e.getVersionNumber()<7)return;const o=new re;De.makeVersionInfoBits(e,o);let s=17;for(let a=0;a<6;++a)for(let l=0;l<3;++l){const u=o.get(s);s--,n.setBoolean(a,n.getHeight()-11+l,u),n.setBoolean(n.getHeight()-11+l,a,u)}}static embedDataBits(e,n,o){let s=0,a=-1,l=o.getWidth()-1,u=o.getHeight()-1;for(;l>0;){for(l===6&&(l-=1);u>=0&&u<o.getHeight();){for(let h=0;h<2;++h){const p=l-h;if(!De.isEmpty(o.get(p,u)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&Nt.getDataMaskBit(n,p,u)&&(y=!y),o.setBoolean(p,u,y)}u+=a}a=-a,u+=a,l-=2}if(s!==e.getSize())throw new dt("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-F.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new A("0 polynomial");const o=De.findMSBSet(n);for(e<<=o-1;De.findMSBSet(e)>=o;)e^=n<<De.findMSBSet(e)-o;return e}static makeTypeInfoBits(e,n,o){if(!lr.isValidMaskPattern(n))throw new dt("Invalid mask pattern");const s=e.getBits()<<3|n;o.appendBits(s,5);const a=De.calculateBCHCode(s,De.TYPE_INFO_POLY);o.appendBits(a,10);const l=new re;if(l.appendBits(De.TYPE_INFO_MASK_PATTERN,15),o.xor(l),o.getSize()!==15)throw new dt("should not happen but we got: "+o.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const o=De.calculateBCHCode(e.getVersionNumber(),De.VERSION_INFO_POLY);if(n.appendBits(o,12),n.getSize()!==18)throw new dt("should not happen but we got: "+n.getSize())}static isEmpty(e){return e===255}static embedTimingPatterns(e){for(let n=8;n<e.getWidth()-8;++n){const o=(n+1)%2;De.isEmpty(e.get(n,6))&&e.setNumber(n,6,o),De.isEmpty(e.get(6,n))&&e.setNumber(6,n,o)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new dt;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,o){for(let s=0;s<8;++s){if(!De.isEmpty(o.get(e+s,n)))throw new dt;o.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,o){for(let s=0;s<7;++s){if(!De.isEmpty(o.get(e,n+s)))throw new dt;o.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,o){for(let s=0;s<5;++s){const a=De.POSITION_ADJUSTMENT_PATTERN[s];for(let l=0;l<5;++l)o.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPattern(e,n,o){for(let s=0;s<7;++s){const a=De.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)o.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=De.POSITION_DETECTION_PATTERN[0].length;De.embedPositionDetectionPattern(0,0,e),De.embedPositionDetectionPattern(e.getWidth()-n,0,e),De.embedPositionDetectionPattern(0,e.getWidth()-n,e);const o=8;De.embedHorizontalSeparationPattern(0,o-1,e),De.embedHorizontalSeparationPattern(e.getWidth()-o,o-1,e),De.embedHorizontalSeparationPattern(0,e.getWidth()-o,e);const s=7;De.embedVerticalSeparationPattern(s,0,e),De.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),De.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const o=e.getVersionNumber()-1,s=De.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[o];for(let a=0,l=s.length;a!==l;a++){const u=s[a];if(u>=0)for(let h=0;h!==l;h++){const p=s[h];p>=0&&De.isEmpty(n.get(p,u))&&De.embedPositionAdjustmentPattern(p-2,u-2,n)}}}}De.POSITION_DETECTION_PATTERN=Array.from([Int32Array.from([1,1,1,1,1,1,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,1,1,1,1,1,1])]),De.POSITION_ADJUSTMENT_PATTERN=Array.from([Int32Array.from([1,1,1,1,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,0,1,0,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,1,1,1,1])]),De.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE=Array.from([Int32Array.from([-1,-1,-1,-1,-1,-1,-1]),Int32Array.from([6,18,-1,-1,-1,-1,-1]),Int32Array.from([6,22,-1,-1,-1,-1,-1]),Int32Array.from([6,26,-1,-1,-1,-1,-1]),Int32Array.from([6,30,-1,-1,-1,-1,-1]),Int32Array.from([6,34,-1,-1,-1,-1,-1]),Int32Array.from([6,22,38,-1,-1,-1,-1]),Int32Array.from([6,24,42,-1,-1,-1,-1]),Int32Array.from([6,26,46,-1,-1,-1,-1]),Int32Array.from([6,28,50,-1,-1,-1,-1]),Int32Array.from([6,30,54,-1,-1,-1,-1]),Int32Array.from([6,32,58,-1,-1,-1,-1]),Int32Array.from([6,34,62,-1,-1,-1,-1]),Int32Array.from([6,26,46,66,-1,-1,-1]),Int32Array.from([6,26,48,70,-1,-1,-1]),Int32Array.from([6,26,50,74,-1,-1,-1]),Int32Array.from([6,30,54,78,-1,-1,-1]),Int32Array.from([6,30,56,82,-1,-1,-1]),Int32Array.from([6,30,58,86,-1,-1,-1]),Int32Array.from([6,34,62,90,-1,-1,-1]),Int32Array.from([6,28,50,72,94,-1,-1]),Int32Array.from([6,26,50,74,98,-1,-1]),Int32Array.from([6,30,54,78,102,-1,-1]),Int32Array.from([6,28,54,80,106,-1,-1]),Int32Array.from([6,32,58,84,110,-1,-1]),Int32Array.from([6,30,58,86,114,-1,-1]),Int32Array.from([6,34,62,90,118,-1,-1]),Int32Array.from([6,26,50,74,98,122,-1]),Int32Array.from([6,30,54,78,102,126,-1]),Int32Array.from([6,26,52,78,104,130,-1]),Int32Array.from([6,30,56,82,108,134,-1]),Int32Array.from([6,34,60,86,112,138,-1]),Int32Array.from([6,30,58,86,114,142,-1]),Int32Array.from([6,34,62,90,118,146,-1]),Int32Array.from([6,30,54,78,102,126,150]),Int32Array.from([6,24,50,76,102,128,154]),Int32Array.from([6,28,54,80,106,132,158]),Int32Array.from([6,32,58,84,110,136,162]),Int32Array.from([6,26,54,82,110,138,166]),Int32Array.from([6,30,58,86,114,142,170])]),De.TYPE_INFO_COORDINATES=Array.from([Int32Array.from([8,0]),Int32Array.from([8,1]),Int32Array.from([8,2]),Int32Array.from([8,3]),Int32Array.from([8,4]),Int32Array.from([8,5]),Int32Array.from([8,7]),Int32Array.from([8,8]),Int32Array.from([7,8]),Int32Array.from([5,8]),Int32Array.from([4,8]),Int32Array.from([3,8]),Int32Array.from([2,8]),Int32Array.from([1,8]),Int32Array.from([0,8])]),De.VERSION_INFO_POLY=7973,De.TYPE_INFO_POLY=1335,De.TYPE_INFO_MASK_PATTERN=21522;class md{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class xt{constructor(){}static calculateMaskPenalty(e){return Nt.applyMaskPenaltyRule1(e)+Nt.applyMaskPenaltyRule2(e)+Nt.applyMaskPenaltyRule3(e)+Nt.applyMaskPenaltyRule4(e)}static encode(e,n,o=null){let s=xt.DEFAULT_BYTE_MODE_ENCODING;const a=o!==null&&o.get(Bt.CHARACTER_SET)!==void 0;a&&(s=o.get(Bt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),u=new re;if(l===Re.BYTE&&(a||xt.DEFAULT_BYTE_MODE_ENCODING!==s)){const pe=z.getCharacterSetECIByName(s);pe!==void 0&&this.appendECI(pe,u)}this.appendModeInfo(l,u);const h=new re;this.appendBytes(e,l,h,s);let p;if(o!==null&&o.get(Bt.QR_VERSION)!==void 0){const pe=Number.parseInt(o.get(Bt.QR_VERSION).toString(),10);p=Ne.getVersionForNumber(pe);const ce=this.calculateBitsNeeded(l,u,h,p);if(!this.willFit(ce,p,n))throw new dt("Data too big for requested version")}else p=this.recommendVersion(n,l,u,h);const y=new re;y.appendBitArray(u);const b=l===Re.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(b,p,l,y),y.appendBitArray(h);const I=p.getECBlocksForLevel(n),R=p.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(R,y);const U=this.interleaveWithECBytes(y,p.getTotalCodewords(),R,I.getNumBlocks()),V=new lr;V.setECLevel(n),V.setMode(l),V.setVersion(p);const H=p.getDimensionForVersion(),Q=new go(H,H),he=this.chooseMaskPattern(U,n,p,Q);return V.setMaskPattern(he),De.buildMatrix(U,n,p,he,Q),V.setMatrix(Q),V}static recommendVersion(e,n,o,s){const a=this.calculateBitsNeeded(n,o,s,Ne.getVersionForNumber(1)),l=this.chooseVersion(a,e),u=this.calculateBitsNeeded(n,o,s,l);return this.chooseVersion(u,e)}static calculateBitsNeeded(e,n,o,s){return n.getSize()+e.getCharacterCountBits(s)+o.getSize()}static getAlphanumericCode(e){return e<xt.ALPHANUMERIC_TABLE.length?xt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(z.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Re.KANJI;let o=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const u=e.charAt(a);if(xt.isDigit(u))o=!0;else if(this.getAlphanumericCode(u.charCodeAt(0))!==-1)s=!0;else return Re.BYTE}return s?Re.ALPHANUMERIC:o?Re.NUMERIC:Re.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=G.encode(e,z.SJIS)}catch{return!1}const o=n.length;if(o%2!==0)return!1;for(let s=0;s<o;s+=2){const a=n[s]&255;if((a<129||a>159)&&(a<224||a>235))return!1}return!0}static chooseMaskPattern(e,n,o,s){let a=Number.MAX_SAFE_INTEGER,l=-1;for(let u=0;u<lr.NUM_MASK_PATTERNS;u++){De.buildMatrix(e,n,o,u,s);let h=this.calculateMaskPenalty(s);h<a&&(a=h,l=u)}return l}static chooseVersion(e,n){for(let o=1;o<=40;o++){const s=Ne.getVersionForNumber(o);if(xt.willFit(e,s,n))return s}throw new dt("Data too big")}static willFit(e,n,o){const s=n.getTotalCodewords(),l=n.getECBlocksForLevel(o).getTotalECCodewords(),u=s-l,h=(e+7)/8;return u>=h}static terminateBits(e,n){const o=e*8;if(n.getSize()>o)throw new dt("data bits cannot fit in the QR Code"+n.getSize()+" > "+o);for(let l=0;l<4&&n.getSize()<o;++l)n.appendBit(!1);const s=n.getSize()&7;if(s>0)for(let l=s;l<8;l++)n.appendBit(!1);const a=e-n.getSizeInBytes();for(let l=0;l<a;++l)n.appendBits((l&1)===0?236:17,8);if(n.getSize()!==o)throw new dt("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,o,s,a,l){if(s>=o)throw new dt("Block ID too large");const u=e%o,h=o-u,p=Math.floor(e/o),y=p+1,b=Math.floor(n/o),I=b+1,R=p-b,U=y-I;if(R!==U)throw new dt("EC bytes mismatch");if(o!==h+u)throw new dt("RS blocks mismatch");if(e!==(b+R)*h+(I+U)*u)throw new dt("Total bytes mismatch");s<h?(a[0]=b,l[0]=R):(a[0]=I,l[0]=U)}static interleaveWithECBytes(e,n,o,s){if(e.getSizeInBytes()!==o)throw new dt("Number of bits and data bytes does not match");let a=0,l=0,u=0;const h=new Array;for(let y=0;y<s;++y){const b=new Int32Array(1),I=new Int32Array(1);xt.getNumDataBytesAndNumECBytesForBlockID(n,o,s,y,b,I);const R=b[0],U=new Uint8Array(R);e.toBytes(8*a,U,0,R);const V=xt.generateECBytes(U,I[0]);h.push(new md(U,V)),l=Math.max(l,R),u=Math.max(u,V.length),a+=b[0]}if(o!==a)throw new dt("Data bytes does not match offset");const p=new re;for(let y=0;y<l;++y)for(const b of h){const I=b.getDataBytes();y<I.length&&p.appendBits(I[y],8)}for(let y=0;y<u;++y)for(const b of h){const I=b.getErrorCorrectionBytes();y<I.length&&p.appendBits(I[y],8)}if(n!==p.getSizeInBytes())throw new dt("Interleaving error: "+n+" and "+p.getSizeInBytes()+" differ.");return p}static generateECBytes(e,n){const o=e.length,s=new Int32Array(o+n);for(let l=0;l<o;l++)s[l]=e[l]&255;new ti(Se.QR_CODE_FIELD_256).encode(s,n);const a=new Uint8Array(n);for(let l=0;l<n;l++)a[l]=s[o+l];return a}static appendModeInfo(e,n){n.appendBits(e.getBits(),4)}static appendLengthInfo(e,n,o,s){const a=o.getCharacterCountBits(n);if(e>=1<<a)throw new dt(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,o,s){switch(n){case Re.NUMERIC:xt.appendNumericBytes(e,o);break;case Re.ALPHANUMERIC:xt.appendAlphanumericBytes(e,o);break;case Re.BYTE:xt.append8BitBytes(e,o,s);break;case Re.KANJI:xt.appendKanjiBytes(e,o);break;default:throw new dt("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=xt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const o=e.length;let s=0;for(;s<o;){const a=xt.getDigit(e.charAt(s));if(s+2<o){const l=xt.getDigit(e.charAt(s+1)),u=xt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+u,10),s+=3}else if(s+1<o){const l=xt.getDigit(e.charAt(s+1));n.appendBits(a*10+l,7),s+=2}else n.appendBits(a,4),s++}}static appendAlphanumericBytes(e,n){const o=e.length;let s=0;for(;s<o;){const a=xt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new dt;if(s+1<o){const l=xt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new dt;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,o){let s;try{s=G.encode(e,o)}catch(a){throw new dt(a)}for(let a=0,l=s.length;a!==l;a++){const u=s[a];n.appendBits(u,8)}}static appendKanjiBytes(e,n){let o;try{o=G.encode(e,z.SJIS)}catch(a){throw new dt(a)}const s=o.length;for(let a=0;a<s;a+=2){const l=o[a]&255,u=o[a+1]&255,h=l<<8&4294967295|u;let p=-1;if(h>=33088&&h<=40956?p=h-33088:h>=57408&&h<=60351&&(p=h-49472),p===-1)throw new dt("Invalid byte sequence");const y=(p>>8)*192+(p&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(Re.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}xt.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]),xt.DEFAULT_BYTE_MODE_ENCODING=z.UTF8.getName();class cr{write(e,n,o,s=null){if(e.length===0)throw new A("Found empty contents");if(n<0||o<0)throw new A("Requested dimensions are too small: "+n+"x"+o);let a=pt.L,l=cr.QUIET_ZONE_SIZE;s!==null&&(s.get(Bt.ERROR_CORRECTION)!==void 0&&(a=pt.fromString(s.get(Bt.ERROR_CORRECTION).toString())),s.get(Bt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Bt.MARGIN).toString(),10)));const u=xt.encode(e,a,s);return this.renderResult(u,n,o,l)}writeToDom(e,n,o,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,o,s,a);e&&e.appendChild(l)}renderResult(e,n,o,s){const a=e.getMatrix();if(a===null)throw new St;const l=a.getWidth(),u=a.getHeight(),h=l+s*2,p=u+s*2,y=Math.max(n,h),b=Math.max(o,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),U=Math.floor((b-u*I)/2),V=this.createSVGElement(y,b);for(let H=0,Q=U;H<u;H++,Q+=I)for(let he=0,pe=R;he<l;he++,pe+=I)if(a.get(he,H)===1){const ce=this.createSvgRectElement(pe,Q,I,I);V.appendChild(ce)}return V}createSVGElement(e,n){const o=document.createElementNS(cr.SVG_NS,"svg");return o.setAttributeNS(null,"height",e.toString()),o.setAttributeNS(null,"width",n.toString()),o}createSvgRectElement(e,n,o,s){const a=document.createElementNS(cr.SVG_NS,"rect");return a.setAttributeNS(null,"x",e.toString()),a.setAttributeNS(null,"y",n.toString()),a.setAttributeNS(null,"height",o.toString()),a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"fill","#000000"),a}}cr.QUIET_ZONE_SIZE=4,cr.SVG_NS="http://www.w3.org/2000/svg";class Er{encode(e,n,o,s,a){if(e.length===0)throw new A("Found empty contents");if(n!==ie.QR_CODE)throw new A("Can only encode QR_CODE, but got "+n);if(o<0||s<0)throw new A(`Requested dimensions are too small: ${o}x${s}`);let l=pt.L,u=Er.QUIET_ZONE_SIZE;a!==null&&(a.get(Bt.ERROR_CORRECTION)!==void 0&&(l=pt.fromString(a.get(Bt.ERROR_CORRECTION).toString())),a.get(Bt.MARGIN)!==void 0&&(u=Number.parseInt(a.get(Bt.MARGIN).toString(),10)));const h=xt.encode(e,l,a);return Er.renderResult(h,o,s,u)}static renderResult(e,n,o,s){const a=e.getMatrix();if(a===null)throw new St;const l=a.getWidth(),u=a.getHeight(),h=l+s*2,p=u+s*2,y=Math.max(n,h),b=Math.max(o,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),U=Math.floor((b-u*I)/2),V=new te(y,b);for(let H=0,Q=U;H<u;H++,Q+=I)for(let he=0,pe=R;he<l;he++,pe+=I)a.get(he,H)===1&&V.setRegion(pe,Q,I,I);return V}}Er.QUIET_ZONE_SIZE=4;class gd{encode(e,n,o,s,a){let l;switch(n){case ie.QR_CODE:l=new Er;break;default:throw new A("No encoder available for format "+n)}return l.encode(e,n,o,s,a)}}class On extends Te{constructor(e,n,o,s,a,l,u,h){if(super(l,u),this.yuvData=e,this.dataWidth=n,this.dataHeight=o,this.left=s,this.top=a,s+l>n||a+u>o)throw new A("Crop rectangle does not fit within image data.");h&&this.reverseHorizontal(l,u)}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const o=this.getWidth();(n==null||n.length<o)&&(n=new Uint8ClampedArray(o));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.yuvData,s,n,0,o),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.yuvData;const o=e*n,s=new Uint8ClampedArray(o);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.yuvData,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;P.arraycopy(this.yuvData,a,s,u,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,o,s){return new On(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,o,s,!1)}renderThumbnail(){const e=this.getWidth()/On.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/On.THUMBNAIL_SCALE_FACTOR,o=new Int32Array(e*n),s=this.yuvData;let a=this.top*this.dataWidth+this.left;for(let l=0;l<n;l++){const u=l*e;for(let h=0;h<e;h++){const p=s[a+h*On.THUMBNAIL_SCALE_FACTOR]&255;o[u+h]=4278190080|p*65793}a+=this.dataWidth*On.THUMBNAIL_SCALE_FACTOR}return o}getThumbnailWidth(){return this.getWidth()/On.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/On.THUMBNAIL_SCALE_FACTOR}reverseHorizontal(e,n){const o=this.yuvData;for(let s=0,a=this.top*this.dataWidth+this.left;s<n;s++,a+=this.dataWidth){const l=a+e/2;for(let u=a,h=a+e-1;u<l;u++,h--){const p=o[u];o[u]=o[h],o[h]=p}}}invert(){return new Je(this)}}On.THUMBNAIL_SCALE_FACTOR=2;class ni extends Te{constructor(e,n,o,s,a,l,u){if(super(n,o),this.dataWidth=s,this.dataHeight=a,this.left=l,this.top=u,e.BYTES_PER_ELEMENT===4){const h=n*o,p=new Uint8ClampedArray(h);for(let y=0;y<h;y++){const b=e[y],I=b>>16&255,R=b>>7&510,U=b&255;p[y]=(I+R+U)/4&255}this.luminances=p}else this.luminances=e;if(s===void 0&&(this.dataWidth=n),a===void 0&&(this.dataHeight=o),l===void 0&&(this.left=0),u===void 0&&(this.top=0),this.left+n>this.dataWidth||this.top+o>this.dataHeight)throw new A("Crop rectangle does not fit within image data.")}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const o=this.getWidth();(n==null||n.length<o)&&(n=new Uint8ClampedArray(o));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.luminances,s,n,0,o),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.luminances;const o=e*n,s=new Uint8ClampedArray(o);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.luminances,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;P.arraycopy(this.luminances,a,s,u,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,o,s){return new ni(this.luminances,o,s,this.dataWidth,this.dataHeight,this.left+e,this.top+n)}invert(){return new Je(this)}}class ys extends z{static forName(e){return this.getCharacterSetECIByName(e)}}class ri{}ri.ISO_8859_1=z.ISO8859_1;class ws{isCompact(){return this.compact}setCompact(e){this.compact=e}getSize(){return this.size}setSize(e){this.size=e}getLayers(){return this.layers}setLayers(e){this.layers=e}getCodeWords(){return this.codeWords}setCodeWords(e){this.codeWords=e}getMatrix(){return this.matrix}setMatrix(e){this.matrix=e}}class _s{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class xd{constructor(e){this.previous=e}getPrevious(){return this.previous}}class Ir extends xd{constructor(e,n,o){super(e),this.value=n,this.bitCount=o}appendTo(e,n){e.appendBits(this.value,this.bitCount)}add(e,n){return new Ir(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new Ir(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+F.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class oi extends Ir{constructor(e,n,o){super(e,0,0),this.binaryShiftStart=n,this.binaryShiftByteCount=o}appendTo(e,n){for(let o=0;o<this.binaryShiftByteCount;o++)(o===0||o===31&&this.binaryShiftByteCount<=62)&&(e.appendBits(31,5),this.binaryShiftByteCount>62?e.appendBits(this.binaryShiftByteCount-31,16):o===0?e.appendBits(Math.min(this.binaryShiftByteCount,31),5):e.appendBits(this.binaryShiftByteCount-31,5)),e.appendBits(n[this.binaryShiftStart+o],8)}addBinaryShift(e,n){return new oi(this,e,n)}toString(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"}}function yd(C,e,n){return new oi(C,e,n)}function zr(C,e,n){return new Ir(C,e,n)}const wd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Yn=0,xo=1,gn=2,vs=3,kn=4,_d=new Ir(null,0,0),ii=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(9<<16)+480+14,0,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(4<<16)+14,(9<<16)+448+28,0,(9<<16)+448+29,932798]),Int32Array.from([(5<<16)+29,(5<<16)+28,656318,0,(5<<16)+30]),Int32Array.from([(5<<16)+31,656380,656382,656381,0])];function vd(C){for(let e of C)$.fill(e,-1);return C[Yn][kn]=0,C[xo][kn]=0,C[xo][Yn]=28,C[vs][kn]=0,C[gn][kn]=0,C[gn][Yn]=15,C}const Cs=vd($.createInt32Array(6,6));class Rn{constructor(e,n,o,s){this.token=e,this.mode=n,this.binaryShiftByteCount=o,this.bitCount=s}getMode(){return this.mode}getToken(){return this.token}getBinaryShiftByteCount(){return this.binaryShiftByteCount}getBitCount(){return this.bitCount}latchAndAppend(e,n){let o=this.bitCount,s=this.token;if(e!==this.mode){let l=ii[this.mode][e];s=zr(s,l&65535,l>>16),o+=l>>16}let a=e===gn?4:5;return s=zr(s,n,a),new Rn(s,e,0,o+a)}shiftAndAppend(e,n){let o=this.token,s=this.mode===gn?4:5;return o=zr(o,Cs[this.mode][e],s),o=zr(o,n,5),new Rn(o,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,o=this.mode,s=this.bitCount;if(this.mode===kn||this.mode===gn){let u=ii[o][Yn];n=zr(n,u&65535,u>>16),s+=u>>16,o=Yn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Rn(n,o,this.binaryShiftByteCount+1,s+a);return l.binaryShiftByteCount===2078&&(l=l.endBinaryShift(e+1)),l}endBinaryShift(e){if(this.binaryShiftByteCount===0)return this;let n=this.token;return n=yd(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Rn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(ii[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Rn.calculateBinaryShiftCost(e)-Rn.calculateBinaryShiftCost(this):this.binaryShiftByteCount>e.binaryShiftByteCount&&e.binaryShiftByteCount>0&&(n+=10),n<=e.bitCount}toBitArray(e){let n=[];for(let s=this.endBinaryShift(e.length).token;s!==null;s=s.getPrevious())n.unshift(s);let o=new re;for(const s of n)s.appendTo(o,e);return o}toString(){return me.format("%s bits=%d bytes=%d",wd[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Rn.INITIAL_STATE=new Rn(_d,Yn,0,0);function Cd(C){const e=me.getCharCode(" "),n=me.getCharCode("."),o=me.getCharCode(",");C[Yn][e]=1;const s=me.getCharCode("Z"),a=me.getCharCode("A");for(let I=a;I<=s;I++)C[Yn][I]=I-a+2;C[xo][e]=1;const l=me.getCharCode("z"),u=me.getCharCode("a");for(let I=u;I<=l;I++)C[xo][I]=I-u+2;C[gn][e]=1;const h=me.getCharCode("9"),p=me.getCharCode("0");for(let I=p;I<=h;I++)C[gn][I]=I-p+2;C[gn][o]=12,C[gn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
80
+ `,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)C[vs][me.getCharCode(y[I])]=I;const b=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<b.length;I++)me.getCharCode(b[I])>0&&(C[kn][me.getCharCode(b[I])]=I);return C}const si=Cd($.createInt32Array(5,256));class Vr{constructor(e){this.text=e}encode(){const e=me.getCharCode(" "),n=me.getCharCode(`
81
+ `);let o=_s.singletonList(Rn.INITIAL_STATE);for(let a=0;a<this.text.length;a++){let l,u=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case me.getCharCode("\r"):l=u===n?2:0;break;case me.getCharCode("."):l=u===e?3:0;break;case me.getCharCode(","):l=u===e?4:0;break;case me.getCharCode(":"):l=u===e?5:0;break;default:l=0}l>0?(o=Vr.updateStateListForPair(o,a,l),a++):o=this.updateStateListForChar(o,a)}return _s.min(o,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const o=[];for(let s of e)this.updateStateForChar(s,n,o);return Vr.simplifyStates(o)}updateStateForChar(e,n,o){let s=this.text[n]&255,a=si[e.getMode()][s]>0,l=null;for(let u=0;u<=kn;u++){let h=si[u][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||u===e.getMode()||u===gn){const p=l.latchAndAppend(u,h);o.push(p)}if(!a&&Cs[e.getMode()][u]>=0){const p=l.shiftAndAppend(u,h);o.push(p)}}}if(e.getBinaryShiftByteCount()>0||si[e.getMode()][s]===0){let u=e.addBinaryShiftChar(n);o.push(u)}}static updateStateListForPair(e,n,o){const s=[];for(let a of e)this.updateStateForPair(a,n,o,s);return this.simplifyStates(s)}static updateStateForPair(e,n,o,s){let a=e.endBinaryShift(n);if(s.push(a.latchAndAppend(kn,o)),e.getMode()!==kn&&s.push(a.shiftAndAppend(kn,o)),o===3||o===4){let l=a.latchAndAppend(gn,16-o).latchAndAppend(gn,1);s.push(l)}if(e.getBinaryShiftByteCount()>0){let l=e.addBinaryShiftChar(n).addBinaryShiftChar(n+1);s.push(l)}}static simplifyStates(e){let n=[];for(const o of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(o)){s=!1;break}o.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(o)}return n}}class tt{constructor(){}static encodeBytes(e){return tt.encode(e,tt.DEFAULT_EC_PERCENT,tt.DEFAULT_AZTEC_LAYERS)}static encode(e,n,o){let s=new Vr(e).encode(),a=F.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,u,h,p,y,b;if(o!==tt.DEFAULT_AZTEC_LAYERS){if(u=o<0,h=Math.abs(o),h>(u?tt.MAX_NB_BITS_COMPACT:tt.MAX_NB_BITS))throw new A(me.format("Illegal value %s for layers",o));p=tt.totalBitsInLayer(h,u),y=tt.WORD_SIZE[h];let ce=p-p%y;if(b=tt.stuffBits(s,y),b.getSize()+a>ce)throw new A("Data to large for user specified layer");if(u&&b.getSize()>y*64)throw new A("Data to large for user specified layer")}else{y=0,b=null;for(let ce=0;;ce++){if(ce>tt.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(u=ce<=3,h=u?ce+1:ce,p=tt.totalBitsInLayer(h,u),l>p)continue;(b==null||y!==tt.WORD_SIZE[h])&&(y=tt.WORD_SIZE[h],b=tt.stuffBits(s,y));let Ke=p-p%y;if(!(u&&b.getSize()>y*64)&&b.getSize()+a<=Ke)break}}let I=tt.generateCheckWords(b,p,y),R=b.getSize()/y,U=tt.generateModeMessage(u,h,R),V=(u?11:14)+h*4,H=new Int32Array(V),Q;if(u){Q=V;for(let ce=0;ce<H.length;ce++)H[ce]=ce}else{Q=V+1+2*F.truncDivision(F.truncDivision(V,2)-1,15);let ce=F.truncDivision(V,2),Ke=F.truncDivision(Q,2);for(let He=0;He<ce;He++){let tn=He+F.truncDivision(He,15);H[ce-He-1]=Ke-tn-1,H[ce+He]=Ke+tn+1}}let he=new te(Q);for(let ce=0,Ke=0;ce<h;ce++){let He=(h-ce)*4+(u?9:12);for(let tn=0;tn<He;tn++){let yn=tn*2;for(let nn=0;nn<2;nn++)I.get(Ke+yn+nn)&&he.set(H[ce*2+nn],H[ce*2+tn]),I.get(Ke+He*2+yn+nn)&&he.set(H[ce*2+tn],H[V-1-ce*2-nn]),I.get(Ke+He*4+yn+nn)&&he.set(H[V-1-ce*2-nn],H[V-1-ce*2-tn]),I.get(Ke+He*6+yn+nn)&&he.set(H[V-1-ce*2-tn],H[ce*2+nn])}Ke+=He*8}if(tt.drawModeMessage(he,u,Q,U),u)tt.drawBullsEye(he,F.truncDivision(Q,2),5);else{tt.drawBullsEye(he,F.truncDivision(Q,2),7);for(let ce=0,Ke=0;ce<F.truncDivision(V,2)-1;ce+=15,Ke+=16)for(let He=F.truncDivision(Q,2)&1;He<Q;He+=2)he.set(F.truncDivision(Q,2)-Ke,He),he.set(F.truncDivision(Q,2)+Ke,He),he.set(He,F.truncDivision(Q,2)-Ke),he.set(He,F.truncDivision(Q,2)+Ke)}let pe=new ws;return pe.setCompact(u),pe.setSize(Q),pe.setLayers(h),pe.setCodeWords(R),pe.setMatrix(he),pe}static drawBullsEye(e,n,o){for(let s=0;s<o;s+=2)for(let a=n-s;a<=n+s;a++)e.set(a,n-s),e.set(a,n+s),e.set(n-s,a),e.set(n+s,a);e.set(n-o,n-o),e.set(n-o+1,n-o),e.set(n-o,n-o+1),e.set(n+o,n-o),e.set(n+o,n-o+1),e.set(n+o,n+o-1)}static generateModeMessage(e,n,o){let s=new re;return e?(s.appendBits(n-1,2),s.appendBits(o-1,6),s=tt.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(o-1,11),s=tt.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,o,s){let a=F.truncDivision(o,2);if(n)for(let l=0;l<7;l++){let u=a-3+l;s.get(l)&&e.set(u,a-5),s.get(l+7)&&e.set(a+5,u),s.get(20-l)&&e.set(u,a+5),s.get(27-l)&&e.set(a-5,u)}else for(let l=0;l<10;l++){let u=a-5+l+F.truncDivision(l,5);s.get(l)&&e.set(u,a-7),s.get(l+10)&&e.set(a+7,u),s.get(29-l)&&e.set(u,a+7),s.get(39-l)&&e.set(a-7,u)}}static generateCheckWords(e,n,o){let s=e.getSize()/o,a=new ti(tt.getGF(o)),l=F.truncDivision(n,o),u=tt.bitsToWords(e,o,l);a.encode(u,l-s);let h=n%o,p=new re;p.appendBits(0,h);for(const y of Array.from(u))p.appendBits(y,o);return p}static bitsToWords(e,n,o){let s=new Int32Array(o),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let u=0;for(let h=0;h<n;h++)u|=e.get(a*n+h)?1<<n-h-1:0;s[a]=u}return s}static getGF(e){switch(e){case 4:return Se.AZTEC_PARAM;case 6:return Se.AZTEC_DATA_6;case 8:return Se.AZTEC_DATA_8;case 10:return Se.AZTEC_DATA_10;case 12:return Se.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let o=new re,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let u=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(u|=1<<n-1-h);(u&a)===a?(o.appendBits(u&a,n),l--):(u&a)===0?(o.appendBits(u|1,n),l--):o.appendBits(u,n)}return o}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}tt.DEFAULT_EC_PERCENT=33,tt.DEFAULT_AZTEC_LAYERS=0,tt.MAX_NB_BITS=32,tt.MAX_NB_BITS_COMPACT=4,tt.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);class yo{encode(e,n,o,s){return this.encodeWithHints(e,n,o,s,null)}encodeWithHints(e,n,o,s,a){let l=ri.ISO_8859_1,u=tt.DEFAULT_EC_PERCENT,h=tt.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Bt.CHARACTER_SET)&&(l=ys.forName(a.get(Bt.CHARACTER_SET).toString())),a.has(Bt.ERROR_CORRECTION)&&(u=F.parseInt(a.get(Bt.ERROR_CORRECTION).toString())),a.has(Bt.AZTEC_LAYERS)&&(h=F.parseInt(a.get(Bt.AZTEC_LAYERS).toString()))),yo.encodeLayers(e,n,o,s,l,u,h)}static encodeLayers(e,n,o,s,a,l,u){if(n!==ie.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=tt.encode(me.getBytes(e,a),l,u);return yo.renderResult(h,o,s)}static renderResult(e,n,o){let s=e.getMatrix();if(s==null)throw new St;let a=s.getWidth(),l=s.getHeight(),u=Math.max(n,a),h=Math.max(o,l),p=Math.min(u/a,h/l),y=(u-a*p)/2,b=(h-l*p)/2,I=new te(u,h);for(let R=0,U=b;R<l;R++,U+=p)for(let V=0,H=y;V<a;V++,H+=p)s.get(V,R)&&I.setRegion(H,U,p,p);return I}}i.AbstractExpandedDecoder=Ho,i.ArgumentException=E,i.ArithmeticException=ye,i.AztecCode=ws,i.AztecCodeReader=Ln,i.AztecCodeWriter=yo,i.AztecDecoder=nt,i.AztecDetector=or,i.AztecDetectorResult=$n,i.AztecEncoder=tt,i.AztecHighLevelEncoder=Vr,i.AztecPoint=At,i.BarcodeFormat=ie,i.Binarizer=S,i.BinaryBitmap=D,i.BitArray=re,i.BitMatrix=te,i.BitSource=Xo,i.BrowserAztecCodeReader=wr,i.BrowserBarcodeReader=Qu,i.BrowserCodeReader=Ze,i.BrowserDatamatrixCodeReader=td,i.BrowserMultiFormatReader=fd,i.BrowserPDF417Reader=hd,i.BrowserQRCodeReader=pd,i.BrowserQRCodeSvgWriter=cr,i.CharacterSetECI=z,i.ChecksumException=T,i.Code128Reader=ge,i.Code39Reader=O,i.DataMatrixDecodedBitStreamParser=Wn,i.DataMatrixReader=Gn,i.DecodeHintType=B,i.DecoderResult=Pe,i.DefaultGridSampler=rr,i.DetectorResult=Bn,i.EAN13Reader=Fn,i.EncodeHintType=Bt,i.Exception=g,i.FormatException=L,i.GenericGF=Se,i.GenericGFPoly=J,i.GlobalHistogramBinarizer=ke,i.GridSampler=jn,i.GridSamplerInstance=sn,i.HTMLCanvasElementLuminanceSource=xe,i.HybridBinarizer=le,i.ITFReader=ne,i.IllegalArgumentException=A,i.IllegalStateException=St,i.InvertedLuminanceSource=Je,i.LuminanceSource=Te,i.MathUtils=Xe,i.MultiFormatOneDReader=br,i.MultiFormatReader=xs,i.MultiFormatWriter=gd,i.NotFoundException=q,i.OneDReader=gt,i.PDF417DecodedBitStreamParser=K,i.PDF417DecoderErrorCorrection=ds,i.PDF417Reader=jt,i.PDF417ResultMetadata=hs,i.PerspectiveTransform=Ft,i.PlanarYUVLuminanceSource=On,i.QRCodeByteMatrix=go,i.QRCodeDataMask=pn,i.QRCodeDecodedBitStreamParser=Et,i.QRCodeDecoderErrorCorrectionLevel=pt,i.QRCodeDecoderFormatInformation=Gt,i.QRCodeEncoder=xt,i.QRCodeEncoderQRCode=lr,i.QRCodeMaskUtil=Nt,i.QRCodeMatrixUtil=De,i.QRCodeMode=Re,i.QRCodeReader=qn,i.QRCodeVersion=Ne,i.QRCodeWriter=Er,i.RGBLuminanceSource=ni,i.RSS14Reader=Tt,i.RSSExpandedReader=se,i.ReaderException=mo,i.ReedSolomonDecoder=vt,i.ReedSolomonEncoder=ti,i.ReedSolomonException=Ve,i.Result=qe,i.ResultMetadataType=_e,i.ResultPoint=be,i.StringUtils=me,i.UnsupportedOperationException=we,i.VideoInputDevice=$e,i.WhiteRectangleDetector=qt,i.WriterException=dt,i.ZXingArrays=$,i.ZXingCharset=ys,i.ZXingInteger=F,i.ZXingStandardCharsets=ri,i.ZXingStringBuilder=fe,i.ZXingStringEncoding=G,i.ZXingSystem=P,i.createAbstractExpandedDecoder=cs,Object.defineProperty(i,"__esModule",{value:!0})}))})(qr,qr.exports)),qr.exports}var yt=aw();const lw=iw(yt),cw=Td({__proto__:null,default:lw},[yt]);var dl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,yt.BarcodeFormat.QR_CODE],[Ce.AZTEC,yt.BarcodeFormat.AZTEC],[Ce.CODABAR,yt.BarcodeFormat.CODABAR],[Ce.CODE_39,yt.BarcodeFormat.CODE_39],[Ce.CODE_93,yt.BarcodeFormat.CODE_93],[Ce.CODE_128,yt.BarcodeFormat.CODE_128],[Ce.DATA_MATRIX,yt.BarcodeFormat.DATA_MATRIX],[Ce.MAXICODE,yt.BarcodeFormat.MAXICODE],[Ce.ITF,yt.BarcodeFormat.ITF],[Ce.EAN_13,yt.BarcodeFormat.EAN_13],[Ce.EAN_8,yt.BarcodeFormat.EAN_8],[Ce.PDF_417,yt.BarcodeFormat.PDF_417],[Ce.RSS_14,yt.BarcodeFormat.RSS_14],[Ce.RSS_EXPANDED,yt.BarcodeFormat.RSS_EXPANDED],[Ce.UPC_A,yt.BarcodeFormat.UPC_A],[Ce.UPC_E,yt.BarcodeFormat.UPC_E],[Ce.UPC_EAN_EXTENSION,yt.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!cw)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=i,this.logger=c;var d=this.createZXingFormats(r),f=new Map;f.set(yt.DecodeHintType.POSSIBLE_FORMATS,d),f.set(yt.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var i=this;return new Promise(function(c,d){try{c(i.decode(r))}catch(f){d(f)}})},t.prototype.decode=function(r){var i=new yt.MultiFormatReader(this.verbose,this.hints),c=new yt.HTMLCanvasElementLuminanceSource(r),d=new yt.BinaryBitmap(new yt.HybridBinarizer(c)),f=i.decode(d);return{text:f.text,format:Hu.create(this.toHtml5QrcodeSupportedFormats(f.format)),debugData:this.createDebugData()}},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(i,c,d){r.set(i,c)}),r},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createZXingFormats=function(r){for(var i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.logError("".concat(f," is not supported by")+"ZXingHtml5QrcodeShim")}return i},t.prototype.createDebugData=function(){return{decoderName:"zxing-js"}},t})(),uw=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},dw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},fl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,"qr_code"],[Ce.AZTEC,"aztec"],[Ce.CODABAR,"codabar"],[Ce.CODE_39,"code_39"],[Ce.CODE_93,"code_93"],[Ce.CODE_128,"code_128"],[Ce.DATA_MATRIX,"data_matrix"],[Ce.ITF,"itf"],[Ce.EAN_13,"ean_13"],[Ce.EAN_8,"ean_8"],[Ce.PDF_417,"pdf417"],[Ce.UPC_A,"upc_a"],[Ce.UPC_E,"upc_e"]]),this.reverseFormatMap=this.createReverseFormatMap(),!t.isSupported())throw"Use html5qrcode.min.js without edit, Use BarcodeDetectorDelegate only if it isSupported();";this.verbose=i,this.logger=c;var d=this.createBarcodeDetectorFormats(r);if(this.detector=new BarcodeDetector(d),!this.detector)throw"BarcodeDetector detector not supported"}return t.isSupported=function(){if(!("BarcodeDetector"in window))return!1;var r=new BarcodeDetector({formats:["qr_code"]});return typeof r<"u"},t.prototype.decodeAsync=function(r){return uw(this,void 0,void 0,function(){var i,c;return dw(this,function(d){switch(d.label){case 0:return[4,this.detector.detect(r)];case 1:if(i=d.sent(),!i||i.length===0)throw"No barcode or QR code detected.";return c=this.selectLargestBarcode(i),[2,{text:c.rawValue,format:Hu.create(this.toHtml5QrcodeSupportedFormats(c.format)),debugData:this.createDebugData()}]}})})},t.prototype.selectLargestBarcode=function(r){for(var i=null,c=0,d=0,f=r;d<f.length;d++){var m=f[d],x=m.boundingBox.width*m.boundingBox.height;x>c&&(c=x,i=m)}if(!i)throw"No largest barcode found";return i},t.prototype.createBarcodeDetectorFormats=function(r){for(var i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.warn("".concat(f," is not supported by")+"BarcodeDetectorDelegate")}return{formats:i}},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(i,c,d){r.set(i,c)}),r},t.prototype.createDebugData=function(){return{decoderName:"BarcodeDetector"}},t})(),hl=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},pl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},fw=(function(){function t(r,i,c,d){this.EXECUTIONS_TO_REPORT_PERFORMANCE=100,this.executions=0,this.executionResults=[],this.wasPrimaryDecoderUsedInLastDecode=!1,this.verbose=c,i&&fl.isSupported()?(this.primaryDecoder=new fl(r,c,d),this.secondaryDecoder=new dl(r,c,d)):this.primaryDecoder=new dl(r,c,d)}return t.prototype.decodeAsync=function(r){return hl(this,void 0,void 0,function(){var i;return pl(this,function(c){switch(c.label){case 0:i=performance.now(),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,this.getDecoder().decodeAsync(r)];case 2:return[2,c.sent()];case 3:return this.possiblyLogPerformance(i),[7];case 4:return[2]}})})},t.prototype.decodeRobustlyAsync=function(r){return hl(this,void 0,void 0,function(){var i,c;return pl(this,function(d){switch(d.label){case 0:i=performance.now(),d.label=1;case 1:return d.trys.push([1,3,4,5]),[4,this.primaryDecoder.decodeAsync(r)];case 2:return[2,d.sent()];case 3:if(c=d.sent(),this.secondaryDecoder)return[2,this.secondaryDecoder.decodeAsync(r)];throw c;case 4:return this.possiblyLogPerformance(i),[7];case 5:return[2]}})})},t.prototype.getDecoder=function(){return this.secondaryDecoder?this.wasPrimaryDecoderUsedInLastDecode===!1?(this.wasPrimaryDecoderUsedInLastDecode=!0,this.primaryDecoder):(this.wasPrimaryDecoderUsedInLastDecode=!1,this.secondaryDecoder):this.primaryDecoder},t.prototype.possiblyLogPerformance=function(r){if(this.verbose){var i=performance.now()-r;this.executionResults.push(i),this.executions++,this.possiblyFlushPerformanceReport()}},t.prototype.possiblyFlushPerformanceReport=function(){if(!(this.executions<this.EXECUTIONS_TO_REPORT_PERFORMANCE)){for(var r=0,i=0,c=this.executionResults;i<c.length;i++){var d=c[i];r+=d}var f=r/this.executionResults.length;console.log("".concat(f," ms for ").concat(this.executionResults.length," last runs.")),this.executions=0,this.executionResults=[]}},t})(),os=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),Bo=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},Lo=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Gu=(function(){function t(r,i){this.name=r,this.track=i}return t.prototype.isSupported=function(){return this.track.getCapabilities?this.name in this.track.getCapabilities():!1},t.prototype.apply=function(r){var i={};i[this.name]=r;var c={advanced:[i]};return this.track.applyConstraints(c)},t.prototype.value=function(){var r=this.track.getSettings();if(this.name in r){var i=r[this.name];return i}return null},t})(),hw=(function(t){os(r,t);function r(i,c){return t.call(this,i,c)||this}return r.prototype.min=function(){return this.getCapabilities().min},r.prototype.max=function(){return this.getCapabilities().max},r.prototype.step=function(){return this.getCapabilities().step},r.prototype.apply=function(i){var c={};c[this.name]=i;var d={advanced:[c]};return this.track.applyConstraints(d)},r.prototype.getCapabilities=function(){this.failIfNotSupported();var i=this.track.getCapabilities(),c=i[this.name];return{min:c.min,max:c.max,step:c.step}},r.prototype.failIfNotSupported=function(){if(!this.isSupported())throw new Error("".concat(this.name," capability not supported"))},r})(Gu),pw=(function(t){os(r,t);function r(i){return t.call(this,"zoom",i)||this}return r})(hw),mw=(function(t){os(r,t);function r(i){return t.call(this,"torch",i)||this}return r})(Gu),gw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new pw(this.track)},t.prototype.torchFeature=function(){return new mw(this.track)},t})(),xw=(function(){function t(r,i,c){this.isClosed=!1,this.parentElement=r,this.mediaStream=i,this.callbacks=c,this.surface=this.createVideoElement(this.parentElement.clientWidth),r.append(this.surface)}return t.prototype.createVideoElement=function(r){var i=document.createElement("video");return i.style.width="".concat(r,"px"),i.style.display="block",i.muted=!0,i.setAttribute("muted","true"),i.playsInline=!0,i},t.prototype.setupSurface=function(){var r=this;this.surface.onabort=function(){throw"RenderedCameraImpl video surface onabort() called"},this.surface.onerror=function(){throw"RenderedCameraImpl video surface onerror() called"};var i=function(){var c=r.surface.clientWidth,d=r.surface.clientHeight;r.callbacks.onRenderSurfaceReady(c,d),r.surface.removeEventListener("playing",i)};this.surface.addEventListener("playing",i),this.surface.srcObject=this.mediaStream,this.surface.play()},t.create=function(r,i,c,d){return Bo(this,void 0,void 0,function(){var f,m;return Lo(this,function(x){switch(x.label){case 0:return f=new t(r,i,d),c.aspectRatio?(m={aspectRatio:c.aspectRatio},[4,f.getFirstTrackOrFail().applyConstraints(m)]):[3,2];case 1:x.sent(),x.label=2;case 2:return f.setupSurface(),[2,f]}})})},t.prototype.failIfClosed=function(){if(this.isClosed)throw"The RenderedCamera has already been closed."},t.prototype.getFirstTrackOrFail=function(){if(this.failIfClosed(),this.mediaStream.getVideoTracks().length===0)throw"No video tracks found";return this.mediaStream.getVideoTracks()[0]},t.prototype.pause=function(){this.failIfClosed(),this.surface.pause()},t.prototype.resume=function(r){this.failIfClosed();var i=this,c=function(){setTimeout(r,200),i.surface.removeEventListener("playing",c)};this.surface.addEventListener("playing",c),this.surface.play()},t.prototype.isPaused=function(){return this.failIfClosed(),this.surface.paused},t.prototype.getSurface=function(){return this.failIfClosed(),this.surface},t.prototype.getRunningTrackCapabilities=function(){return this.getFirstTrackOrFail().getCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getFirstTrackOrFail().getSettings()},t.prototype.applyVideoConstraints=function(r){return Bo(this,void 0,void 0,function(){return Lo(this,function(i){if("aspectRatio"in r)throw"Changing 'aspectRatio' in run-time is not yet supported.";return[2,this.getFirstTrackOrFail().applyConstraints(r)]})})},t.prototype.close=function(){if(this.isClosed)return Promise.resolve();var r=this;return new Promise(function(i,c){var d=r.mediaStream.getVideoTracks(),f=d.length,m=0;r.mediaStream.getVideoTracks().forEach(function(x){r.mediaStream.removeTrack(x),x.stop(),++m,m>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),i())})})},t.prototype.getCapabilities=function(){return new gw(this.getFirstTrackOrFail())},t})(),yw=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,i,c){return Bo(this,void 0,void 0,function(){return Lo(this,function(d){return[2,xw.create(r,this.mediaStream,i,c)]})})},t.create=function(r){return Bo(this,void 0,void 0,function(){var i,c;return Lo(this,function(d){switch(d.label){case 0:if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return i={audio:!1,video:r},[4,navigator.mediaDevices.getUserMedia(i)];case 1:return c=d.sent(),[2,new t(c)]}})})},t})(),ml=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},gl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},ww=(function(){function t(){}return t.failIfNotSupported=function(){return ml(this,void 0,void 0,function(){return gl(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return ml(this,void 0,void 0,function(){return gl(this,function(i){return[2,yw.create(r)]})})},t})(),_w=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},vw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Cw=(function(){function t(){}return t.retrieve=function(){if(navigator.mediaDevices)return t.getCamerasFromMediaDevices();var r=MediaStreamTrack;return MediaStreamTrack&&r.getSources?t.getCamerasFromMediaStreamTrack():t.rejectWithError()},t.rejectWithError=function(){var r=Rr.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Rr.insecureContextCameraQueryError()),Promise.reject(r)},t.isHttpsOrLocalhost=function(){if(location.protocol==="https:")return!0;var r=location.host.split(":")[0];return r==="127.0.0.1"||r==="localhost"},t.getCamerasFromMediaDevices=function(){return _w(this,void 0,void 0,function(){var r,i,c,d,f,m,x;return vw(this,function(v){switch(v.label){case 0:return r=function(g){for(var E=g.getVideoTracks(),A=0,D=E;A<D.length;A++){var T=D[A];T.enabled=!1,T.stop(),g.removeTrack(T)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return i=v.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=v.sent(),d=[],f=0,m=c;f<m.length;f++)x=m[f],x.kind==="videoinput"&&d.push({id:x.deviceId,label:x.label});return r(i),[2,d]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,i){var c=function(f){for(var m=[],x=0,v=f;x<v.length;x++){var g=v[x];g.kind==="video"&&m.push({id:g.id,label:g.label})}r(m)},d=MediaStreamTrack;d.getSources(c)})},t})(),Ot;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(Ot||(Ot={}));var bw=(function(){function t(){this.state=Ot.NOT_STARTED,this.onGoingTransactionNewState=Ot.UNKNOWN}return t.prototype.directTransition=function(r){this.failIfTransitionOngoing(),this.validateTransition(r),this.state=r},t.prototype.startTransition=function(r){return this.failIfTransitionOngoing(),this.validateTransition(r),this.onGoingTransactionNewState=r,this},t.prototype.execute=function(){if(this.onGoingTransactionNewState===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=Ot.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=Ot.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==Ot.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case Ot.UNKNOWN:throw"Transition from unknown is not allowed";case Ot.NOT_STARTED:this.failIfNewStateIs(r,[Ot.PAUSED]);break;case Ot.SCANNING:break;case Ot.PAUSED:break}},t.prototype.failIfNewStateIs=function(r,i){for(var c=0,d=i;c<d.length;c++){var f=d[c];if(r===f)throw"Cannot transition from ".concat(this.state," to ").concat(r)}},t})(),Aw=(function(){function t(r){this.stateManager=r}return t.prototype.startTransition=function(r){return this.stateManager.startTransition(r)},t.prototype.directTransition=function(r){this.stateManager.directTransition(r)},t.prototype.getState=function(){return this.stateManager.getState()},t.prototype.canScanFile=function(){return this.stateManager.getState()===Ot.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==Ot.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===Ot.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===Ot.PAUSED},t})(),Ew=(function(){function t(){}return t.create=function(){return new Aw(new bw)},t})(),Iw=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),ln=(function(t){Iw(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.DEFAULT_WIDTH=300,r.DEFAULT_WIDTH_OFFSET=2,r.FILE_SCAN_MIN_HEIGHT=300,r.FILE_SCAN_HIDDEN_CANVAS_PADDING=100,r.MIN_QR_BOX_SIZE=50,r.SHADED_LEFT=1,r.SHADED_RIGHT=2,r.SHADED_TOP=3,r.SHADED_BOTTOM=4,r.SHADED_REGION_ELEMENT_ID="qr-shaded-region",r.VERBOSE=!1,r.BORDER_SHADER_DEFAULT_COLOR="#ffffff",r.BORDER_SHADER_MATCH_COLOR="rgb(90, 193, 56)",r})(nw),Sw=(function(){function t(r,i){this.logger=i,this.fps=ln.SCAN_DEFAULT_FPS,r?(r.fps&&(this.fps=r.fps),this.disableFlip=r.disableFlip===!0,this.qrbox=r.qrbox,this.aspectRatio=r.aspectRatio,this.videoConstraints=r.videoConstraints):this.disableFlip=ln.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Wu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!zn(this.qrbox)},t.create=function(r,i){return new t(r,i)},t})(),xl=(function(){function t(r,i){if(this.element=null,this.canvasElement=null,this.scannerPausedUiElement=null,this.hasBorderShaders=null,this.borderShaders=null,this.qrMatch=null,this.renderedCamera=null,this.qrRegion=null,this.context=null,this.lastScanImageFile=null,this.isScanning=!1,!document.getElementById(r))throw"HTML Element with id=".concat(r," not found");this.elementId=r,this.verbose=!1;var c;typeof i=="boolean"?this.verbose=i===!0:i&&(c=i,this.verbose=c.verbose===!0,c.experimentalFeatures),this.logger=new ow(this.verbose),this.qrcode=new fw(this.getSupportedFormats(i),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Ew.create()}return t.prototype.start=function(r,i,c,d){var f=this;if(!r)throw"cameraIdOrConfig is required";if(!c||typeof c!="function")throw"qrCodeSuccessCallback is required and should be a function.";var m;d?m=d:m=this.verbose?this.logger.log:function(){};var x=Sw.create(i,this.logger);this.clearElement();var v=!1;x.videoConstraints&&(x.isMediaStreamConstraintsValid()?v=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var g=v,E=document.getElementById(this.elementId);E.clientWidth?E.clientWidth:ln.DEFAULT_WIDTH,E.style.position="relative",this.shouldScan=!0,this.element=E;var A=this,D=this.stateManagerProxy.startTransition(Ot.SCANNING);return new Promise(function(T,S){var P=g?x.videoConstraints:A.createVideoConstraints(r);if(!P){D.cancel(),S("videoConstraints should be defined");return}var M={};(!g||x.aspectRatio)&&(M.aspectRatio=x.aspectRatio);var ee={onRenderSurfaceReady:function($,F){A.setupUi($,F,x),A.isScanning=!0,A.foreverScan(x,c,m)}};ww.failIfNotSupported().then(function($){$.create(P).then(function(F){return F.render(f.element,M,ee).then(function(re){A.renderedCamera=re,D.execute(),T(null)}).catch(function(re){D.cancel(),S(re)})}).catch(function(F){D.cancel(),S(Rr.errorGettingUserMedia(F))})}).catch(function($){D.cancel(),S(Rr.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(Ot.PAUSED),this.showPausedState(),(zn(r)||r!==!0)&&(r=!1),r&&this.renderedCamera&&this.renderedCamera.pause()},t.prototype.resume=function(){if(!this.stateManagerProxy.isPaused())throw"Cannot result, scanner is not paused.";if(!this.renderedCamera)throw"renderedCamera doesn't exist while trying resume()";var r=this,i=function(){r.stateManagerProxy.directTransition(Ot.SCANNING),r.hidePausedState()};if(!this.renderedCamera.isPaused()){i();return}this.renderedCamera.resume(function(){i()})},t.prototype.getState=function(){return this.stateManagerProxy.getState()},t.prototype.stop=function(){var r=this;if(!this.stateManagerProxy.isScanning())throw"Cannot stop, scanner is not running or paused.";var i=this.stateManagerProxy.startTransition(Ot.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(ln.SHADED_REGION_ELEMENT_ID);f&&r.element.removeChild(f)}},d=this;return this.renderedCamera.close().then(function(){return d.renderedCamera=null,d.element&&(d.element.removeChild(d.canvasElement),d.canvasElement=null),c(),d.qrRegion&&(d.qrRegion=null),d.context&&(d.context=null),i.execute(),d.hidePausedState(),d.isScanning=!1,Promise.resolve()})},t.prototype.scanFile=function(r,i){return this.scanFileV2(r,i).then(function(c){return c.decodedText})},t.prototype.scanFileV2=function(r,i){var c=this;if(!r||!(r instanceof File))throw"imageFile argument is mandatory and should be instance of File. Use 'event.target.files[0]'.";if(zn(i)&&(i=!0),!this.stateManagerProxy.canScanFile())throw"Cannot start file scan - ongoing camera scan";return new Promise(function(d,f){c.possiblyCloseLastScanImageFile(),c.clearElement(),c.lastScanImageFile=URL.createObjectURL(r);var m=new Image;m.onload=function(){var x=m.width,v=m.height,g=document.getElementById(c.elementId),E=g.clientWidth?g.clientWidth:ln.DEFAULT_WIDTH,A=Math.max(g.clientHeight?g.clientHeight:v,ln.FILE_SCAN_MIN_HEIGHT),D=c.computeCanvasDrawConfig(x,v,E,A);if(i){var T=c.createCanvasElement(E,A,"qr-canvas-visible");T.style.display="inline-block",g.appendChild(T);var S=T.getContext("2d");if(!S)throw"Unable to get 2d context from canvas";S.canvas.width=E,S.canvas.height=A,S.drawImage(m,0,0,x,v,D.x,D.y,D.width,D.height)}var P=ln.FILE_SCAN_HIDDEN_CANVAS_PADDING,M=Math.max(m.width,D.width),ee=Math.max(m.height,D.height),$=M+2*P,F=ee+2*P,re=c.createCanvasElement($,F);g.appendChild(re);var Z=re.getContext("2d");if(!Z)throw"Unable to get 2d context from canvas";Z.canvas.width=$,Z.canvas.height=F,Z.drawImage(m,0,0,x,v,P,P,M,ee);try{c.qrcode.decodeRobustlyAsync(re).then(function(B){d(cl.createFromQrcodeResult(B))}).catch(f)}catch(B){f("QR code parse error, error = ".concat(B))}},m.onerror=f,m.onabort=f,m.onstalled=f,m.onsuspend=f,m.src=URL.createObjectURL(r)})},t.prototype.clear=function(){this.clearElement()},t.getCameras=function(){return Cw.retrieve()},t.prototype.getRunningTrackCapabilities=function(){return this.getRenderedCameraOrFail().getRunningTrackCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getRenderedCameraOrFail().getRunningTrackSettings()},t.prototype.getRunningTrackCameraCapabilities=function(){return this.getRenderedCameraOrFail().getCapabilities()},t.prototype.applyVideoConstraints=function(r){if(r){if(!Wu.isMediaStreamConstraintsValid(r,this.logger))throw"invalid videoConstaints passed, check logs for more details"}else throw"videoConstaints is required argument.";return this.getRenderedCameraOrFail().applyVideoConstraints(r)},t.prototype.getRenderedCameraOrFail=function(){if(this.renderedCamera==null)throw"Scanning is not in running state, call this API only when QR code scanning using camera is in running state.";return this.renderedCamera},t.prototype.getSupportedFormats=function(r){var i=[Ce.QR_CODE,Ce.AZTEC,Ce.CODABAR,Ce.CODE_39,Ce.CODE_93,Ce.CODE_128,Ce.DATA_MATRIX,Ce.MAXICODE,Ce.ITF,Ce.EAN_13,Ce.EAN_8,Ce.PDF_417,Ce.RSS_14,Ce.RSS_EXPANDED,Ce.UPC_A,Ce.UPC_E,Ce.UPC_EAN_EXTENSION];if(!r||typeof r=="boolean"||!r.formatsToSupport)return i;if(!Array.isArray(r.formatsToSupport))throw"configOrVerbosityFlag.formatsToSupport should be undefined or an array.";if(r.formatsToSupport.length===0)throw"Atleast 1 formatsToSupport is needed.";for(var c=[],d=0,f=r.formatsToSupport;d<f.length;d++){var m=f[d];tw(m)?c.push(m):this.logger.warn("Invalid format: ".concat(m," passed in config, ignoring."))}if(c.length===0)throw"None of formatsToSupport match supported values.";return c},t.prototype.getUseBarCodeDetectorIfSupported=function(r){if(zn(r))return!0;if(!zn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(zn(r.experimentalFeatures))return!0;var i=r.experimentalFeatures;return zn(i.useBarCodeDetectorIfSupported)?!0:i.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,i,c){var d=this,f=c.qrbox;this.validateQrboxConfig(f);var m=this.toQrdimensions(r,i,f),x=function(g){if(g<ln.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(ln.MIN_QR_BOX_SIZE,"px.")},v=function(g){return g>r&&(d.logger.warn("`qrbox.width` or `qrbox` is larger than the width of the root element. The width will be truncated to the width of root element."),g=r),g};x(m.width),x(m.height),m.width=v(m.width)},t.prototype.validateQrboxConfig=function(r){if(typeof r!="number"&&typeof r!="function"&&(r.width===void 0||r.height===void 0))throw"Invalid instance of QrDimensions passed for 'config.qrbox'. Both 'width' and 'height' should be set."},t.prototype.toQrdimensions=function(r,i,c){if(typeof c=="number")return{width:c,height:c};if(typeof c=="function")try{return c(r,i)}catch(d){throw new Error("qrbox config was passed as a function but it failed with unknown error"+d)}return c},t.prototype.setupUi=function(r,i,c){c.isShadedBoxEnabled()&&this.validateQrboxSize(r,i,c);var d=zn(c.qrbox)?{width:r,height:i}:c.qrbox;this.validateQrboxConfig(d);var f=this.toQrdimensions(r,i,d);f.height>i&&this.logger.warn("[Html5Qrcode] config.qrbox has height that isgreater than the height of the video stream. Shading will be ignored");var m=c.isShadedBoxEnabled()&&f.height<=i,x={x:0,y:0,width:r,height:i},v=m?this.getShadedRegionBounds(r,i,f):x,g=this.createCanvasElement(v.width,v.height),E={willReadFrequently:!0},A=g.getContext("2d",E);A.canvas.width=v.width,A.canvas.height=v.height,this.element.append(g),m&&this.possiblyInsertShadingElement(this.element,r,i,f),this.createScannerPausedUiElement(this.element),this.qrRegion=v,this.context=A,this.canvasElement=g},t.prototype.createScannerPausedUiElement=function(r){var i=document.createElement("div");i.innerText=Rr.scannerPaused(),i.style.display="none",i.style.position="absolute",i.style.top="0px",i.style.zIndex="1",i.style.background="rgba(9, 9, 9, 0.46)",i.style.color="#FFECEC",i.style.textAlign="center",i.style.width="100%",r.appendChild(i),this.scannerPausedUiElement=i},t.prototype.scanContext=function(r,i){var c=this;return this.stateManagerProxy.isPaused()?Promise.resolve(!1):this.qrcode.decodeAsync(this.canvasElement).then(function(d){return r(d.text,cl.createFromQrcodeResult(d)),c.possiblyUpdateShaders(!0),!0}).catch(function(d){c.possiblyUpdateShaders(!1);var f=Rr.codeParseError(d);return i(f,rw.createFrom(f)),!1})},t.prototype.foreverScan=function(r,i,c){var d=this;if(this.shouldScan&&this.renderedCamera){var f=this.renderedCamera.getSurface(),m=f.videoWidth/f.clientWidth,x=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var v=this.qrRegion.width*m,g=this.qrRegion.height*x,E=this.qrRegion.x*m,A=this.qrRegion.y*x;this.context.drawImage(f,E,A,v,g,0,0,this.qrRegion.width,this.qrRegion.height);var D=function(){d.foreverScanTimeout=setTimeout(function(){d.foreverScan(r,i,c)},d.getTimeoutFps(r.fps))};this.scanContext(i,c).then(function(T){!T&&r.disableFlip!==!0?(d.context.translate(d.context.canvas.width,0),d.context.scale(-1,1),d.scanContext(i,c).finally(function(){D()})):D()}).catch(function(T){d.logger.logError("Error happend while scanning context",T),D()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var i="facingMode",c="deviceId",d={user:!0,environment:!0},f="exact",m=function(S){if(S in d)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(S,"'")},x=Object.keys(r);if(x.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(x.length," keys");var v=Object.keys(r)[0];if(v!==i&&v!==c)throw"Only '".concat(i,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(v===i){var g=r.facingMode;if(typeof g=="string"){if(m(g))return{facingMode:g}}else if(typeof g=="object")if(f in g){if(m(g["".concat(f)]))return{facingMode:{exact:g["".concat(f)]}}}else throw"'facingMode' should be string or object with"+" ".concat(f," as key.");else{var E=typeof g;throw"Invalid type of 'facingMode' = ".concat(E)}}else{var A=r.deviceId;if(typeof A=="string")return{deviceId:A};if(typeof A=="object"){if(f in A)return{deviceId:{exact:A["".concat(f)]}};throw"'deviceId' should be string or object with"+" ".concat(f," as key.")}else{var D=typeof A;throw"Invalid type of 'deviceId' = ".concat(D)}}}var T=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(T)},t.prototype.computeCanvasDrawConfig=function(r,i,c,d){if(r<=c&&i<=d){var f=(c-r)/2,m=(d-i)/2;return{x:f,y:m,width:r,height:i}}else{var x=r,v=i;return r>c&&(i=c/r*i,r=c),i>d&&(r=d/i*r,i=d),this.logger.log("Image downsampled from "+"".concat(x,"X").concat(v)+" to ".concat(r,"X").concat(i,".")),this.computeCanvasDrawConfig(r,i,c,d)}},t.prototype.clearElement=function(){if(this.stateManagerProxy.isScanning())throw"Cannot clear while scan is ongoing, close it first.";var r=document.getElementById(this.elementId);r&&(r.innerHTML="")},t.prototype.possiblyUpdateShaders=function(r){this.qrMatch!==r&&(this.hasBorderShaders&&this.borderShaders&&this.borderShaders.length&&this.borderShaders.forEach(function(i){i.style.backgroundColor=r?ln.BORDER_SHADER_MATCH_COLOR:ln.BORDER_SHADER_DEFAULT_COLOR}),this.qrMatch=r)},t.prototype.possiblyCloseLastScanImageFile=function(){this.lastScanImageFile&&(URL.revokeObjectURL(this.lastScanImageFile),this.lastScanImageFile=null)},t.prototype.createCanvasElement=function(r,i,c){var d=r,f=i,m=document.createElement("canvas");return m.style.width="".concat(d,"px"),m.style.height="".concat(f,"px"),m.style.display="none",m.id=zn(c)?"qr-canvas":c,m},t.prototype.getShadedRegionBounds=function(r,i,c){if(c.width>r||c.height>i)throw"'config.qrbox' dimensions should not be greater than the dimensions of the root HTML element.";return{x:(r-c.width)/2,y:(i-c.height)/2,width:c.width,height:c.height}},t.prototype.possiblyInsertShadingElement=function(r,i,c,d){if(!(i-d.width<1||c-d.height<1)){var f=document.createElement("div");f.style.position="absolute";var m=(i-d.width)/2,x=(c-d.height)/2;if(f.style.borderLeft="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderRight="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderTop="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.boxSizing="border-box",f.style.top="0px",f.style.bottom="0px",f.style.left="0px",f.style.right="0px",f.id="".concat(ln.SHADED_REGION_ELEMENT_ID),i-d.width<11||c-d.height<11)this.hasBorderShaders=!1;else{var v=5,g=40;this.insertShaderBorders(f,g,v,-v,null,0,!0),this.insertShaderBorders(f,g,v,-v,null,0,!1),this.insertShaderBorders(f,g,v,null,-v,0,!0),this.insertShaderBorders(f,g,v,null,-v,0,!1),this.insertShaderBorders(f,v,g+v,-v,null,-v,!0),this.insertShaderBorders(f,v,g+v,null,-v,-v,!0),this.insertShaderBorders(f,v,g+v,-v,null,-v,!1),this.insertShaderBorders(f,v,g+v,null,-v,-v,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,i,c,d,f,m,x){var v=document.createElement("div");v.style.position="absolute",v.style.backgroundColor=ln.BORDER_SHADER_DEFAULT_COLOR,v.style.width="".concat(i,"px"),v.style.height="".concat(c,"px"),d!==null&&(v.style.top="".concat(d,"px")),f!==null&&(v.style.bottom="".concat(f,"px")),x?v.style.left="".concat(m,"px"):v.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(v),r.appendChild(v)},t.prototype.showPausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="block"},t.prototype.hidePausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="none"},t.prototype.getTimeoutFps=function(r){return 1e3/r},t})(),yl;(function(t){t[t.STATUS_DEFAULT=0]="STATUS_DEFAULT",t[t.STATUS_SUCCESS=1]="STATUS_SUCCESS",t[t.STATUS_WARNING=2]="STATUS_WARNING",t[t.STATUS_REQUESTING_PERMISSION=3]="STATUS_REQUESTING_PERMISSION"})(yl||(yl={}));const Tw={class:"scan-code"},Nw={class:"btn"},Ow={class:"left-back"},kw=_.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const i=r,c=Sd.IconScan(),d=_.reactive({html5QrCode:null}),f=_.ref(!1),m=()=>{if(!d.html5QrCode){it("摄像头无访问权限!");return}f.value=!0,d.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[oo.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},A=>{try{const T=new URL(A).searchParams.get("sessionId");T?i("scanSuccess",T):it("无效的二维码")}catch{it("无效的二维码")}E()}).catch(A=>{console.log(A),it({message:"二维码识别失败",duration:3e3})})},x=()=>{g().then(()=>{m()})},v=()=>{E()},g=()=>xl.getCameras().then(A=>{A&&A.length&&(d.html5QrCode=new xl("reader"))}).catch(()=>{it({message:"摄像头无访问权限!",duration:3e3})}),E=()=>{d.html5QrCode&&d.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),it("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{d.html5QrCode&&d.html5QrCode.isScanning&&E()}),(A,D)=>{const T=rs;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:D[0]||(D[0]=S=>x())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",Tw,[D[1]||(D[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",Nw,[_.createElementVNode("div",Ow,[_.createVNode(T,{name:"arrow-left",onClick:v})])])],512),[[_.vShow,f.value]])]))])}}}),Rw=nr(kw,[["__scopeId","data-v-2d988579"]]);function is(t,r,i){const c=_.computed(()=>t?Array.isArray(t)?t:t.value:[]),d=()=>{const E=c.value;if(E.length===0)return"";if(r){const D=typeof r=="string"?r:r.value;if(D&&E.some(T=>T.id===D))return D}const A=E.find(D=>D.isDefault);return A?A.id:E[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(E=>E.id===f.value))&&(f.value=d());else{let E;r&&typeof r=="string"&&(E=r),f=_.ref(E&&c.value.some(A=>A.id===E)?E:d())}(!m||i)&&_.watch(f,E=>{i&&i(E)});const x=_.computed(()=>c.value.find(E=>E.id===f.value)),v=_.computed(()=>c.value);return{selectedModelId:f,selectedModel:x,availableModels:v,setSelectedModel:E=>{c.value.find(D=>D.id===E)?f.value=E:console.warn(`[useModel] Model not found: ${E}`)}}}const Mw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Dw=Object.prototype.toString,Pw=t=>Dw.call(t)==="[object Object]",No=()=>{};function wi(t){return Array.isArray(t)?t:[t]}function Bw(t,r,i){return _.watch(t,r,{...i,immediate:!0})}const qu=Mw?window:void 0;function Xr(t){var r;const i=_.toValue(t);return(r=i?.$el)!==null&&r!==void 0?r:i}function _i(...t){const r=(c,d,f,m)=>(c.addEventListener(d,f,m),()=>c.removeEventListener(d,f,m)),i=_.computed(()=>{const c=wi(_.toValue(t[0])).filter(d=>d!=null);return c.every(d=>typeof d!="string")?c:void 0});return Bw(()=>{var c,d;return[(c=(d=i.value)===null||d===void 0?void 0:d.map(f=>Xr(f)))!==null&&c!==void 0?c:[qu].filter(f=>f!=null),wi(_.toValue(i.value?t[1]:t[0])),wi(_.unref(i.value?t[2]:t[1])),_.toValue(i.value?t[3]:t[2])]},([c,d,f,m],x,v)=>{if(!c?.length||!d?.length||!f?.length)return;const g=Pw(m)?{...m}:m,E=c.flatMap(A=>d.flatMap(D=>f.map(T=>r(A,D,T,g))));v(()=>{E.forEach(A=>A())})},{flush:"post"})}function Lw(t,r,i={}){const{window:c=qu,ignore:d=[],capture:f=!0,detectIframe:m=!1,controls:x=!1}=i;if(!c)return x?{stop:No,cancel:No,trigger:No}:No;let v=!0;const g=M=>_.toValue(d).some(ee=>{if(typeof ee=="string")return Array.from(c.document.querySelectorAll(ee)).some($=>$===M.target||M.composedPath().includes($));{const $=Xr(ee);return $&&(M.target===$||M.composedPath().includes($))}});function E(M){const ee=_.toValue(M);return ee&&ee.$.subTree.shapeFlag===16}function A(M,ee){const $=_.toValue(M),F=$.$.subTree&&$.$.subTree.children;return F==null||!Array.isArray(F)?!1:F.some(re=>re.el===ee.target||ee.composedPath().includes(re.el))}const D=M=>{const ee=Xr(t);if(M.target!=null&&!(!(ee instanceof Element)&&E(t)&&A(t,M))&&!(!ee||ee===M.target||M.composedPath().includes(ee))){if("detail"in M&&M.detail===0&&(v=!g(M)),!v){v=!0;return}r(M)}};let T=!1;const S=[_i(c,"click",M=>{T||(T=!0,setTimeout(()=>{T=!1},0),D(M))},{passive:!0,capture:f}),_i(c,"pointerdown",M=>{const ee=Xr(t);v=!g(M)&&!!(ee&&!M.composedPath().includes(ee))},{passive:!0}),m&&_i(c,"blur",M=>{setTimeout(()=>{const ee=Xr(t);let $=c.document.activeElement;for(;$?.shadowRoot;)$=$.shadowRoot.activeElement;$?.tagName==="IFRAME"&&!ee?.contains(c.document.activeElement)&&r(M)},0)},{passive:!0})].filter(Boolean),P=()=>S.forEach(M=>M());return x?{stop:P,cancel:()=>{v=!1},trigger:M=>{v=!0,D(M),v=!1}}:P}const Fw=["data-active","disabled"],Uw=_.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,i)=>(_.openBlock(),_.createElementBlock("button",{class:_.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[_.renderSlot(r.$slots,"default",{},void 0,!0)],10,Fw))}}),ss=nr(Uw,[["__scopeId","data-v-6f582cce"]]),zw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function Vw(t,r){return _.openBlock(),_.createElementBlock("svg",zw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),_.createElementVNode("path",{id:"矢量 90",d:"M13.683 2.26904C12.5753 1.16177 10.344 1.47577 8.02582 2.86527C5.70758 1.47576 3.47637 1.16179 2.36913 2.26904C1.2619 3.37646 1.57573 5.60771 2.96524 7.92589C1.57573 10.2441 1.2619 12.4754 2.36913 13.5827C3.47637 14.6901 5.7078 14.3762 8.02599 12.9867C10.344 14.3762 12.5752 14.6901 13.6825 13.5827C14.7901 12.4754 14.4761 10.2441 13.0866 7.92594C14.4761 5.60775 14.7902 3.37646 13.683 2.26904ZM10.8544 5.09764C11.4667 5.70995 12.0076 6.34819 12.4699 6.99044C12.7244 6.52061 12.9268 6.06037 13.077 5.60959C13.2948 4.95652 13.3832 4.38597 13.3426 3.89769C13.3089 3.49437 13.1869 3.18725 12.9754 2.97631C12.7645 2.76513 12.4574 2.64282 12.0541 2.60912C11.5658 2.56835 10.9955 2.65698 10.3422 2.87475C9.89153 3.02497 9.43121 3.22735 8.96135 3.48197C9.60365 3.94428 10.242 4.48527 10.8544 5.09764ZM5.70991 2.87475C6.16049 3.02494 6.62073 3.22729 7.09051 3.48185C6.44826 3.94412 5.81002 4.48507 5.19771 5.09739C4.58523 5.70982 4.04417 6.34819 3.58181 6.99055C3.32716 6.52071 3.1248 6.06037 2.97459 5.60959C2.75682 4.95677 2.66844 4.38597 2.70897 3.89769C2.74266 3.49437 2.86522 3.18725 3.07615 2.97631C3.28709 2.76513 3.59421 2.64282 3.99753 2.60912C4.4858 2.5686 5.0566 2.65698 5.70991 2.87475ZM5.90473 5.80466Q4.89236 6.81738 4.14938 7.92595C4.64428 8.66515 5.2294 9.3722 5.90473 10.0473C6.57966 10.7222 7.28696 11.3074 8.02584 11.8027C8.76507 11.3074 9.47197 10.7222 10.1474 10.0473C10.8222 9.37218 11.4074 8.66511 11.9027 7.92588Q11.1597 6.81736 10.1474 5.80466C9.47203 5.12956 8.7652 4.54447 8.02604 4.04937C7.28683 4.54447 6.5796 5.12956 5.90473 5.80466ZM7.99992 6.90011C7.44768 6.90011 6.99993 7.34787 6.99993 7.90011C6.99993 8.45235 7.44768 8.9001 7.99992 8.9001C8.55216 8.9001 8.99991 8.45235 8.99991 7.90011C8.99991 7.34787 8.55216 6.90011 7.99992 6.90011ZM10.3422 12.9772C9.89161 12.827 9.43138 12.6246 8.96148 12.37C9.60377 11.9077 10.242 11.3667 10.8544 10.7543C11.4667 10.142 12.0077 9.50369 12.4699 8.8614C12.7245 9.33127 12.9268 9.79154 13.077 10.2421C13.2948 10.8952 13.3832 11.4658 13.3426 11.954C13.3089 12.3574 13.1864 12.6647 12.9754 12.8757C12.7645 13.0866 12.4574 13.2089 12.0541 13.2426C11.5658 13.2834 10.995 13.195 10.3422 12.9772ZM2.97459 10.2421C3.12478 9.7914 3.32733 9.3312 3.58196 8.86141C4.04428 9.50369 4.5853 10.142 5.19771 10.7543C5.81003 11.3667 6.44827 11.9077 7.09052 12.37C6.62074 12.6246 6.16049 12.827 5.70991 12.9772C5.0566 13.195 4.48629 13.2834 3.99802 13.2426C3.5947 13.2089 3.28709 13.0866 3.07615 12.8757C2.86522 12.6647 2.74315 12.3574 2.70946 11.954C2.66844 11.4658 2.75682 10.8952 2.97459 10.2421Z",fill:"rgb(89,89,89)","fill-rule":"evenodd"},null,-1)])])}const Zw={render:Vw},$w={class:"button-text"},jw={class:"dropdown-menu__items"},Hw=["onClick"],Ww=_.defineComponent({__name:"ModelSwitch",props:_.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,i=_.useModel(t,"selectedModelId"),c=_.computed(()=>{const T=r.modelConfigs;return T?Array.isArray(T)?T:T.value:[]}),{selectedModel:d,availableModels:f,setSelectedModel:m}=is(c,i),x=_.ref(!1),v=T=>{m(T),E()},g=()=>{x.value=!x.value},E=()=>{x.value=!1},A=_.ref(null),D=_.ref(null);return Lw(D,()=>{E()},{ignore:[A]}),(T,S)=>(_.openBlock(),_.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[_.createVNode(ss,{size:"small",class:"action-button",rounded:"",onClick:g},{default:_.withCtx(()=>[(_.openBlock(),_.createBlock(_.resolveDynamicComponent(_.unref(d)?.icon),{width:16,height:16,class:"selected-model__icon"})),_.createElementVNode("span",$w,_.toDisplayString(_.unref(d)?.label),1),_.createVNode(_.unref(Zw),{width:16,height:16})]),_:1}),_.createVNode(_.Transition,{name:"dropdown"},{default:_.withCtx(()=>[x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:D},[_.createElementVNode("div",jw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),P=>(_.openBlock(),_.createElementBlock("div",{key:P.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":P.id===i.value}]),onClick:_.withModifiers(M=>v(P.id),["stop"])},[P.icon?(_.openBlock(),_.createBlock(_.resolveDynamicComponent(P.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):_.createCommentVNode("",!0),_.createElementVNode("span",null,_.toDisplayString(P.label),1)],10,Hw))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):_.createCommentVNode("",!0)],512))}}),Gw=nr(Ww,[["__scopeId","data-v-475491fd"]]),qw={key:0,class:"active-count"},Xw=_.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,i=_.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,d)=>(_.openBlock(),_.createBlock(ss,{size:"small",class:"action-button",active:i.value>0,rounded:"",onClick:d[0]||(d[0]=f=>c.$emit("click"))},{default:_.withCtx(()=>[_.createVNode(_.unref(Mr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),d[1]||(d[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),i.value>0?(_.openBlock(),_.createElementBlock("span",qw,_.toDisplayString(i.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),Yw=nr(Xw,[["__scopeId","data-v-c2a16c66"]]),Kw={"data-v-99394ae9":"",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",width:"16.000000",height:"16.000000",fill:"none",customFrame:"#000000",size:"16"};function Jw(t,r){return _.openBlock(),_.createElementBlock("svg",Kw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),_.createElementVNode("path",{id:"矢量 154",d:"M7.41014 2.09741L7.67112 2.70606C7.68333 2.73438 7.70579 2.75684 7.73411 2.76905L8.34275 3.02979C8.43968 3.0713 8.43968 3.20875 8.34275 3.25025L7.73411 3.51124C7.70579 3.52345 7.68333 3.54591 7.67112 3.57423L7.41014 4.18288C7.36863 4.2798 7.23118 4.2798 7.18968 4.18288L6.92894 3.57423C6.91673 3.54591 6.89427 3.52345 6.86595 3.51124L6.25731 3.25025C6.16039 3.20875 6.16039 3.0713 6.25731 3.02979L6.86595 2.76905C6.89427 2.75684 6.91673 2.73438 6.92894 2.70606L7.18968 2.09741C7.23118 2.00049 7.36863 2.00049 7.41014 2.09741ZM4.57006 11.9625L7.27611 8.09746L9.69944 4.63674L10.592 3.36207C10.6899 3.22218 10.8017 3.09864 10.9272 2.99122C11.0529 2.88404 11.1926 2.79297 11.3459 2.71802C11.4992 2.64332 11.657 2.58936 11.8191 2.5564C11.9809 2.52369 12.1472 2.51172 12.3176 2.52051C12.5315 2.53174 12.7336 2.57373 12.9238 2.64649C13.0678 2.70118 13.205 2.77369 13.3354 2.86353C13.4651 2.95289 13.5813 3.05445 13.6836 3.16822C13.8064 3.3047 13.9094 3.45851 13.9929 3.6299C14.0766 3.80128 14.1342 3.97731 14.1662 4.15773C14.1928 4.30861 14.2014 4.46267 14.1919 4.61989C14.1823 4.7781 14.1547 4.93069 14.1096 5.07791C14.0495 5.27249 13.958 5.45755 13.8352 5.63309L7.81321 14.2335Q7.66985 14.4382 7.48649 14.5965Q7.4825 14.6 7.4785 14.6034Q7.29063 14.7641 7.06102 14.8766C6.90794 14.9513 6.75072 15.0052 6.5891 15.0384C6.42748 15.0714 6.2617 15.0836 6.09154 15.0751C5.87743 15.0643 5.67504 15.0226 5.48436 14.9503C5.34008 14.8956 5.20287 14.8233 5.07201 14.7335C4.94213 14.6444 4.82592 14.5428 4.72313 14.4291C4.60033 14.2928 4.49682 14.1388 4.41308 13.9674C4.32934 13.7958 4.27123 13.6197 4.23925 13.4391C4.21239 13.2882 4.20385 13.1339 4.21313 12.9767C4.22265 12.8184 4.24999 12.6656 4.2954 12.5184C4.35546 12.3233 4.44701 12.138 4.57006 11.9625ZM4.7185 4.67361L4.18383 3.42579C4.11449 3.26441 3.88549 3.26441 3.81616 3.42579L3.28149 4.67361C3.26123 4.72073 3.22363 4.75832 3.17651 4.77859L1.92871 5.31326C1.76733 5.3826 1.76733 5.6116 1.92871 5.68094L3.17651 6.21561C3.22363 6.23587 3.26123 6.27347 3.28149 6.32059L3.81616 7.56841C3.88549 7.73003 4.11449 7.73003 4.18383 7.56841L4.7185 6.32059C4.73876 6.27347 4.77636 6.23587 4.82348 6.21561L6.07128 5.68094C6.23265 5.6116 6.23265 5.3826 6.07128 5.31326L4.82348 4.77859C4.77636 4.75832 4.73876 4.72073 4.7185 4.67361ZM5.38915 12.536C5.32006 12.6346 5.27099 12.7384 5.24169 12.8475C5.22533 12.9088 5.21532 12.9718 5.21141 13.0362C5.20726 13.1063 5.21044 13.1751 5.22094 13.2428C5.23583 13.3402 5.2661 13.4354 5.31151 13.5282C5.35692 13.6209 5.41332 13.7032 5.48095 13.775C5.52806 13.8248 5.58031 13.8695 5.63817 13.9093C5.69139 13.9459 5.7473 13.9764 5.80565 14.0011C5.9099 14.0453 6.02196 14.0702 6.14208 14.0763C6.2263 14.0807 6.30834 14.0746 6.38841 14.0582C6.46825 14.0418 6.54613 14.015 6.62181 13.9781C6.69749 13.941 6.76634 13.8961 6.8286 13.8429C6.89061 13.7899 6.94578 13.7289 6.99412 13.6598L11.9415 6.59405L10.3381 5.46789L5.38915 12.536ZM10.9168 4.6415L12.5202 5.76762L13.0161 5.05935C13.0849 4.96096 13.134 4.85745 13.1633 4.74831C13.1797 4.68703 13.1897 4.62429 13.1936 4.55959C13.198 4.48977 13.1948 4.42092 13.1843 4.35329C13.1694 4.25588 13.1394 4.16091 13.0942 4.06813C13.0488 3.97536 12.9926 3.89308 12.925 3.8213C12.8781 3.7715 12.8259 3.72682 12.7683 3.68703C12.7148 3.6504 12.6591 3.61964 12.6008 3.59474C12.4968 3.55079 12.385 3.5254 12.2651 3.5193C12.1806 3.51466 12.0984 3.52076 12.0183 3.53688C11.9382 3.55324 11.8601 3.57985 11.7841 3.61696C11.7082 3.65407 11.6391 3.69899 11.5771 3.75221C11.5149 3.80519 11.4594 3.86647 11.4111 3.93556L10.9168 4.6415Z",fill:"currentColor","fill-rule":"evenodd"},null,-1)])])}const Qw={render:Jw},e_=_.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=_.useModel(t,"genuiEnabled"),i=()=>{r.value=!r.value};return(c,d)=>(_.openBlock(),_.createBlock(ss,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:i},{default:_.withCtx(()=>[_.createVNode(_.unref(Qw),{width:16,height:16}),d[0]||(d[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),t_=nr(e_,[["__scopeId","data-v-7f3b0372"]]),n_={class:"bubble-image-wrapper"},r_=["src"],o_=["src"],i_=_.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=_.ref(!1),i=_.ref(null),c=()=>{r.value=!0},d=()=>{r.value=!1};return _.watch(r,f=>{f&&_.nextTick(()=>{i.value?.focus()})}),(f,m)=>(_.openBlock(),_.createElementBlock("div",n_,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,r_),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[r.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:d,onKeydown:_.withKeys(d,["esc"])},[_.createElementVNode("button",{ref_key:"closeButtonRef",ref:i,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:d},[...m[1]||(m[1]=[_.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[_.createElementVNode("path",{d:"M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z",fill:"currentColor"})],-1)])],512),_.createElementVNode("div",{class:"preview-content",onClick:m[0]||(m[0]=_.withModifiers(()=>{},["stop"]))},[_.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,o_)])],32)):_.createCommentVNode("",!0)]))]))}}),s_=nr(i_,[["__scopeId","data-v-91c75579"]]),a_=`
77
82
  <svg width="1em" height="1em" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
78
83
  <defs>
79
84
  <clipPath id="clip657_188316">
@@ -86,4 +91,4 @@ ${this.tempPrompt}
86
91
  <path id="path" d="M1.25 9.97C1.25 9.63 1.53 9.35 1.87 9.35L4.37 9.35C4.72 9.35 5 9.63 5 9.97C5 10.32 4.72 10.6 4.37 10.6L1.87 10.6C1.53 10.6 1.25 10.32 1.25 9.97ZM12.5 6.25C12.5 5.9 12.78 5.62 13.12 5.62L17.46 5.62C17.8 5.62 18.08 5.9 18.08 6.25C18.08 6.59 17.8 6.87 17.46 6.87L13.12 6.87C12.78 6.87 12.5 6.59 12.5 6.25ZM12.5 13.73C12.5 13.39 12.78 13.11 13.12 13.11L17.46 13.11C17.8 13.11 18.08 13.39 18.08 13.73C18.08 14.08 17.8 14.36 17.46 14.36L13.12 14.36C12.78 14.36 12.5 14.08 12.5 13.73Z" fill="currentColor" fill-opacity="1" fill-rule="nonzero"></path>
87
92
  </g>
88
93
  </svg>
89
- `,Ow=btoa(Nw),cl=`data:image/svg+xml;base64,${Ow}`,go=(t,r)=>{const[o,c]=t.split("#");return{id:r,text:o,inputMessage:c}},kw=t=>{const r={"zh-CN":{title:"OpenTiny NEXT",description:"我是你的私人智能助手",placeholder:"请输入您的问题",thinking:"正在思考中..."},"en-US":{title:"OpenTiny NEXT",description:"I am your private AI assistant",placeholder:"Please enter your question",thinking:"Thinking..."}},o=[{id:"office",text:t.locale==="zh-CN"?"办公助手":"Office Assistant",menus:["接收邮件#请同步邮箱的新邮件。","编写邮件#请新建一个邮件,收件人为 opentiny-next@meeting.com, 内容为举办一个临时会议。","安排会议#创建一个临时的在线会议,主题为讨论问题,时长为1小时。","整理文档#请分析附件中的销售情况,把销售额绘制成折线图。"].map(go)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(go)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(go)}],c=[{label:t.locale==="zh-CN"?"企业办公助手":"Enterprise Office Assistant",description:t.locale==="zh-CN"?"需要我帮你处理邮件、安排会议、整理文档,还是优化工作流程?":"Need help with emails, meeting scheduling, document organization, or workflow optimization?",icon:_.h("span",{style:{fontSize:"18px"}},"🧠"),badge:"NEW"},{label:t.locale==="zh-CN"?"开发技术支持":"Development Support",description:t.locale==="zh-CN"?"遇到代码问题?需要架构建议?还是想了解最新的技术趋势?":"Facing code issues? Need architecture advice? Or want to learn about latest tech trends?",icon:_.h("span",{style:{fontSize:"18px"}},"💻")},{label:t.locale==="zh-CN"?"项目管理协作":"Project Management",description:t.locale==="zh-CN"?"需要项目规划、任务分配、进度跟踪,还是团队协作建议?":"Need project planning, task assignment, progress tracking, or team collaboration advice?",icon:_.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:o,promptItems:c}},ul={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},Rw=t=>{console.log("message",t);const r=Object.keys(ul),o=r.findIndex(u=>t.includes(u));return(o!==-1?ul[r[o]]:t)||t},Mw={class:"tr-container__title"},Dw={style:{flex:"1"}},Pw={class:"chat-input"},Bw={class:"chat-input-pills"},Lw={class:"attachments-container"},Fw={class:"action-buttons"},Uw=_.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:_.mergeModels({sessionId:{type:String,default:void 0},agentRoot:{type:String,default:"https://agent.opentiny.design/api/v1/webmcp-trial/"},systemPrompt:{type:String,default:"你是一个智能助手,擅长通过工具调用帮助用户解决问题和满足用户需求"},title:{type:String,default:"OpenTiny NEXT"},locale:{type:String,default:"zh-CN"},remoteUrl:{type:String},menuItems:{type:Array},qrCodeUrl:{type:String},AILogoUrl:{type:String},roleAvatar:{type:Object,default:()=>({user:_.h(Or.IconUser,{style:{fontSize:"32px"}}),assistant:_.h(Ou,{style:{fontSize:"32px"}})})},mode:{type:String,default:"remoter"},llmConfig:{type:Object,default:()=>({baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt"})},inBrowserExt:{type:Boolean,default:!1},genUiComponents:{type:Object,default:()=>({})},customMarketMcpServers:{type:Array,default:()=>[]},mcpServers:{type:Object,default:void 0},llmConfigs:{type:Array,default:void 0},skills:{type:Object,default:void 0},layoutMode:{type:String,default:"fixed"},debugStream:{type:Boolean,default:!1},promptItems:{type:Array,default:void 0},pillItems:{type:Array,default:void 0}},{fullscreen:{type:Boolean,default:!1},fullscreenModifiers:{},show:{type:Boolean,default:!1},showModifiers:{},selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{},genUiAble:{type:Boolean,default:!1,required:!1},genUiAbleModifiers:{},enabledTools:{type:Object,default:void 0,required:!1},enabledToolsModifiers:{}}),emits:_.mergeModels(["before-ai-render","chat-stream-finish"],["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"]),setup(t,{expose:r,emit:o}){const c=t,u=o,f=_.useModel(t,"fullscreen"),m=_.useModel(t,"show"),g=_.useModel(t,"selectedModelId"),C=_.useModel(t,"genUiAble"),x=_.useModel(t,"enabledTools"),A=c.llmConfigs?_.toRef(c,"llmConfigs"):void 0,{selectedModel:v}=es(A,g),P=_.computed(()=>{const $e=A?.value?.length?v.value:c.llmConfig;return $e?!!($e.baseURL&&$e.genuiUrl):!1}),{hasMultimodalSupport:O,attachments:M,onFilesSelected:D,checkCanSendAttachments:B,processAttachments:G,cleanupAttachments:Z}=Cy({selectedModel:v,selectedModelId:g}),{agent:z,customAgentProvider:ee,conversationState:K,messages:V,messageState:U,inputMessage:J,abortRequest:S,senderRef:Te,sendMessage:ye,handleSendMessage:re,addMessage:xe,send:Me,createConversation:$,switchConversation:ge,deleteConversation:ne,getCurrentConversation:Q}=U2({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:u});_.watch(()=>c.systemPrompt,$e=>{ee.promptManager.setStatic($e)}),ee.isGenuiEnabled=C,ee.debugStream=c.debugStream;const me=_.toRef(c,"skills"),{processSkillMentions:fe}=ly({skillsRef:me,customAgentProvider:ee}),ie=async($e,ke)=>re($e,ke,fe),{welcomeIcon:pe,roles:vt}=py({props:c,messages:V,messageState:U,inputMessage:J,handleSendMessage:ie}),{showHistory:Ee,handleCreateConversation:Tt,handleHistorySelect:Ce,handleHistoryUpdateTitle:sn,handleHistoryDelete:Ue}=my({createConversation:$,switchConversation:ge,deleteConversation:ne,getCurrentConversation:Q,abortRequest:S,conversationState:K,customAgentProvider:ee}),Ht=()=>{if(v.value){const $e=v.value;ee.updateLLMConfig({model:$e.model||"",baseURL:$e.baseURL||"",genuiUrl:$e.genuiUrl||"",apiKey:$e.apiKey||"",providerType:$e.providerType,useReActMode:$e.useReActMode,llm:$e.llm,providerOptions:$e.providerOptions,headers:$e.headers})}else ee.updateLLMConfig(ee.llmConfig)};c.llmConfigs&&_.watch(v,Ht,{immediate:!0}),_.watch(C,Ht,{immediate:!0});const de={markdown:new Ut.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":$e=>_.h(dd.GenuiRenderer,{...$e,customActions:{continueChat:{execute:(ke,Ye)=>{const He=typeof ke=="string"?ke:ke.message,Ln=`${He},相关参数为:${JSON.stringify(Ye?.state||{})}`;xe({role:"user",content:Ln,uiContent:[{type:"markdown",content:He}]}),Me()}}},generating:Jn.GeneratingStatus.includes(U.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:Tw};function Oe($e,ke){de[$e]=ke}const{installedPlugins:yt,marketPlugins:be,pluginVisible:Xt,loadMcpServerToPlugin:Wt,togglePlugin:In,toggleTool:Ct,deletePlugin:Xe,addPluginCore:Ze,addPluginFromMarket:Sn,addPluginFromScan:ve,handleClientDisconnected:Bn,searchPlugin:Hn,syncInstalledPluginTools:Jt}=sy(z,x,cl);ay({onToolCatalogChanged:async()=>{await z.refreshTools(),Jt()}}),be.value=[...c.customMarketMcpServers];const Wn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Bt=kw(c),rr=_.computed(()=>c.pillItems??Bt.pillItems),R=_.computed(()=>c.promptItems??Bt.promptItems),oe=Bt.lang,{handleScanSuccess:qe,handleSessionIdInput:lt,initialize:xr}=gy({sessionId:_.toRef(c,"sessionId"),agentRoot:c.agentRoot,mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:_.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:m,addPluginFromScan:ve,inputMessage:J}),bt=async $e=>{if(await lt(J.value)||!B())return;const Ye=await G();try{await ie($e,Ye),Z()}catch(He){console.error("发送消息失败:",He)}},he=_.computed(()=>Jn.GeneratingStatus.includes(U.status)?oe[c.locale].thinking:oe[c.locale].placeholder),Nt=_.computed(()=>Jn.GeneratingStatus.includes(U.status)),nt=$e=>{J.value=$e.inputMessage};xr(),_.onMounted(async()=>{setTimeout(()=>{Tt()},100),z.onError=ke=>{ke&&Je(Rw(ke))};const $e=be.value.filter(ke=>ke.addState==="added"&&ke.enabled);for(const ke of $e)await Sn(ke);if(c.mcpServers)for(const[ke,Ye]of Object.entries(c.mcpServers))await Wt(ke,Ye)});const{handleCustomAdd:mt}=oy(z,yt,cl);return r({agent:z,welcomeIcon:pe,messages:V,messageState:U,roles:vt,inputMessage:J,senderRef:Te,abortRequest:S,sendMessage:ye,loadMcpServerToPlugin:Wt,handleClientDisconnected:Bn,addMessage:xe,installedPlugins:yt,addPluginCore:Ze,deletePlugin:Xe,registerContentRenderer:Oe}),($e,ke)=>(_.openBlock(),_.createBlock(_.unref(Ut.TrContainer),{show:m.value,"onUpdate:show":ke[11]||(ke[11]=Ye=>m.value=Ye),fullscreen:f.value,"onUpdate:fullscreen":ke[12]||(ke[12]=Ye=>f.value=Ye),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",Mw,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot($e.$slots,"operations",{},()=>[_.createVNode(_.unref(Ut.TrIconButton),{icon:_.unref(Or.IconNewSession),size:"28",svgSize:"20",onClick:ke[0]||(ke[0]=Ye=>_.unref(Tt)())},null,8,["icon"]),_.createVNode(_.unref(Ut.TrIconButton),{icon:_.unref(Or.IconHistory),size:"28",svgSize:"20",onClick:ke[1]||(ke[1]=Ye=>Ee.value=!_.unref(Ee))},null,8,["icon"]),_.createVNode(ew,{onScanSuccess:_.unref(qe)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(Ee)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:ke[4]||(ke[4]=Ye=>Ee.value=!1)},[_.createElementVNode("div",{class:"drawer-container",onClick:ke[3]||(ke[3]=_.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[ke[13]||(ke[13]=_.createElementVNode("h4",null,"历史会话",-1)),_.createVNode(_.unref(Ut.TrHistory),{class:"tr-history-demo",selected:_.unref(K).currentId,data:_.unref(K).conversations,showRenameControls:!0,onClose:ke[2]||(ke[2]=Ye=>Ee.value=!1),onItemClick:_.unref(Ce),onItemTitleChange:_.unref(sn),onItemAction:_.unref(Ue)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",Pw,[_.renderSlot($e.$slots,"suggestions",{},()=>[_.createElementVNode("div",Bw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(rr.value,Ye=>(_.openBlock(),_.createBlock(_.unref(Ut.TrDropdownMenu),{key:Ye.id,items:Ye.menus,onItemClick:nt,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref(Ut.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(Ye.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref(Ut.TrSender),{ref_key:"senderRef",ref:Te,mode:"multiple",modelValue:_.unref(J),"onUpdate:modelValue":ke[9]||(ke[9]=Ye=>_.isRef(J)?J.value=Ye:null),placeholder:he.value,clearable:!!_.unref(J),loading:Nt.value,showWordLimit:!0,maxLength:2e4,onSubmit:bt,onCancel:_.unref(S)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",Fw,[_.createVNode(yw,{"installed-plugins":_.unref(yt),onClick:ke[6]||(ke[6]=Ye=>Xt.value=!_.unref(Xt))},null,8,["installed-plugins"]),_.unref(A)&&_.unref(A).length>0?(_.openBlock(),_.createBlock(mw,{key:0,"model-configs":_.unref(A),"selected-model-id":g.value,"onUpdate:selectedModelId":ke[7]||(ke[7]=Ye=>g.value=Ye)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),P.value?(_.openBlock(),_.createBlock(bw,{key:1,"genui-enabled":C.value,"onUpdate:genuiEnabled":ke[8]||(ke[8]=Ye=>C.value=Ye)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(O)?(_.openBlock(),_.createBlock(_.unref(Ut.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(D)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(M).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",Lw,[_.createVNode(_.unref(Ut.TrAttachments),{items:_.unref(M),"onUpdate:items":ke[5]||(ke[5]=Ye=>_.isRef(M)?M.value=Ye:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref(Ut.TrMcpServerPicker),{visible:_.unref(Xt),"onUpdate:visible":ke[10]||(ke[10]=Ye=>_.isRef(Xt)?Xt.value=Ye:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(yt),marketPlugins:_.unref(be),"market-category-options":Wn.value,"installed-search-fn":_.unref(Hn),"market-search-fn":_.unref(Hn),onPluginToggle:_.unref(In),onPluginAdd:_.unref(Sn),onPluginDelete:_.unref(Xe),onToolToggle:_.unref(Ct),onPluginCreate:_.unref(mt)},{"header-actions":_.withCtx(()=>[_.renderSlot($e.$slots,"header-actions",{},void 0,!0)]),_:3},8,["visible","installedPlugins","marketPlugins","market-category-options","installed-search-fn","market-search-fn","onPluginToggle","onPluginAdd","onPluginDelete","onToolToggle","onPluginCreate"])])]),default:_.withCtx(()=>[_.createVNode(_.unref(Ut.TrBubbleProvider),{"content-renderers":de},{default:_.withCtx(()=>[_.unref(V).length===0?_.renderSlot($e.$slots,"welcome",{key:0},()=>[_.createElementVNode("div",Dw,[_.createVNode(_.unref(Ut.TrWelcome),{title:_.unref(oe)[t.locale].title,description:_.unref(oe)[t.locale].description,icon:_.unref(pe)},null,8,["title","description","icon"]),_.createVNode(_.unref(Ut.TrPrompts),{items:R.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(_.openBlock(),_.createBlock(_.unref(Ut.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(V),roles:_.unref(vt),"auto-scroll":"",loading:_.unref(U).status===_.unref(Jn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Do=nr(Uw,[["__scopeId","data-v-5ee9b3f3"]]);function zw(t){const r=t.sessionId?dl(t.sessionId,t.agentRoot):[],o=new Vn.AgentModelProvider({llmConfig:t.llmConfig,mcpServers:r}),c=_.ref("ready"),u=_.ref([]),f=_.ref("");let m=null;async function g(){const v=f.value;if(!v)return;if(/^\/[A-Za-z0-9-]{6,}$/.test(v)){A(v.slice(1));return}c.value="submitted",m=new AbortController;const P=await o.chatStream({message:v,model:t.model,system:t.systemPrompt||"",abortSignal:m.signal,maxSteps:t.maxSteps||5,onFinish:async()=>{await o.closeAll(),c.value="ready"},onError:()=>c.value="error",onAbort:()=>c.value="ready"});if(f.value="",t.processStream&&typeof t.processStream=="function"){t.processStream(P.fullStream,u,v);return}t.ui==="matechat"?Vw(P.fullStream,u,v):t.ui==="antx"?Zw(P.fullStream,u,v):t.ui==="elplusx"?$w(P.fullStream,u,v):t.ui==="tdchat"?Hw(P.fullStream,u,v):console.warn("暂时未实现")}function C(){m&&m.abort()}function x(){u.value=[],o.responseMessages=[]}async function A(v){const O=(await fetch(`${t.agentRoot}client?sessionId=${v}`).then(M=>M.json()))?.data?.sessionId||"";if(O){const M=dl(O,t.agentRoot);Object.assign(o.mcpServers,M)}}return{agent:o,status:c,messages:u,inputValue:f,chatStream:g,stopChat:C,newConversation:x,addSessionId:A}}function dl(t,r){if(!t)return{};const o=t.includes(",")?t.split(",").map(u=>u.trim()):[t],c={};return o.forEach(u=>{c[`mcp-server-${u}`]={type:"streamableHttp",url:`${r}mcp?sessionId=${u}`}}),c}async function Vw(t,r,o){r.value.push({from:"user",content:o,avatarConfig:{name:"user"}});let c={from:"model",content:"",avatarConfig:{name:"model"},id:Date.now().toString()};r.value.push(c),c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function Zw(t,r,o){r.value.push({from:"user",content:o}),r.value.push({from:"model",content:""});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function $w(t,r,o){r.value.push({from:"user",content:o}),r.value.push({from:"model",content:""});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function Hw(t,r,o){r.value.push({role:"user",content:o,avatar:"https://tdesign.gtimg.com/site/avatar.jpg"}),r.value.push({role:"assistant",content:"",avatar:"https://tdesign.gtimg.com/site/chat-avatar.png"});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}Do.install=function(t){t.component("tiny-remoter",Do)};exports.TinyRemoter=Do;exports.useModel=es;exports.useNextAgent=zw;
94
+ `,l_=btoa(a_),wl=`data:image/svg+xml;base64,${l_}`,vi=(t,r)=>{const[i,c]=t.split("#");return{id:r,text:i,inputMessage:c}},c_=t=>{const r={"zh-CN":{title:"OpenTiny NEXT",description:"我是你的私人智能助手",placeholder:"请输入您的问题",thinking:"正在思考中..."},"en-US":{title:"OpenTiny NEXT",description:"I am your private AI assistant",placeholder:"Please enter your question",thinking:"Thinking..."}},i=[{id:"office",text:t.locale==="zh-CN"?"办公助手":"Office Assistant",menus:["接收邮件#请同步邮箱的新邮件。","编写邮件#请新建一个邮件,收件人为 opentiny-next@meeting.com, 内容为举办一个临时会议。","安排会议#创建一个临时的在线会议,主题为讨论问题,时长为1小时。","整理文档#请分析附件中的销售情况,把销售额绘制成折线图。"].map(vi)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(vi)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(vi)}],c=[{label:t.locale==="zh-CN"?"企业办公助手":"Enterprise Office Assistant",description:t.locale==="zh-CN"?"需要我帮你处理邮件、安排会议、整理文档,还是优化工作流程?":"Need help with emails, meeting scheduling, document organization, or workflow optimization?",icon:_.h("span",{style:{fontSize:"18px"}},"🧠"),badge:"NEW"},{label:t.locale==="zh-CN"?"开发技术支持":"Development Support",description:t.locale==="zh-CN"?"遇到代码问题?需要架构建议?还是想了解最新的技术趋势?":"Facing code issues? Need architecture advice? Or want to learn about latest tech trends?",icon:_.h("span",{style:{fontSize:"18px"}},"💻")},{label:t.locale==="zh-CN"?"项目管理协作":"Project Management",description:t.locale==="zh-CN"?"需要项目规划、任务分配、进度跟踪,还是团队协作建议?":"Need project planning, task assignment, progress tracking, or team collaboration advice?",icon:_.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:i,promptItems:c}},_l={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},u_=t=>{console.log("message",t);const r=Object.keys(_l),i=r.findIndex(d=>t.includes(d));return(i!==-1?_l[r[i]]:t)||t},d_={class:"tr-container__title"},f_={style:{flex:"1"}},h_={class:"chat-input"},p_={class:"chat-input-pills"},m_={class:"attachments-container"},g_={class:"action-buttons"},x_=_.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:_.mergeModels({agentRoot:{type:String,default:"https://agent.opentiny.design/api/v1/webmcp-trial/"},sessionId:{type:String,default:void 0},menuItems:{type:Array},remoteUrl:{type:String},qrCodeUrl:{type:String},systemPrompt:{type:String,default:"你是一个智能助手,擅长通过工具调用帮助用户解决问题和满足用户需求"},title:{type:String,default:"OpenTiny NEXT"},locale:{type:String,default:"zh-CN"},AILogoUrl:{type:String},roleAvatar:{type:Object,default:()=>({user:_.h(Mr.IconUser,{style:{fontSize:"32px"}}),assistant:_.h(ju,{style:{fontSize:"32px"}})})},mode:{type:String,default:"remoter"},llmConfig:{type:Object,default:()=>({baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt"})},inBrowserExt:{type:Boolean,default:!1},genUiComponents:{type:Object,default:()=>({})},customMarketMcpServers:{type:Array,default:()=>[]},mcpServers:{type:Object,default:void 0},llmConfigs:{type:Array,default:void 0},skills:{type:Object,default:void 0},layoutMode:{type:String,default:"fixed"},debugStream:{type:Boolean,default:!1},promptItems:{type:Array,default:void 0},pillItems:{type:Array,default:void 0}},{fullscreen:{type:Boolean,default:!1},fullscreenModifiers:{},show:{type:Boolean,default:!1},showModifiers:{},selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{},genUiAble:{type:Boolean,default:!1,required:!1},genUiAbleModifiers:{},enabledTools:{type:Object,default:void 0,required:!1},enabledToolsModifiers:{}}),emits:_.mergeModels(["before-ai-render","chat-stream-finish"],["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"]),setup(t,{expose:r,emit:i}){const c=t,d=i,f=_.useModel(t,"fullscreen"),m=_.useModel(t,"show"),x=_.useModel(t,"selectedModelId"),v=_.useModel(t,"genUiAble"),g=_.useModel(t,"enabledTools"),E=c.llmConfigs?_.toRef(c,"llmConfigs"):void 0,{selectedModel:A}=is(E,x),D=_.computed(()=>{const Ee=E?.value?.length?A.value:c.llmConfig;return Ee?!!(Ee.baseURL&&Ee.genuiUrl):!1}),{hasMultimodalSupport:T,attachments:S,onFilesSelected:P,checkCanSendAttachments:M,processAttachments:ee,cleanupAttachments:$}=ew({selectedModel:A,selectedModelId:x}),{agent:F,customAgentProvider:re,conversationState:Z,messages:B,messageState:L,inputMessage:W,abortRequest:z,senderRef:we,sendMessage:G,handleSendMessage:me,addMessage:fe,send:te,createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te}=yx({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:d});_.watch(()=>c.systemPrompt,Ee=>{re.promptManager.setStatic(Ee)}),re.isGenuiEnabled=v,re.debugStream=c.debugStream;const Je=_.toRef(c,"skills"),{processSkillMentions:xe}=zy({skillsRef:Je,customAgentProvider:re}),$e=async(Ee,Oe)=>me(Ee,Oe,xe),{welcomeIcon:Ue,roles:Ze}=Wy({props:c,messages:B,messageState:L,inputMessage:W,handleSendMessage:$e}),{showHistory:qe,handleCreateConversation:ze,handleHistorySelect:ie,handleHistoryUpdateTitle:de,handleHistoryDelete:_e}=Gy({createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te,abortRequest:z,conversationState:Z,customAgentProvider:re}),Pe=()=>{if(A.value){const Ee=A.value;re.updateLLMConfig({model:Ee.model||"",baseURL:Ee.baseURL||"",genuiUrl:Ee.genuiUrl||"",apiKey:Ee.apiKey||"",providerType:Ee.providerType,useReActMode:Ee.useReActMode,llm:Ee.llm,providerOptions:Ee.providerOptions,headers:Ee.headers})}else re.updateLLMConfig(re.llmConfig)};c.llmConfigs&&_.watch(A,Pe,{immediate:!0}),_.watch(v,Pe,{immediate:!0});const ae={markdown:new Vt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":Ee=>_.h(Ed.GenuiRenderer,{...Ee,customActions:{continueChat:{execute:(Oe,rt)=>{const Ye=typeof Oe=="string"?Oe:Oe.message,Fn=`${Ye},相关参数为:${JSON.stringify(rt?.state||{})}`;fe({role:"user",content:Fn,uiContent:[{type:"markdown",content:Ye}]}),te()}}},generating:Kn.GeneratingStatus.includes(L.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:s_};function J(Ee,Oe){ae[Ee]=Oe}const{installedPlugins:ye,marketPlugins:Se,pluginVisible:Ve,loadMcpServerToPlugin:St,togglePlugin:vt,toggleTool:et,deletePlugin:nt,addPluginCore:Xe,addPluginFromMarket:In,addPluginFromScan:be,handleClientDisconnected:Bn,searchPlugin:$n,syncInstalledPluginTools:qt}=Fy(F,g,wl);Uy({onToolCatalogChanged:async()=>{await F.refreshTools(),qt()}}),Se.value=[...c.customMarketMcpServers];const jn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Ft=c_(c),rr=_.computed(()=>c.pillItems??Ft.pillItems),sn=_.computed(()=>c.promptItems??Ft.promptItems),At=Ft.lang,{handleScanSuccess:or,handleSessionIdInput:Ln,initialize:wr}=qy({sessionId:_.toRef(c,"sessionId"),agentRoot:_.toRef(c,"agentRoot"),mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:_.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:m,addPluginFromScan:be,inputMessage:W}),gt=async Ee=>{if(await Ln(W.value)||!M())return;const rt=await ee();try{await $e(Ee,rt),$()}catch(Ye){console.error("发送消息失败:",Ye)}},ge=_.computed(()=>Kn.GeneratingStatus.includes(L.status)?At[c.locale].thinking:At[c.locale].placeholder),O=_.computed(()=>Kn.GeneratingStatus.includes(L.status)),ne=Ee=>{W.value=Ee.inputMessage};wr(),_.onMounted(async()=>{setTimeout(()=>{ze()},100),F.onError=Oe=>{Oe&&it(u_(Oe))};const Ee=Se.value.filter(Oe=>Oe.addState==="added"&&Oe.enabled);for(const Oe of Ee)await In(Oe);if(c.mcpServers)for(const[Oe,rt]of Object.entries(c.mcpServers))await St(Oe,rt)});const{handleCustomAdd:Me}=Ly(F,ye,wl);return r({agent:F,welcomeIcon:Ue,messages:B,messageState:L,roles:Ze,inputMessage:W,senderRef:we,abortRequest:z,sendMessage:G,loadMcpServerToPlugin:St,handleClientDisconnected:Bn,addMessage:fe,installedPlugins:ye,addPluginCore:Xe,deletePlugin:nt,registerContentRenderer:J,async refreshPluginTools(){await F.refreshTools(),qt()}}),(Ee,Oe)=>(_.openBlock(),_.createBlock(_.unref(Vt.TrContainer),{show:m.value,"onUpdate:show":Oe[11]||(Oe[11]=rt=>m.value=rt),fullscreen:f.value,"onUpdate:fullscreen":Oe[12]||(Oe[12]=rt=>f.value=rt),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",d_,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot(Ee.$slots,"operations",{},()=>[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconNewSession),size:"28",svgSize:"20",onClick:Oe[0]||(Oe[0]=rt=>_.unref(ze)())},null,8,["icon"]),_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconHistory),size:"28",svgSize:"20",onClick:Oe[1]||(Oe[1]=rt=>qe.value=!_.unref(qe))},null,8,["icon"]),_.createVNode(Rw,{onScanSuccess:_.unref(or)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(qe)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:Oe[4]||(Oe[4]=rt=>qe.value=!1)},[_.createElementVNode("div",{class:"drawer-container",onClick:Oe[3]||(Oe[3]=_.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[Oe[13]||(Oe[13]=_.createElementVNode("h4",null,"历史会话",-1)),_.createVNode(_.unref(Vt.TrHistory),{class:"tr-history-demo",selected:_.unref(Z).currentId,data:_.unref(Z).conversations,showRenameControls:!0,onClose:Oe[2]||(Oe[2]=rt=>qe.value=!1),onItemClick:_.unref(ie),onItemTitleChange:_.unref(de),onItemAction:_.unref(_e)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",h_,[_.renderSlot(Ee.$slots,"suggestions",{},()=>[_.createElementVNode("div",p_,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(rr.value,rt=>(_.openBlock(),_.createBlock(_.unref(Vt.TrDropdownMenu),{key:rt.id,items:rt.menus,onItemClick:ne,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(rt.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref(Vt.TrSender),{ref_key:"senderRef",ref:we,mode:"multiple",modelValue:_.unref(W),"onUpdate:modelValue":Oe[9]||(Oe[9]=rt=>_.isRef(W)?W.value=rt:null),placeholder:ge.value,clearable:!!_.unref(W),loading:O.value,showWordLimit:!0,maxLength:2e4,onSubmit:gt,onCancel:_.unref(z)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",g_,[_.createVNode(Yw,{"installed-plugins":_.unref(ye),onClick:Oe[6]||(Oe[6]=rt=>Ve.value=!_.unref(Ve))},null,8,["installed-plugins"]),_.unref(E)&&_.unref(E).length>0?(_.openBlock(),_.createBlock(Gw,{key:0,"model-configs":_.unref(E),"selected-model-id":x.value,"onUpdate:selectedModelId":Oe[7]||(Oe[7]=rt=>x.value=rt)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),D.value?(_.openBlock(),_.createBlock(t_,{key:1,"genui-enabled":v.value,"onUpdate:genuiEnabled":Oe[8]||(Oe[8]=rt=>v.value=rt)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(T)?(_.openBlock(),_.createBlock(_.unref(Vt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(P)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(S).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",m_,[_.createVNode(_.unref(Vt.TrAttachments),{items:_.unref(S),"onUpdate:items":Oe[5]||(Oe[5]=rt=>_.isRef(S)?S.value=rt:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref(Vt.TrMcpServerPicker),{visible:_.unref(Ve),"onUpdate:visible":Oe[10]||(Oe[10]=rt=>_.isRef(Ve)?Ve.value=rt:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(ye),marketPlugins:_.unref(Se),"market-category-options":jn.value,"installed-search-fn":_.unref($n),"market-search-fn":_.unref($n),onPluginToggle:_.unref(vt),onPluginAdd:_.unref(In),onPluginDelete:_.unref(nt),onToolToggle:_.unref(et),onPluginCreate:_.unref(Me)},{"header-actions":_.withCtx(()=>[_.renderSlot(Ee.$slots,"header-actions",{},void 0,!0)]),_:3},8,["visible","installedPlugins","marketPlugins","market-category-options","installed-search-fn","market-search-fn","onPluginToggle","onPluginAdd","onPluginDelete","onToolToggle","onPluginCreate"])])]),default:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrBubbleProvider),{"content-renderers":ae},{default:_.withCtx(()=>[_.unref(B).length===0?_.renderSlot(Ee.$slots,"welcome",{key:0},()=>[_.createElementVNode("div",f_,[_.createVNode(_.unref(Vt.TrWelcome),{title:_.unref(At)[t.locale].title,description:_.unref(At)[t.locale].description,icon:_.unref(Ue)},null,8,["title","description","icon"]),_.createVNode(_.unref(Vt.TrPrompts),{items:sn.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(_.openBlock(),_.createBlock(_.unref(Vt.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(B),roles:_.unref(Ze),"auto-scroll":"",loading:_.unref(L).status===_.unref(Kn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Fi=nr(x_,[["__scopeId","data-v-635a2faf"]]);Fi.install=function(t){t.component("tiny-remoter",Fi)};exports.TinyRemoter=Fi;exports.useModel=is;