@opentiny/next-remoter 0.4.2 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/composable/useRouteBasedTools.d.ts +2 -2
- package/dist/next-remoter-runtime.es.js +54138 -54059
- package/dist/next-remoter.cjs.js +34 -34
- package/dist/next-remoter.es.js +3543 -3534
- package/package.json +2 -2
package/dist/next-remoter.cjs.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("vue"),
|
|
2
|
-
Error message: ${Ol(i)}`,cause:i}),this[zl]=!0,this.text=r}static isInstance(r){return
|
|
3
|
-
Error message: ${Ol(i)}`,cause:i}),this[Xl]=!0,this.value=r}static isInstance(r){return
|
|
4
|
-
`)===-1&&Z.indexOf("\r")===-1){m.push(Z),x+=Z.length,
|
|
5
|
-
`,B);for(;L!==-1;){if(B===L){A>0&&r({id:g,event:
|
|
6
|
-
`,B);continue}const W=Z.charCodeAt(B);if(Is(Z,B,W)){const z=Z.charCodeAt(B+5)===
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("vue"),Zt=require("@opentiny/tiny-robot"),Ed=require("@opentiny/genui-sdk-vue"),Kn=require("@opentiny/tiny-robot-kit"),Rr=require("@opentiny/tiny-robot-svgs"),Xr=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 $t=Od,Al="AI_APICallError",El=`vercel.ai.error.${Al}`,kd=Symbol.for(El),Il,Vn=class extends $t{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 $t.hasMarker(r,El)}};Il=kd;var Sl="AI_EmptyResponseBodyError",Tl=`vercel.ai.error.${Sl}`,Rd=Symbol.for(Tl),Nl,Md=class extends $t{constructor({message:r="Empty response body"}={}){super({name:Sl,message:r}),this[Nl]=!0}static isInstance(r){return $t.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 $t{constructor({message:r,cause:i,argument:c}){super({name:kl,message:r,cause:i}),this[Ml]=!0,this.argument=c}static isInstance(r){return $t.hasMarker(r,Rl)}};Ml=Dd;var Pl="AI_InvalidResponseDataError",Bl=`vercel.ai.error.${Pl}`,Pd=Symbol.for(Bl),Ll,bs=class extends $t{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 $t.hasMarker(r,Bl)}};Ll=Pd;var Fl="AI_JSONParseError",Ul=`vercel.ai.error.${Fl}`,Bd=Symbol.for(Ul),zl,Oo=class extends $t{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 $t.hasMarker(r,Ul)}};zl=Bd;var Vl="AI_LoadAPIKeyError",Zl=`vercel.ai.error.${Vl}`,Ld=Symbol.for(Zl),$l,wo=class extends $t{constructor({message:r}){super({name:Vl,message:r}),this[$l]=!0}static isInstance(r){return $t.hasMarker(r,Zl)}};$l=Ld;var jl="AI_NoSuchModelError",Hl=`vercel.ai.error.${jl}`,Fd=Symbol.for(Hl),Wl,As=class extends $t{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 $t.hasMarker(t,Hl)}};Wl=Fd;var Gl="AI_TypeValidationError",ql=`vercel.ai.error.${Gl}`,Ud=Symbol.for(ql),Xl,zd=class Ci extends $t{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 $t.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 $t{constructor({functionality:r,message:i=`'${r}' functionality not supported.`}){super({name:Yl,message:i}),this[Jl]=!0,this.functionality=r}static isInstance(r){return $t.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,cr=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,P,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),D();return}if(Z.indexOf(`
|
|
4
|
+
`)===-1&&Z.indexOf("\r")===-1){m.push(Z),x+=Z.length,D();return}m.push(Z);const B=m.join("");m.length=0,x=0;const L=M(B);L!==""&&(m.push(L),x=L.length),D()}function D(){f!==void 0&&(x+E.length<=f||(T=!0,m.length=0,x=0,g=void 0,E="",A=0,P=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:P,data:E}),g=void 0,E="",A=0,P=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)===cr?B+6:B+5,we=Z.slice(z,L);if(A===0&&Z.charCodeAt(L+1)===Es){r({id:g,event:P,data:we}),g=void 0,E="",P=void 0,B=L+2,L=Z.indexOf(`
|
|
7
7
|
`,B);continue}E=A===0?we:`${E}
|
|
8
|
-
${we}`,A++}else Ss(Z,B,W)?
|
|
8
|
+
${we}`,A++}else Ss(Z,B,W)?P=Z.slice(Z.charCodeAt(B+6)===cr?B+7:B+6,L)||void 0:ee(Z,B,L);B=L+1,L=Z.indexOf(`
|
|
9
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)===
|
|
11
|
-
${q}`,A++;return}if(Ss(Z,B,W)){
|
|
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(`
|
|
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)===cr?B+6:B+5,q=Z.slice(te,L);E=A===0?q:`${E}
|
|
11
|
+
${q}`,A++;return}if(Ss(Z,B,W)){P=Z.slice(Z.charCodeAt(B+6)===cr?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)===cr?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)===cr?2:1))}return}const z=Z.slice(B,L),we=z.indexOf(":");if(we===-1){$(z,"",z);return}const G=z.slice(0,we),pe=z.charCodeAt(we+1)===cr?2:1,de=z.slice(we+pe);$(G,de,z)}function $(Z,B,L){switch(Z){case"event":P=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:P,data:E}),g=void 0,E="",A=0,P=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,P=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 Jn(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 at(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 Vr(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 mr(t,r,i){const c=new t._zod.constr(r??t._zod.def);return(!r||i?.parent)&&(c._zod.parent=t),c}function Se(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 mr(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 mr(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 mr(t,i)}function Qd(t,r){return mr(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 mr(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 mr(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 fr(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 Qn(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=>Qn(v,f,Jn())));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=>Qn(v,f,Jn())));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=>Qn(m,d,Jn())))}:{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=>Qn(m,d,Jn())))}:{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]*$/,sn=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)=>{sn.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)=>{sn.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)=>{sn.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)=>{sn.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;sn.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;sn.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;sn.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;sn.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)=>{sn.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)=>{sn.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)=>{sn.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)=>{sn.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
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},
|
|
14
|
+
`))}}const X1={major:4,minor:0,patch:0},pt=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,P=E._zod.check(f);if(P instanceof Promise&&x?.async===!1)throw new Qr;if(g||P instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await P,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)=>{pt.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)=>{pt.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)=>{pt.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)=>{pt.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)=>{pt.init(t,r),t._zod.parse=i=>i}),E0=oe("$ZodUnknown",(t,r)=>{pt.init(t,r),t._zod.parse=i=>i}),I0=oe("$ZodNever",(t,r)=>{pt.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(...fr(i,t.issues)),r.value[i]=t.value}const S0=oe("$ZodArray",(t,r)=>{pt.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(...fr(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(...fr(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)=>{pt.init(t,r);const i=Ui(()=>{const A=Object.keys(r.shape);for(const T of A)if(!(r.shape[T]instanceof pt))throw new Error(`Invalid element at key "${T}": expected a Zod schema`);const P=qd(r.shape);return{shape:r.shape,keys:A,keySet:new Set(A),numKeys:A.length,optionalKeys:new Set(P)}});at(t._zod,"propValues",()=>{const A=r.shape,P={};for(const T in A){const S=A[T]._zod;if(S.values){P[T]??(P[T]=new Set);for(const D of S.values)P[T].add(D)}}return P});const c=A=>{const P=new q1(["shape","payload","ctx"]),T=i.value,S=$=>{const F=Vr($);return`shape[${F}]._zod.run({ value: input[${F}], issues: [] }, ctx)`};P.write("const input = payload.value;");const D=Object.create(null);let M=0;for(const $ of T.keys)D[$]=`key_${M++}`;P.write("const newResult = {}");for(const $ of T.keys)if(T.optionalKeys.has($)){const F=D[$];P.write(`const ${F} = ${S($)};`);const re=Vr($);P.write(`
|
|
15
15
|
if (${F}.issues.length) {
|
|
16
16
|
if (input[${re}] === undefined) {
|
|
17
17
|
if (${re} in input) {
|
|
@@ -30,19 +30,19 @@ ${B}`,A++;break;case"id":g=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.t
|
|
|
30
30
|
} else {
|
|
31
31
|
newResult[${re}] = ${F}.value;
|
|
32
32
|
}
|
|
33
|
-
`)}else{const F=
|
|
33
|
+
`)}else{const F=D[$];P.write(`const ${F} = ${S($)};`),P.write(`
|
|
34
34
|
if (${F}.issues.length) payload.issues = payload.issues.concat(${F}.issues.map(iss => ({
|
|
35
35
|
...iss,
|
|
36
|
-
path: iss.path ? [${
|
|
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>
|
|
36
|
+
path: iss.path ? [${Vr($)}, ...iss.path] : [${Vr($)}]
|
|
37
|
+
})));`),P.write(`newResult[${Vr($)}] = ${F}.value`)}P.write("payload.value = newResult;"),P.write("return payload;");const ee=P.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,P)=>{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&&P?.async===!1&&P.jitless!==!0)d||(d=c(r.shape)),A=d(A,P);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:[]},P),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 D=[],M=E.keySet,ee=g._zod,$=ee.def.type;for(const F of Object.keys(T)){if(M.has(F))continue;if($==="never"){D.push(F);continue}const re=ee.run({value:T[F],issues:[]},P);re instanceof Promise?S.push(re.then(Z=>vo(Z,A,F))):vo(re,A,F)}return D.length&&A.issues.push({code:"unrecognized_keys",keys:D,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=>Qn(f,c,Jn())))}),r}const xc=oe("$ZodUnion",(t,r)=>{pt.init(t,r),at(t._zod,"optin",()=>r.options.some(i=>i._zod.optin==="optional")?"optional":void 0),at(t._zod,"optout",()=>r.options.some(i=>i._zod.optout==="optional")?"optional":void 0),at(t._zod,"values",()=>{if(r.options.every(i=>i._zod.values))return new Set(r.options.flatMap(i=>Array.from(i._zod.values)))}),at(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;at(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)=>{pt.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)=>{pt.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(...fr(v,E.issues)),i.value[v]=E.value})):(g.issues.length&&i.issues.push(...fr(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=>Qn(g,c,Jn())),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(...fr(m,g.issues)),i.value[x.value]=g.value})):(v.issues.length&&i.issues.push(...fr(m,v.issues)),i.value[x.value]=v.value)}}return f.length?Promise.all(f).then(()=>i):i}}),R0=oe("$ZodEnum",(t,r)=>{pt.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)=>{pt.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)=>{pt.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)=>{pt.init(t,r),t._zod.optin="optional",t._zod.optout="optional",at(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),at(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)=>{pt.init(t,r),at(t._zod,"optin",()=>r.innerType._zod.optin),at(t._zod,"optout",()=>r.innerType._zod.optout),at(t._zod,"pattern",()=>{const i=r.innerType._zod.pattern;return i?new RegExp(`^(${Vi(i.source)}|null)$`):void 0}),at(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)=>{pt.init(t,r),t._zod.optin="optional",at(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)=>{pt.init(t,r),t._zod.optin="optional",at(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)=>{pt.init(t,r),at(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)=>{pt.init(t,r),t._zod.optin="optional",at(t._zod,"optout",()=>r.innerType._zod.optout),at(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=>Qn(m,c,Jn()))},input:i.value}),i.issues=[]),i)):(i.value=d.value,d.issues.length&&(i.value=r.catchValue({...i,error:{issues:d.issues.map(f=>Qn(f,c,Jn()))},input:i.value}),i.issues=[]),i)}}),V0=oe("$ZodPipe",(t,r)=>{pt.init(t,r),at(t._zod,"values",()=>r.in._zod.values),at(t._zod,"optin",()=>r.in._zod.optin),at(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)=>{pt.init(t,r),at(t._zod,"propValues",()=>r.innerType._zod.propValues),at(t._zod,"values",()=>r.innerType._zod.values),at(t._zod,"optin",()=>r.innerType._zod.optin),at(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)=>{pt.init(t,r),at(t._zod,"innerType",()=>r.getter()),at(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),at(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),at(t._zod,"optin",()=>t._zod.innerType._zod.optin),at(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)=>{sn.init(t,r),pt.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 Wr=H0();function W0(t,r){return new t({type:"string",...Se(r)})}function G0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Se(r)})}function Fs(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Se(r)})}function q0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Se(r)})}function X0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Se(r)})}function Y0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Se(r)})}function K0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Se(r)})}function J0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Se(r)})}function Q0(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Se(r)})}function ef(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Se(r)})}function tf(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Se(r)})}function nf(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Se(r)})}function rf(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Se(r)})}function of(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Se(r)})}function sf(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Se(r)})}function af(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Se(r)})}function lf(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Se(r)})}function cf(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Se(r)})}function uf(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Se(r)})}function df(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Se(r)})}function ff(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Se(r)})}function hf(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Se(r)})}function pf(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Se(r)})}function mf(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Se(r)})}function gf(t,r){return new t({type:"string",format:"date",check:"string_format",...Se(r)})}function xf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...Se(r)})}function yf(t,r){return new t({type:"string",format:"duration",check:"string_format",...Se(r)})}function wf(t,r){return new t({type:"number",checks:[],...Se(r)})}function _f(t,r){return new t({type:"number",coerce:!0,checks:[],...Se(r)})}function vf(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Se(r)})}function Cf(t,r){return new t({type:"boolean",...Se(r)})}function bf(t,r){return new t({type:"null",...Se(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",...Se(r)})}function Us(t,r){return new hc({check:"less_than",...Se(r),value:t,inclusive:!1})}function ci(t,r){return new hc({check:"less_than",...Se(r),value:t,inclusive:!0})}function zs(t,r){return new pc({check:"greater_than",...Se(r),value:t,inclusive:!1})}function ui(t,r){return new pc({check:"greater_than",...Se(r),value:t,inclusive:!0})}function Vs(t,r){return new B1({check:"multiple_of",...Se(r),value:t})}function wc(t,r){return new F1({check:"max_length",...Se(r),maximum:t})}function Mo(t,r){return new U1({check:"min_length",...Se(r),minimum:t})}function _c(t,r){return new z1({check:"length_equals",...Se(r),length:t})}function Sf(t,r){return new V1({check:"string_format",format:"regex",...Se(r),pattern:t})}function Tf(t){return new Z1({check:"string_format",format:"lowercase",...Se(t)})}function Nf(t){return new $1({check:"string_format",format:"uppercase",...Se(t)})}function Of(t,r){return new j1({check:"string_format",format:"includes",...Se(r),includes:t})}function kf(t,r){return new H1({check:"string_format",format:"starts_with",...Se(r),prefix:t})}function Rf(t,r){return new W1({check:"string_format",format:"ends_with",...Se(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,...Se(i)})}function Ff(t,r,i){return new t({type:"custom",check:"custom",fn:r,...Se(i)})}class Zs{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??Wr,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},P=r._zod.parent;if(P)x.ref=P,this.process(P,A),this.seen.get(P).isParent=!0;else{const T=x.schema;switch(d.type){case"string":{const S=T;S.type="string";const{minimum:D,maximum:M,format:ee,patterns:$,contentEncoding:F}=r._zod.bag;if(typeof D=="number"&&(S.minLength=D),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:D,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 D=="number"&&(S.minimum=D,typeof re=="number"&&(re>=D?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:D,maximum:M}=r._zod.bag;typeof D=="number"&&(S.minItems=D),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 D=d.shape;for(const $ in D)S.properties[$]=this.process(D[$],{...A,path:[...A.path,"properties",$]});const M=new Set(Object.keys(D)),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((D,M)=>this.process(D,{...A,path:[...A.path,"anyOf",M]}));break}case"intersection":{const S=T,D=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(D)?D.allOf:[D],...ee(M)?M.allOf:[M]];S.allOf=$;break}case"tuple":{const S=T;S.type="array";const D=d.items.map(($,F)=>this.process($,{...A,path:[...A.path,"prefixItems",F]}));if(this.target==="draft-2020-12"?S.prefixItems=D:S.items=D,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,D=nc(d.entries);D.every(M=>typeof M=="number")&&(S.type="number"),D.every(M=>typeof M=="string")&&(S.type="string"),S.enum=D;break}case"literal":{const S=T,D=[];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");D.push(Number(M))}else D.push(M);if(D.length!==0)if(D.length===1){const M=D[0];S.type=M===null?"null":typeof M,S.const=M}else D.every(M=>typeof M=="number")&&(S.type="number"),D.every(M=>typeof M=="string")&&(S.type="string"),D.every(M=>typeof M=="boolean")&&(S.type="string"),D.every(M=>M===null)&&(S.type="null"),S.enum=D;break}case"file":{const S=T,D={type:"string",format:"binary",contentEncoding:"binary"},{minimum:M,maximum:ee,mime:$}=r._zod.bag;M!==void 0&&(D.minLength=M),ee!==void 0&&(D.maxLength=ee),$?$.length===1?(D.contentMediaType=$[0],Object.assign(S,D)):S.anyOf=$.map(F=>({...D,contentMediaType:F})):Object.assign(S,D);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,D=r._zod.pattern;if(!D)throw new Error("Pattern not found in template literal");S.type="string",S.pattern=D.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 D=c.external.registry.get(E[0])?.id,M=c.external.uri??($=>$);if(D)return{ref:M(D)};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:P,defId:T}=f(E);A.def={...A.schema},T&&(A.defId=T);const S=A.schema;for(const D in S)delete S[D];S.$ref=P};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>
|
|
38
38
|
|
|
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
|
|
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.39";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
|
|
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 P=this.seen.get(E),T=P.def??P.schema,S={...T};if(P.ref===null)return;const D=P.ref;if(P.ref=null,D){x(D,A);const M=this.seen.get(D).schema;M.$ref&&A.target==="draft-7"?(T.allOf=T.allOf??[],T.allOf.push(M)):(Object.assign(T,M),Object.assign(T,S))}P.isParent||this.override({zodSchema:E,jsonSchema:T,path:P.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),vt=oe("ZodType",(t,r)=>(pt.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)=>mr(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=>it([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 Wr.add(c,{description:i}),c},Object.defineProperty(t,"description",{get(){return Wr.get(t)?.description},configurable:!0}),t.meta=(...i)=>{if(i.length===0)return Wr.get(t);const c=t.clone();return Wr.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),vt.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),vt.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),vt.init(t,r)});function Mt(t){return Cf(xh,t)}const yh=oe("ZodNull",(t,r)=>{b0.init(t,r),vt.init(t,r)});function bc(t){return bf(yh,t)}const wh=oe("ZodAny",(t,r)=>{A0.init(t,r),vt.init(t,r)});function gr(){return Af(wh)}const _h=oe("ZodUnknown",(t,r)=>{E0.init(t,r),vt.init(t,r)});function bn(){return Ef(_h)}const vh=oe("ZodNever",(t,r)=>{I0.init(t,r),vt.init(t,r)});function Ch(t){return If(vh,t)}const bh=oe("ZodArray",(t,r)=>{S0.init(t,r),vt.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),vt.init(t,r),at(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:bn()}),t.loose=()=>t.clone({...t._zod.def,catchall:bn()}),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},...Se(r)};return new Ah(i)}const Ac=oe("ZodUnion",(t,r)=>{xc.init(t,r),vt.init(t,r),t.options=r.options});function it(t,r){return new Ac({type:"union",options:t,...Se(r)})}const Eh=oe("ZodDiscriminatedUnion",(t,r)=>{Ac.init(t,r),N0.init(t,r)});function gt(t,r,i){return new Eh({type:"union",options:r,discriminator:t,...Se(i)})}const Ih=oe("ZodIntersection",(t,r)=>{O0.init(t,r),vt.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),vt.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function _t(t,r,i){return new Th({type:"record",keyType:t,valueType:r,...Se(i)})}const Ai=oe("ZodEnum",(t,r)=>{R0.init(t,r),vt.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:[],...Se(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:[],...Se(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,...Se(r)})}const Nh=oe("ZodLiteral",(t,r)=>{M0.init(t,r),vt.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],...Se(r)})}const Oh=oe("ZodTransform",(t,r)=>{D0.init(t,r),vt.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),vt.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),vt.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),vt.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),vt.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),vt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Lh(t,r){return new Ic({type:"nonoptional",innerType:t,...Se(r)})}const Fh=oe("ZodCatch",(t,r)=>{z0.init(t,r),vt.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),vt.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),vt.init(t,r)});function Zh(t){return new Vh({type:"readonly",innerType:t})}const $h=oe("ZodLazy",(t,r)=>{$0.init(t,r),vt.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),vt.init(t,r)});function Hh(t){const r=new sn({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 $e;(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"})($e||($e={}));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 Zr(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=Zr({...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,...Zr(c[0])});break}r.push({role:"user",content:c.map(m=>{const x=Zr(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=Zr(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=Zr(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:gr().nullish(),code:it([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:P}){var T,S,D,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:P,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:(D=g.name)!=null?D:"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,P,T,S,D,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 pe={[this.providerOptionsName]:{},...await((d=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:d.call(c,{parsedBody:L}))},de=(f=B.usage)==null?void 0:f.completion_tokens_details;return de?.accepted_prediction_tokens!=null&&(pe[this.providerOptionsName].acceptedPredictionTokens=de?.accepted_prediction_tokens),de?.rejected_prediction_tokens!=null&&(pe[this.providerOptionsName].rejectedPredictionTokens=de?.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=(P=B.usage)==null?void 0:P.completion_tokens_details)==null?void 0:T.reasoning_tokens)!=null?S:void 0,cachedInputTokens:(ee=(M=(D=B.usage)==null?void 0:D.prompt_tokens_details)==null?void 0:M.cached_tokens)!=null?ee:void 0},providerMetadata:pe,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 P=this.providerOptionsName;let T=!1,S=!1;return{stream:x.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:c})},transform(D,M){var ee,$,F,re,Z,B,L,W,z,we,G,pe,de;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){g="error",M.enqueue({type:"error",error:D.error});return}const te=D.value;if(f?.processChunk(D.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:ze,prompt_tokens_details:Xe,completion_tokens_details:Ve}=te.usage;E.promptTokens=Te??void 0,E.completionTokens=Je??void 0,E.totalTokens=ze??void 0,Ve?.reasoning_tokens!=null&&(E.completionTokensDetails.reasoningTokens=Ve?.reasoning_tokens),Ve?.accepted_prediction_tokens!=null&&(E.completionTokensDetails.acceptedPredictionTokens=Ve?.accepted_prediction_tokens),Ve?.rejected_prediction_tokens!=null&&(E.completionTokensDetails.rejectedPredictionTokens=Ve?.rejected_prediction_tokens),Xe?.cached_tokens!=null&&(E.promptTokensDetails.cachedTokens=Xe?.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 Xe=v[Je];((re=Xe.function)==null?void 0:re.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}),Ys(Xe.function.arguments)&&(M.enqueue({type:"tool-input-end",id:Xe.id}),M.enqueue({type:"tool-call",toolCallId:(B=Xe.id)!=null?B:bo(),toolName:Xe.function.name,input:Xe.function.arguments}),Xe.hasFinished=!0));continue}const ze=v[Je];ze.hasFinished||(((L=Te.function)==null?void 0:L.arguments)!=null&&(ze.function.arguments+=(z=(W=Te.function)==null?void 0:W.arguments)!=null?z:""),M.enqueue({type:"tool-input-delta",id:ze.id,delta:(we=Te.function.arguments)!=null?we:""}),((G=ze.function)==null?void 0:G.name)!=null&&((pe=ze.function)==null?void 0:pe.arguments)!=null&&Ys(ze.function.arguments)&&(M.enqueue({type:"tool-input-end",id:ze.id}),M.enqueue({type:"tool-call",toolCallId:(de=ze.id)!=null?de:bo(),toolName:ze.function.name,input:ze.function.arguments}),ze.hasFinished=!0))}},flush(D){var M,ee,$,F,re,Z;T&&D.enqueue({type:"reasoning-end",id:"reasoning-0"}),S&&D.enqueue({type:"text-end",id:"txt-0"});for(const L of v.filter(W=>!W.hasFinished))D.enqueue({type:"tool-input-end",id:L.id}),D.enqueue({type:"tool-call",toolCallId:(M=L.id)!=null?M:bo(),toolName:L.function.name,input:L.function.arguments});const B={[P]:{},...f?.buildMetadata()};E.completionTokensDetails.acceptedPredictionTokens!=null&&(B[P].acceptedPredictionTokens=E.completionTokensDetails.acceptedPredictionTokens),E.completionTokensDetails.rejectedPredictionTokens!=null&&(B[P].rejectedPredictionTokens=E.completionTokensDetails.rejectedPredictionTokens),D.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=>it([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:_t(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:_t(w(),_t(w(),gr())).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 P=[...Array.isArray(v.prompt)?v.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...v,prompt:P}}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,Ot=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,Jt=class extends(ia=Ot,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 Ot.hasMarker(t,Pc)}},Bc="AI_EmptyResponseBodyError",Lc=`vercel.ai.error.${Bc}`,Pp=Symbol.for(Lc),sa,aa,Bp=class extends(aa=Ot,sa=Pp,aa){constructor({message:t="Empty response body"}={}){super({name:Bc,message:t}),this[sa]=!0}static isInstance(t){return Ot.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=Ot,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 Ot.hasMarker(t,zc)}},Zc="AI_InvalidPromptError",$c=`vercel.ai.error.${Zc}`,Fp=Symbol.for($c),ua,da,Up=class extends(da=Ot,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 Ot.hasMarker(t,$c)}},jc="AI_InvalidResponseDataError",Hc=`vercel.ai.error.${jc}`,zp=Symbol.for(Hc),fa,ha,fi=class extends(ha=Ot,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 Ot.hasMarker(t,Hc)}},Wc="AI_JSONParseError",Gc=`vercel.ai.error.${Wc}`,Vp=Symbol.for(Gc),pa,ma,Do=class extends(ma=Ot,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 Ot.hasMarker(t,Gc)}},qc="AI_LoadAPIKeyError",Xc=`vercel.ai.error.${qc}`,Zp=Symbol.for(Xc),ga,xa,Ao=class extends(xa=Ot,ga=Zp,xa){constructor({message:t}){super({name:qc,message:t}),this[ga]=!0}static isInstance(t){return Ot.hasMarker(t,Xc)}},Yc="AI_TooManyEmbeddingValuesForCallError",Kc=`vercel.ai.error.${Yc}`,$p=Symbol.for(Kc),ya,wa,jp=class extends(wa=Ot,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 Ot.hasMarker(t,Kc)}},Jc="AI_TypeValidationError",Qc=`vercel.ai.error.${Jc}`,Hp=Symbol.for(Qc),_a,va,no=class Si extends(va=Ot,_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 Ot.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=Ot,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 Ot.hasMarker(t,tu)}};function An(...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 Or(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,un=class extends(Ea=Ot,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 Ot.hasMarker(t,ru)}};function em(t=globalThis){return t.window!=null}function tm(t){let r;try{r=new URL(t)}catch{throw new un({url:t,message:`Invalid URL: ${t}`})}if(r.protocol==="data:")return;if(r.protocol!=="http:"&&r.protocol!=="https:")throw new un({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});const i=r.hostname.toLowerCase().replace(/\.+$/,"");if(!i)throw new un({url:t,message:"URL must have a hostname"});if(i==="localhost"||i.endsWith(".local")||i.endsWith(".localhost"))throw new un({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 un({url:t,message:`URL with IPv6 address ${i} is not allowed`});return}if(ou(i)){if(iu(i))throw new un({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,P,T,S]=E.split(".").map(Number);x.push(A<<8|P,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 un({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 un({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 un({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 un({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 un({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 un.isInstance(d)?d:new un({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()}`},on=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 Jt({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return cm(t)?new Jt({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.40";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]=ur(i[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(ur):ur(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(ur)),t.allOf!=null&&(t.allOf=t.allOf.map(ur)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(ur));const{definitions:r}=t;if(r!=null)for(const i of Object.keys(r))r[i]=ur(r[i]);return t}function ur(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 hn(){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)!==$e.ZodAny&&(f.items=lt(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 lt(t.type._def,r)}var Em=(t,r)=>lt(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{...lt(t.innerType._def,r),default:t.defaultValue()}}function Tm(t,r){return r.effectStrategy==="input"?lt(t.schema._def,r):hn()}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=[lt(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),lt(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,_n={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":vn(i,"email",c.message,r);break;case"format:idn-email":vn(i,"idn-email",c.message,r);break;case"pattern:zod":Kt(i,_n.email,c.message,r);break}break;case"url":vn(i,"uri",c.message,r);break;case"uuid":vn(i,"uuid",c.message,r);break;case"regex":Kt(i,c.regex,c.message,r);break;case"cuid":Kt(i,_n.cuid,c.message,r);break;case"cuid2":Kt(i,_n.cuid2,c.message,r);break;case"startsWith":Kt(i,RegExp(`^${pi(c.value,r)}`),c.message,r);break;case"endsWith":Kt(i,RegExp(`${pi(c.value,r)}$`),c.message,r);break;case"datetime":vn(i,"date-time",c.message,r);break;case"date":vn(i,"date",c.message,r);break;case"time":vn(i,"time",c.message,r);break;case"duration":vn(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":{Kt(i,RegExp(pi(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&vn(i,"ipv4",c.message,r),c.version!=="v4"&&vn(i,"ipv6",c.message,r);break}case"base64url":Kt(i,_n.base64url,c.message,r);break;case"jwt":Kt(i,_n.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Kt(i,_n.ipv4Cidr,c.message,r),c.version!=="v4"&&Kt(i,_n.ipv6Cidr,c.message,r);break}case"emoji":Kt(i,_n.emoji(),c.message,r);break;case"ulid":{Kt(i,_n.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{vn(i,"binary",c.message,r);break}case"contentEncoding:base64":{i.contentEncoding="base64";break}case"pattern:zod":{Kt(i,_n.base64,c.message,r);break}}break}case"nanoid":Kt(i,_n.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 vn(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 Kt(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
42
|
]))`;continue}else if(d[g]==="$"){f+=`($|(?=[\r
|
|
43
43
|
]))`;continue}}if(c.s&&d[g]==="."){f+=x?`${d[g]}\r
|
|
44
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(()=>{if(!cg(t))throw new Error(`Standard schema vendor '${t["~standard"].vendor}' does not support JSON Schema conversion.`);return 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){return t["~standard"].jsonSchema!=null}function ug(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 dg(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 fg(t){return"_zod"in t}function Le(t,r){return fg(t)?dg(t):ug(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 hg({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 pg=()=>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=pg()})=>{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 mg({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 gg=new TextDecoder;async function wu({response:t,url:r}){return gg.decode(await au({response:t,url:r}))}var xg=({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:hg({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}},yg=()=>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 wg(t){return t?.replace(/\/$/,"")}var Qi=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),En=xg({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(()=>{}),_g({frame:A,url:c,requestBodyValues:d,responseHeaders:f});if(i(E.value))return x}}finally{v.cancel().catch(()=>{}),v.releaseLock()}}function _g({frame:t,url:r,requestBodyValues:i,responseHeaders:c}){var d;const f=vg(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:Cg(f),responseHeaders:c,responseBody:JSON.stringify(t),data:t})}function vg(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 Cg(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 bg(t){return JSON.stringify(t===void 0?{}:t)}function Un(t){var r;return(r=t?.openai)==null?void 0:r.promptCacheBreakpoint}function Ag({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:bg(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 Eg=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()}))),Ig=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]))),Sg=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 Tg({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 Ng=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:Sg}))!=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}=Ag({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}=Tg({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(Eg),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(Ig),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:P=>"error"in P?P.error:void 0,isOutputChunk:Og,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 Og(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 kg({prompt:t,user:r="user",assistant:i="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
|
|
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=lt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?i:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===$e.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)===$e.ZodEnum)return{...v,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===$e.ZodBranded&&t.keyType._def.type._def.typeName===$e.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=lt(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||hn(),c=lt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||hn();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:hn()}}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)=>lt(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=lt(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=lt(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 lt(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 lt(t.innerType._def,r);const c=lt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:hn()},c]}:hn()},Gm=(t,r)=>{if(r.pipeStrategy==="input")return lt(t.in._def,r);if(r.pipeStrategy==="output")return lt(t.out._def,r);const i=lt(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=lt(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 lt(t.type._def,r)}function Xm(t,r){const c={type:"array",uniqueItems:!0,items:lt(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)=>lt(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[]),additionalItems:lt(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((i,c)=>lt(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[])}}function Km(){return{not:hn()}}function Jm(){return hn()}var Qm=(t,r)=>lt(t.innerType._def,r),eg=(t,r,i)=>{switch(r){case $e.ZodString:return hu(t,i);case $e.ZodNumber:return Zm(t);case $e.ZodObject:return $m(t,i);case $e.ZodBigInt:return bm(t);case $e.ZodBoolean:return Am();case $e.ZodDate:return fu(t,i);case $e.ZodUndefined:return Km();case $e.ZodNull:return Fm();case $e.ZodArray:return Cm(t,i);case $e.ZodUnion:case $e.ZodDiscriminatedUnion:return Um(t,i);case $e.ZodIntersection:return km(t,i);case $e.ZodTuple:return Ym(t,i);case $e.ZodRecord:return pu(t,i);case $e.ZodLiteral:return Rm(t);case $e.ZodEnum:return Nm(t);case $e.ZodNativeEnum:return Bm(t);case $e.ZodNullable:return Vm(t,i);case $e.ZodOptional:return Wm(t,i);case $e.ZodMap:return Pm(t,i);case $e.ZodSet:return Xm(t,i);case $e.ZodLazy:return()=>t.getter()._def;case $e.ZodPromise:return qm(t,i);case $e.ZodNaN:case $e.ZodNever:return Lm();case $e.ZodEffects:return Tm(t,i);case $e.ZodAny:return hn();case $e.ZodUnknown:return Jm();case $e.ZodDefault:return Sm(t,i);case $e.ZodBranded:return du(t,i);case $e.ZodReadonly:return Qm(t,i);case $e.ZodCatch:return Em(t,i);case $e.ZodPipeline:return Gm(t,i);case $e.ZodFunction:case $e.ZodVoid:case $e.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 lt(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"?lt(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`),hn()):r.$refStrategy==="seen"?hn():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 P;return{...g,[E]:(P=lt(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,E]},!0))!=null?P:hn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(i=lt(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?i:hn(),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 Ue(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(()=>{if(!cg(t))throw new Error(`Standard schema vendor '${t["~standard"].vendor}' does not support JSON Schema conversion.`);return 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){return t["~standard"].jsonSchema!=null}function ug(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 dg(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 fg(t){return"_zod"in t}function Le(t,r){return fg(t)?dg(t):ug(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 hg({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 En({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 pg=()=>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=pg()})=>{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)||Jt.isInstance(E)?E:new Jt({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)||Jt.isInstance(g))?g:new Jt({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 mg({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 gg=new TextDecoder;async function wu({response:t,url:r}){return gg.decode(await au({response:t,url:r}))}var xg=({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 Jt({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 Jt({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 Jt({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:hg({stream:r.body,schema:t})}},pr=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 Jt({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}},yg=()=>async({response:t,url:r,requestBodyValues:i})=>{const c=ao(t);if(!t.body)throw new Jt({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 Jt({message:"Failed to read response as array buffer",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:d})}};function wg(t){return t?.replace(/\/$/,"")}var Qi=N({error:N({message:w(),type:w().nullish(),param:gr().nullish(),code:it([w(),j()]).nullish()})}),In=xg({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(()=>{}),_g({frame:A,url:c,requestBodyValues:d,responseHeaders:f});if(i(E.value))return x}}finally{v.cancel().catch(()=>{}),v.releaseLock()}}function _g({frame:t,url:r,requestBodyValues:i,responseHeaders:c}){var d;const f=vg(t);return new Jt({message:(d=f?.message)!=null?d:"OpenAI stream failed before any output was generated",url:r,requestBodyValues:i,statusCode:f==null?500:Cg(f),responseHeaders:c,responseBody:JSON.stringify(t),data:t})}function vg(t){var r;const i=$r(t);if(i==null)return;if(i.type==="response.failed"){const d=$r(i.response),f=$r(d?.error);return typeof f?.message=="string"?{message:f.message,code:Oa(f.code),type:"response.failed",frame:t}:void 0}const c=(r=$r(i.error))!=null?r:i;return typeof c.message=="string"&&($r(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 Cg(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 $r(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,P=(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-(P??0),cacheRead:A,cacheWrite:P},outputTokens:{total:E,text:E-T,reasoning:T},raw:t}}function bg(t){return JSON.stringify(t===void 0?{}:t)}function Un(t){var r;return(r=t?.openai)==null?void 0:r.promptCacheBreakpoint}function Ag({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,P,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 D=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${D};base64,${Or(g.data)}`,detail:(P=(A=g.providerOptions)==null?void 0:A.openai)==null?void 0:P.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:Or(g.data),format:"wav"},...S!=null&&{prompt_cache_breakpoint:S}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Or(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,${Or(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 P=[];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":{P.push({id:T.toolCallId,type:"function",function:{name:T.toolName,arguments:bg(T.input)}});break}}d.push({role:"assistant",content:A?E:P.length>0?g||null:g,tool_calls:P.length>0?P: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 P;switch(E.type){case"text":case"error-text":P=E.value;break;case"execution-denied":P=(c=E.reason)!=null?c:"Tool call execution denied.";break;case"content":case"json":case"error-json":P=JSON.stringify(E.value);break}d.push({role:"tool",tool_call_id:g.toolCallId,content:A==null?P:[{type:"text",text:P,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 Eg=Ue(()=>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()}))),Ig=Ue(()=>Le(it([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]))),Sg=Ue(()=>Le(N({logitBias:_t(qh(),j()).optional(),logprobs:it([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:_t(w().max(64),w().max(512)).optional(),prediction:_t(w(),gr()).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 Tg({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 Ng=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:P}){var T,S,D,M,ee;const $=[],F=(T=await En({provider:"openai",providerOptions:P,schema:Sg}))!=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}=Ag({prompt:t,systemMessageMode:(D=F.systemMessageMode)!=null?D: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:pe}=Tg({tools:E,toolChoice:A});return{args:{...z,tools:we,tool_choice:G},warnings:[...$,...pe]}}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:P}=await Zn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:An(this.config.headers(),t.headers),body:v,failedResponseHandler:In,successfulResponseHandler:pr(Eg),abortSignal:t.abortSignal,fetch:this.config.fetch}),T=A.choices[0],S=[],D=T.message.content;D!=null&&D.length>0&&S.push({type:"text",text:D});for(const $ of(r=T.message.tool_calls)!=null?r:[])S.push({type:"tool-call",toolCallId:(i=$.id)!=null?i:on(),toolName:$.function.name,input:$.function.arguments});for(const $ of(c=T.message.annotations)!=null?c:[])S.push({type:"source",sourceType:"url",id:on(),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:P},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:An(this.config.headers(),t.headers),body:c,failedResponseHandler:In,successfulResponseHandler:Ji(Ig),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:D=>"error"in D?D.error:void 0,isOutputChunk:Og,url:d,requestBodyValues:c,responseHeaders:f}),v=[];let g={unified:"other",raw:void 0},E,A=!1,P=!1;const T={openai:{}};return{stream:x.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:i})},transform(D,M){var ee,$,F,re,Z,B,L,W,z,we,G,pe,de;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:D.error});return}const te=D.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&&(P||(M.enqueue({type:"text-start",id:"0"}),P=!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 ze=v[Te];((W=ze.function)==null?void 0:W.name)!=null&&((z=ze.function)==null?void 0:z.arguments)!=null&&ze.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:ze.id,delta:ze.function.arguments});continue}const Je=v[Te];Je.hasFinished||(((we=le.function)==null?void 0:we.arguments)!=null&&(Je.function.arguments+=(pe=(G=le.function)==null?void 0:G.arguments)!=null?pe:""),M.enqueue({type:"tool-input-delta",id:Je.id,delta:(de=le.function.arguments)!=null?de:""}))}if(ke.annotations!=null)for(const le of ke.annotations)M.enqueue({type:"source",sourceType:"url",id:on(),url:le.url_citation.url,title:le.url_citation.title})},flush(D){var M;P&&D.enqueue({type:"text-end",id:"0"});for(const ee of v)ee.hasFinished||(D.enqueue({type:"tool-input-end",id:ee.id}),D.enqueue({type:"tool-call",toolCallId:(M=ee.id)!=null?M:on(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0);D.enqueue({type:"finish",finishReason:g,usage:Ra(E),...T!=null?{providerMetadata:T}:{}})}})),request:{body:c},response:{headers:f}}}};function Og(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 kg({prompt:t,user:r="user",assistant:i="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
|
|
46
46
|
|
|
47
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}:
|
|
48
48
|
${m}
|
|
@@ -52,22 +52,22 @@ ${m}
|
|
|
52
52
|
|
|
53
53
|
`;break}case"tool":throw new Mn({functionality:"tool messages"});default:{const m=d;throw new Error(`Unsupported role: ${m}`)}}return c+=`${i}:
|
|
54
54
|
`,{prompt:c,stopSequences:[`
|
|
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 Rg=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()}))),Mg=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()}))),Dg=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}=kg({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(Rg),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(Mg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:T=>"error"in T?T.error:void 0,isOutputChunk:Pg,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 Pg(t){return!("error"in t)&&t.choices.some(r=>r.text.length>0)}var Bg=Fe(()=>Le(N({dimensions:j().optional(),user:w().optional()}))),Lg=Fe(()=>Le(N({data:ue(N({embedding:ue(j())})),usage:N({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: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:Bg}))!=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(Lg),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()}))),Ug={"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},zg=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function Vg(t){return zg.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()}),Zg=Fe(()=>Le(vu.extend({style:Ae(["vivid","natural"]).optional(),moderation:Ae(["auto","low"]).optional()}))),$g=Fe(()=>Le(vu.extend({inputFidelity:Ae(["high","low"]).optional()}))),jg=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=Ug[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:$g}))!=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 Hg(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:Zg}))!=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,...Vg(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 Hg(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()}))),Wg=Dn({id:"openai.apply_patch",inputSchema:Cu,outputSchema:bu}),Gg=Wg,qg=Fe(()=>Le(N({code:w().nullish(),containerId:w()}))),Xg=Fe(()=>Le(N({outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullish()}))),Yg=Fe(()=>Le(N({container:st([w(),N({fileIds:ue(w()).optional()})]).optional()}))),Kg=Dn({id:"openai.code_interpreter",inputSchema:qg,outputSchema:Xg}),Jg=(t={})=>Kg(t),Qg=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()}))),e2=Fe(()=>Le(w())),t2=mg({id:"openai.custom",inputSchema:e2}),n2=t=>t2(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)]))}),r2=Fe(()=>Le(N({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:N({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:st([Au,Eu]).optional()}))),o2=Fe(()=>Le(N({queries:ue(w()),results:ue(N({attributes:wt(w(),Cn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),i2=Dn({id:"openai.file_search",inputSchema:N({}),outputSchema:o2}),s2=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())),a2=Fe(()=>Le(N({}))),l2=Fe(()=>Le(N({result:w()}))),c2=Dn({id:"openai.image_generation",inputSchema:a2,outputSchema:l2}),u2=(t={})=>c2(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()}))),d2=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()})])}))}))),f2=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(),h2=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:f2}),N({type:Y("containerReference"),containerId:w()}),N({type:Y("local").optional(),skills:ue(N({name:w(),description:w(),path:w()})).optional()})]).optional()}))),p2=Dn({id:"openai.shell",inputSchema:Tu,outputSchema:ki}),m2=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()))}))),g2=Dn({id:"openai.tool_search",inputSchema:Ri,outputSchema:Mi}),x2=(t={})=>g2(t),y2=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()}))),w2=Fe(()=>Le(N({}))),_2=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()}))),v2=Dn({id:"openai.web_search",inputSchema:w2,outputSchema:_2}),C2=(t={})=>v2(t),b2=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()}))),A2=Fe(()=>Le(N({}))),E2=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()}))),I2=Dn({id:"openai.web_search_preview",inputSchema:A2,outputSchema:E2}),Di=Wi(()=>st([w(),j(),Mt(),bc(),ue(Di),wt(w(),Di)])),S2=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."))),T2=Fe(()=>Le(N({}))),N2=Fe(()=>Le(N({type:Y("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:st([w(),Di]).optional()}))),O2=Dn({id:"openai.mcp",inputSchema:T2,outputSchema:N2}),k2=t=>O2(t),R2={applyPatch:Gg,customTool:n2,codeInterpreter:Jg,fileSearch:i2,imageGeneration:u2,localShell:d2,shell:p2,webSearchPreview:I2,webSearch:C2,mcp:k2,toolSearch:x2};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 M2(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 D2({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:M2(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:P2}),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 P2=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())])),B2=N({type:Y("error"),sequence_number:j(),error:N({type:w(),code:w(),message:w(),param:w().nullish()})}),L2=N({type:Y("error"),sequence_number:j(),code:w().nullish(),message:w(),param:w().nullish()}),F2=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()}),B2,L2,N({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),U2=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 z2({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=V2({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:r2});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:h2});g.push({type:"shell",...S.environment&&{environment:Z2(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:b2});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:y2});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:Yg});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:s2});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:S2}),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:Qg});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:m2});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 V2({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 Z2(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:$2(i.skills)}}return{type:"local",skills:t.skills}}function $2(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 j2=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 z2({tools:E,toolChoice:A,allowedTools:(S=G?.allowedTools)!=null?S:void 0,toolNameMapping:fe,customProviderToolNames:te}),{input:Te,warnings:Je}=await D2({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(U2),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(F2),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:sx,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=W2(fe.rawValue)?G2({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(X2(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(J2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(Q2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(rx(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(ox(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(ex(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(tx(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)})}else if(nx(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(K2(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(H2(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(Y2(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 ix(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 H2(t){return t.type==="response.output_text.delta"}function W2(t){const r=q2(t);return r!=null&&Array.isArray(r.choices)&&typeof r.type!="string"}function G2({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 q2(t){return typeof t=="object"&&t!=null?t:void 0}function X2(t){return t.type==="response.output_item.done"}function Y2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ja(t){return t.type==="response.failed"}function K2(t){return t.type==="response.created"}function J2(t){return t.type==="response.function_call_arguments.delta"}function Q2(t){return t.type==="response.custom_tool_call_input.delta"}function ex(t){return t.type==="response.image_generation_call.partial_image"}function tx(t){return t.type==="response.code_interpreter_call_code.delta"}function nx(t){return t.type==="response.code_interpreter_call_code.done"}function rx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function ox(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function ix(t){return t.type==="response.output_text.annotation.added"}function Wa(t){return t.type==="error"}function sx(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 ax=Fe(()=>Le(N({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),lx=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:ax}),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:yg(),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}}}},cx=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()}))),ux=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"},dx=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:ux}),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(cx),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}}}},fx="3.0.85";function Ou(t={}){var r,i;const c=(r=wg(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/${fx}`),m=P=>new Ng(P,{provider:`${d}.chat`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),x=P=>new Dg(P,{provider:`${d}.completion`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),v=P=>new Fg(P,{provider:`${d}.embedding`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),g=P=>new jg(P,{provider:`${d}.image`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),E=P=>new dx(P,{provider:`${d}.transcription`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),A=P=>new lx(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 j2(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=R2,S}Ou();const hx={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 px{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 mx(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 gx{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 Rg=Ue(()=>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(_t(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),Mg=Ue(()=>Le(it([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(_t(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Qi]))),La=Ue(()=>Le(N({echo:Mt().optional(),logitBias:_t(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:it([Mt(),j()]).optional()}))),Dg=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:P}){const T=[],S={...await En({provider:"openai",providerOptions:P,schema:La}),...await En({provider:this.providerOptionsName,providerOptions:P,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:D,stopSequences:M}=kg({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:D,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:An(this.config.headers(),t.headers),body:i,failedResponseHandler:In,successfulResponseHandler:pr(Rg),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:An(this.config.headers(),t.headers),body:c,failedResponseHandler:In,successfulResponseHandler:Ji(Mg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:T=>"error"in T?T.error:void 0,isOutputChunk:Pg,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 D=T.value;if("error"in D){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:D.error});return}A&&(A=!1,S.enqueue({type:"response-metadata",...Pa(D)}),S.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(E=D.usage);const M=D.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 Pg(t){return!("error"in t)&&t.choices.some(r=>r.text.length>0)}var Bg=Ue(()=>Le(N({dimensions:j().optional(),user:w().optional()}))),Lg=Ue(()=>Le(N({data:ue(N({embedding:ue(j())})),usage:N({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: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 En({provider:"openai",providerOptions:c,schema:Bg}))!=null?d:{},{responseHeaders:m,value:x,rawValue:v}=await Zn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:An(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:In,successfulResponseHandler:pr(Lg),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=Ue(()=>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()}))),Ug={"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},zg=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function Vg(t){return zg.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()}),Zg=Ue(()=>Le(vu.extend({style:Ae(["vivid","natural"]).optional(),moderation:Ae(["auto","low"]).optional()}))),$g=Ue(()=>Le(vu.extend({inputFidelity:Ae(["high","low"]).optional()}))),jg=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=Ug[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,P,T,S,D,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=(P=(A=(E=this.config._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E))!=null?P:new Date;if(r!=null){const we=(T=await En({provider:"openai",providerOptions:x,schema:$g}))!=null?T:{},{value:G,responseHeaders:pe}=await xu({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:An(this.config.headers(),v),formData:Jp({model:this.modelId,prompt:t,image:await Promise.all(r.map(de=>de.type==="file"?new Blob([de.data instanceof Uint8Array?new Blob([de.data],{type:de.mediaType}):new Blob([qi(de.data)],{type:de.mediaType})],{type:de.mediaType}):lu(de.url))),mask:i!=null?await Hg(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:In,successfulResponseHandler:pr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:G.data.map(de=>de.b64_json),warnings:Z,usage:G.usage!=null?{inputTokens:(S=G.usage.input_tokens)!=null?S:void 0,outputTokens:(D=G.usage.output_tokens)!=null?D:void 0,totalTokens:(M=G.usage.total_tokens)!=null?M:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:pe},providerMetadata:{openai:{images:G.data.map((de,te)=>{var q,ke,le,Te,Je,ze;return{...de.revised_prompt?{revisedPrompt:de.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((ze=G.usage)==null?void 0:ze.input_tokens_details,te,G.data.length)}})}}}}const L=(ee=await En({provider:"openai",providerOptions:x,schema:Zg}))!=null?ee:{},{value:W,responseHeaders:z}=await Zn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:An(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,...Vg(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:In,successfulResponseHandler:pr(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 pe,de,te,q,ke,le;return{...we.revised_prompt?{revisedPrompt:we.revised_prompt}:{},created:(pe=W.created)!=null?pe:void 0,size:(de=W.size)!=null?de: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 Hg(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=Ue(()=>Le(N({callId:w(),operation:gt("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=Ue(()=>Le(N({status:Ae(["completed","failed"]),output:w().optional()}))),Wg=Dn({id:"openai.apply_patch",inputSchema:Cu,outputSchema:bu}),Gg=Wg,qg=Ue(()=>Le(N({code:w().nullish(),containerId:w()}))),Xg=Ue(()=>Le(N({outputs:ue(gt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullish()}))),Yg=Ue(()=>Le(N({container:it([w(),N({fileIds:ue(w()).optional()})]).optional()}))),Kg=Dn({id:"openai.code_interpreter",inputSchema:qg,outputSchema:Xg}),Jg=(t={})=>Kg(t),Qg=Ue(()=>Le(N({name:w(),description:w().optional(),format:it([N({type:Y("grammar"),syntax:Ae(["regex","lark"]),definition:w()}),N({type:Y("text")})]).optional()}))),e2=Ue(()=>Le(w())),t2=mg({id:"openai.custom",inputSchema:e2}),n2=t=>t2(t),Au=N({key:w(),type:Ae(["eq","ne","gt","gte","lt","lte","in","nin"]),value:it([w(),j(),Mt(),ue(w())])}),Eu=N({type:Ae(["and","or"]),filters:ue(it([Au,Wi(()=>Eu)]))}),r2=Ue(()=>Le(N({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:N({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:it([Au,Eu]).optional()}))),o2=Ue(()=>Le(N({queries:ue(w()),results:ue(N({attributes:_t(w(),bn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),i2=Dn({id:"openai.file_search",inputSchema:N({}),outputSchema:o2}),s2=Ue(()=>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())),a2=Ue(()=>Le(N({}))),l2=Ue(()=>Le(N({result:w()}))),c2=Dn({id:"openai.image_generation",inputSchema:a2,outputSchema:l2}),u2=(t={})=>c2(t),Iu=Ue(()=>Le(N({action:N({type:Y("exec"),command:ue(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:_t(w(),w()).optional()})}))),Su=Ue(()=>Le(N({output:w()}))),d2=Dn({id:"openai.local_shell",inputSchema:Iu,outputSchema:Su}),Tu=Ue(()=>Le(N({action:N({commands:ue(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),ki=Ue(()=>Le(N({output:ue(N({stdout:w(),stderr:w(),outcome:gt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exitCode:j()})])}))}))),f2=ue(gt("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(),h2=Ue(()=>Le(N({environment:it([N({type:Y("containerAuto"),fileIds:ue(w()).optional(),memoryLimit:Ae(["1g","4g","16g","64g"]).optional(),networkPolicy:gt("type",[N({type:Y("disabled")}),N({type:Y("allowlist"),allowedDomains:ue(w()),domainSecrets:ue(N({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:f2}),N({type:Y("containerReference"),containerId:w()}),N({type:Y("local").optional(),skills:ue(N({name:w(),description:w(),path:w()})).optional()})]).optional()}))),p2=Dn({id:"openai.shell",inputSchema:Tu,outputSchema:ki}),m2=Ue(()=>Le(N({execution:Ae(["server","client"]).optional(),description:w().optional(),parameters:_t(w(),bn()).optional()}))),Ri=Ue(()=>Le(N({arguments:bn().optional(),call_id:w().nullish()}))),Mi=Ue(()=>Le(N({tools:ue(_t(w(),bn()))}))),g2=Dn({id:"openai.tool_search",inputSchema:Ri,outputSchema:Mi}),x2=(t={})=>g2(t),y2=Ue(()=>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()}))),w2=Ue(()=>Le(N({}))),_2=Ue(()=>Le(N({action:gt("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(gt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).optional()}))),v2=Dn({id:"openai.web_search",inputSchema:w2,outputSchema:_2}),C2=(t={})=>v2(t),b2=Ue(()=>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()}))),A2=Ue(()=>Le(N({}))),E2=Ue(()=>Le(N({action:gt("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()}))),I2=Dn({id:"openai.web_search_preview",inputSchema:A2,outputSchema:E2}),Di=Wi(()=>it([w(),j(),Mt(),bc(),ue(Di),_t(w(),Di)])),S2=Ue(()=>Le(N({serverLabel:w(),allowedTools:it([ue(w()),N({readOnly:Mt().optional(),toolNames:ue(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:_t(w(),w()).optional(),requireApproval:it([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."))),T2=Ue(()=>Le(N({}))),N2=Ue(()=>Le(N({type:Y("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:it([w(),Di]).optional()}))),O2=Dn({id:"openai.mcp",inputSchema:T2,outputSchema:N2}),k2=t=>O2(t),R2={applyPatch:Gg,customTool:n2,codeInterpreter:Jg,fileSearch:i2,imageGeneration:u2,localShell:d2,shell:p2,webSearchPreview:I2,webSearch:C2,mcp:k2,toolSearch:x2};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 M2(t){return JSON.stringify(t===void 0?{}:t)}function Tr(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 D2({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:P}){var T,S,D,M,ee,$,F,re,Z,B,L,W,z,we,G,pe,de,te,q,ke,le,Te,Je,ze,Xe,Ve;let _e=[];const We=[],Ze=new Set;for(const{role:ye,content:ct,providerOptions:tt}of t)switch(ye){case"system":{switch(i){case"system":{const Ee=Tr(tt,c);_e.push({role:"system",content:Ee==null?ct:[{type:"input_text",text:ct,prompt_cache_breakpoint:Ee}]});break}case"developer":{const Ee=Tr(tt,c);_e.push({role:"developer",content:Ee==null?ct:[{type:"input_text",text:ct,prompt_cache_breakpoint:Ee}]});break}case"remove":{We.push({type:"other",message:"system messages are removed for this model"});break}default:{const Ee=i;throw new Error(`Unsupported system message mode: ${Ee}`)}}break}case"user":{_e.push({role:"user",content:ct.map((Ee,ae)=>{var J,xe,ie;switch(Ee.type){case"text":{const ge=Tr(Ee.providerOptions,c);return{type:"input_text",text:Ee.text,...ge!=null&&{prompt_cache_breakpoint:ge}}}case"file":{const ge=Tr(Ee.providerOptions,c),Fe=Ee.mediaType==="image/*"?"image/jpeg":Ee.mediaType;if(Fe.startsWith("image/"))return{type:"input_image",...Ee.data instanceof URL?{image_url:Ee.data.toString()}:typeof Ee.data=="string"&&Va(Ee.data,d)?{file_id:Ee.data}:{image_url:`data:${Fe};base64,${Or(Ee.data)}`},detail:(xe=(J=Ee.providerOptions)==null?void 0:J[c])==null?void 0:xe.imageDetail,...ge!=null&&{prompt_cache_breakpoint:ge}};if(Ee.data instanceof URL)return{type:"input_file",file_url:Ee.data.toString(),...ge!=null&&{prompt_cache_breakpoint:ge}};if(Fe!=="application/pdf"&&!f)throw new Mn({functionality:`file part media type ${Fe}`});return{type:"input_file",...typeof Ee.data=="string"&&Va(Ee.data,d)?{file_id:Ee.data}:{filename:(ie=Ee.filename)!=null?ie:Fe==="application/pdf"?`part-${ae}.pdf`:`part-${ae}`,file_data:`data:${Fe};base64,${Or(Ee.data)}`},...ge!=null&&{prompt_cache_breakpoint:ge}}}}})});break}case"assistant":{const Ee={};for(const ae of ct)switch(ae.type){case"text":{const J=(T=ae.providerOptions)==null?void 0:T[c],xe=J?.itemId,ie=J?.phase;if(x&&xe!=null)break;if(m&&xe!=null){_e.push({type:"item_reference",id:xe});break}_e.push({role:"assistant",content:[{type:"output_text",text:ae.text}],id:xe,...ie!=null&&{phase:ie}});break}case"tool-call":{const J=($=(D=(S=ae.providerOptions)==null?void 0:S[c])==null?void 0:D.itemId)!=null?$:(ee=(M=ae.providerMetadata)==null?void 0:M[c])==null?void 0:ee.itemId,xe=(L=(re=(F=ae.providerOptions)==null?void 0:F[c])==null?void 0:re.namespace)!=null?L:(B=(Z=ae.providerMetadata)==null?void 0:Z[c])==null?void 0:B.namespace;if(x&&J!=null)break;const ie=r.toProviderToolName(ae.toolName);if(ie==="tool_search"){if(m&&J!=null){_e.push({type:"item_reference",id:J});break}const Fe=typeof ae.input=="string"?await mu({text:ae.input,schema:Ri}):await Dt({value:ae.input,schema:Ri}),Ft=Fe.call_id!=null?"client":"server";_e.push({type:"tool_search_call",id:J??ae.toolCallId,execution:Ft,call_id:(W=Fe.call_id)!=null?W:null,status:"completed",arguments:Fe.arguments});break}if(ae.providerExecuted){m&&J!=null&&_e.push({type:"item_reference",id:J});break}if(v&&m&&J!=null)break;const ge=g&&ie==="local_shell"||E&&ie==="shell"||A&&ie==="apply_patch"||((z=P?.has(ie))!=null?z:!1);if(m&&J!=null&&ge){_e.push({type:"item_reference",id:J});break}if(g&&ie==="local_shell"){const Fe=await Dt({value:ae.input,schema:Iu});_e.push({type:"local_shell_call",call_id:ae.toolCallId,id:J,action:{type:"exec",command:Fe.action.command,timeout_ms:Fe.action.timeoutMs,user:Fe.action.user,working_directory:Fe.action.workingDirectory,env:Fe.action.env}});break}if(E&&ie==="shell"){const Fe=await Dt({value:ae.input,schema:Tu});_e.push({type:"shell_call",call_id:ae.toolCallId,id:J,status:"completed",action:{commands:Fe.action.commands,timeout_ms:Fe.action.timeoutMs,max_output_length:Fe.action.maxOutputLength}});break}if(A&&ie==="apply_patch"){const Fe=await Dt({value:ae.input,schema:Cu});_e.push({type:"apply_patch_call",call_id:Fe.callId,id:J,status:"completed",operation:Fe.operation});break}if(P?.has(ie)){_e.push({type:"custom_tool_call",call_id:ae.toolCallId,name:ie,input:typeof ae.input=="string"?ae.input:JSON.stringify(ae.input),id:J});break}_e.push({type:"function_call",call_id:ae.toolCallId,name:ie,arguments:M2(ae.input),...xe!=null&&{namespace:xe}});break}case"tool-result":{if(ae.output.type==="execution-denied"||ae.output.type==="json"&&typeof ae.output.value=="object"&&ae.output.value!=null&&"type"in ae.output.value&&ae.output.value.type==="execution-denied"||x)break;const J=r.toProviderToolName(ae.toolName);if(J==="tool_search"){const xe=(q=(te=(G=(we=ae.providerOptions)==null?void 0:we[c])==null?void 0:G.itemId)!=null?te:(de=(pe=ae.providerMetadata)==null?void 0:pe[c])==null?void 0:de.itemId)!=null?q:ae.toolCallId;if(m)_e.push({type:"item_reference",id:xe});else if(ae.output.type==="json"){const ie=await Dt({value:ae.output.value,schema:Mi});_e.push({type:"tool_search_output",id:xe,execution:"server",call_id:null,status:"completed",tools:ie.tools})}break}if(E&&J==="shell"){if(ae.output.type==="json"){const xe=await Dt({value:ae.output.value,schema:ki});_e.push({type:"shell_call_output",call_id:ae.toolCallId,output:xe.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(m){const xe=(Te=(le=(ke=ae.providerOptions)==null?void 0:ke[c])==null?void 0:le.itemId)!=null?Te:ae.toolCallId;_e.push({type:"item_reference",id:xe})}else We.push({type:"other",message:`Results for OpenAI tool ${ae.toolName} are not sent to the API when store is false`});break}case"reasoning":{const J=await En({provider:c,providerOptions:ae.providerOptions,schema:P2}),xe=J?.itemId;if((x||v)&&xe!=null)break;if(xe!=null){const ie=Ee[xe];if(m)ie===void 0&&(_e.push({type:"item_reference",id:xe}),Ee[xe]={type:"reasoning",id:xe,summary:[]});else{const ge=[];ae.text.length>0?ge.push({type:"summary_text",text:ae.text}):ie!==void 0&&We.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(ae)}.`}),ie===void 0?(Ee[xe]={type:"reasoning",id:xe,encrypted_content:J?.reasoningEncryptedContent,summary:ge},_e.push(Ee[xe])):(ie.summary.push(...ge),J?.reasoningEncryptedContent!=null&&(ie.encrypted_content=J.reasoningEncryptedContent))}}else{const ie=J?.reasoningEncryptedContent;if(ie!=null){const ge=[];ae.text.length>0&&ge.push({type:"summary_text",text:ae.text}),_e.push({type:"reasoning",encrypted_content:ie,summary:ge})}else We.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(ae)}.`})}break}}break}case"tool":{for(const Ee of ct){if(Ee.type==="tool-approval-response"){const ie=Ee;if(Ze.has(ie.approvalId))continue;Ze.add(ie.approvalId),m&&_e.push({type:"item_reference",id:ie.approvalId}),_e.push({type:"mcp_approval_response",approval_request_id:ie.approvalId,approve:ie.approved});continue}const ae=Ee.output;if(ae.type==="execution-denied"&&((ze=(Je=ae.providerOptions)==null?void 0:Je.openai)==null?void 0:ze.approvalId))continue;const J=r.toProviderToolName(Ee.toolName);if(J==="tool_search"&&ae.type==="json"){const ie=await Dt({value:ae.value,schema:Mi});_e.push({type:"tool_search_output",execution:"client",call_id:Ee.toolCallId,status:"completed",tools:ie.tools});continue}if(g&&J==="local_shell"&&ae.type==="json"){const ie=await Dt({value:ae.value,schema:Su});_e.push({type:"local_shell_call_output",call_id:Ee.toolCallId,output:ie.output});continue}if(E&&J==="shell"&&ae.type==="json"){const ie=await Dt({value:ae.value,schema:ki});_e.push({type:"shell_call_output",call_id:Ee.toolCallId,output:ie.output.map(ge=>({stdout:ge.stdout,stderr:ge.stderr,outcome:ge.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ge.outcome.exitCode}}))});continue}if(A&&Ee.toolName==="apply_patch"&&ae.type==="json"){const ie=await Dt({value:ae.value,schema:bu});_e.push({type:"apply_patch_call_output",call_id:Ee.toolCallId,status:ie.status,output:ie.output});continue}if(P?.has(J)){let ie;switch(ae.type){case"text":case"error-text":ie=ae.value;break;case"execution-denied":ie=(Xe=ae.reason)!=null?Xe:"Tool call execution denied.";break;case"json":case"error-json":ie=JSON.stringify(ae.value);break;case"content":ie=ae.value.map(ge=>{var Fe,Ft,ut,qe,Me;const kt=Tr(ge.providerOptions,c);switch(ge.type){case"text":return{type:"input_text",text:ge.text,...kt!=null&&{prompt_cache_breakpoint:kt}};case"image-data":return{type:"input_image",image_url:`data:${ge.mediaType};base64,${ge.data}`,detail:(Ft=(Fe=ge.providerOptions)==null?void 0:Fe[c])==null?void 0:Ft.imageDetail,...kt!=null&&{prompt_cache_breakpoint:kt}};case"image-url":return{type:"input_image",image_url:ge.url,detail:(qe=(ut=ge.providerOptions)==null?void 0:ut[c])==null?void 0:qe.imageDetail,...kt!=null&&{prompt_cache_breakpoint:kt}};case"file-data":return{type:"input_file",filename:(Me=ge.filename)!=null?Me:"data",file_data:`data:${ge.mediaType};base64,${ge.data}`,...kt!=null&&{prompt_cache_breakpoint:kt}};case"file-url":return{type:"input_file",file_url:ge.url,...kt!=null&&{prompt_cache_breakpoint:kt}};default:We.push({type:"other",message:`unsupported custom tool content part type: ${ge.type}`});return}}).filter(Ia);break;default:ie=""}_e.push({type:"custom_tool_call_output",call_id:Ee.toolCallId,output:ie});continue}let xe;switch(ae.type){case"text":case"error-text":xe=ae.value;break;case"execution-denied":xe=(Ve=ae.reason)!=null?Ve:"Tool call execution denied.";break;case"json":case"error-json":xe=JSON.stringify(ae.value);break;case"content":xe=ae.value.map(ie=>{var ge,Fe,Ft,ut,qe;const Me=Tr(ie.providerOptions,c);switch(ie.type){case"text":return{type:"input_text",text:ie.text,...Me!=null&&{prompt_cache_breakpoint:Me}};case"image-data":return{type:"input_image",image_url:`data:${ie.mediaType};base64,${ie.data}`,detail:(Fe=(ge=ie.providerOptions)==null?void 0:ge[c])==null?void 0:Fe.imageDetail,...Me!=null&&{prompt_cache_breakpoint:Me}};case"image-url":return{type:"input_image",image_url:ie.url,detail:(ut=(Ft=ie.providerOptions)==null?void 0:Ft[c])==null?void 0:ut.imageDetail,...Me!=null&&{prompt_cache_breakpoint:Me}};case"file-data":return{type:"input_file",filename:(qe=ie.filename)!=null?qe:"data",file_data:`data:${ie.mediaType};base64,${ie.data}`,...Me!=null&&{prompt_cache_breakpoint:Me}};case"file-url":return{type:"input_file",file_url:ie.url,...Me!=null&&{prompt_cache_breakpoint:Me}};default:{We.push({type:"other",message:`unsupported tool content part type: ${ie.type}`});return}}}).filter(Ia);break}_e.push({type:"function_call_output",call_id:Ee.toolCallId,output:xe})}break}default:{const Ee=ye;throw new Error(`Unsupported role: ${Ee}`)}}return!m&&_e.some(ye=>"type"in ye&&ye.type==="reasoning"&&ye.encrypted_content==null)&&(We.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),_e=_e.filter(ye=>!("type"in ye)||ye.type!=="reasoning"||ye.encrypted_content!=null)),{input:_e,warnings:We}}var P2=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(()=>it([w(),j(),Mt(),bc(),ue(ro),_t(w(),ro.optional())])),B2=N({type:Y("error"),sequence_number:j(),error:N({type:w(),code:w(),message:w(),param:w().nullish()})}),L2=N({type:Y("error"),sequence_number:j(),code:w().nullish(),message:w(),param:w().nullish()}),F2=Ue(()=>Le(it([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:gt("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(gt("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:gt("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:gt("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:bn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(_t(w(),ro.optional()))})])}),N({type:Y("response.output_item.done"),output_index:j(),item:gt("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(gt("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:gt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(gt("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:_t(w(),it([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:_t(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:it([w(),N({type:w().optional(),code:it([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:gr(),annotations:_t(w(),bn()).optional()})),error:it([w(),N({type:w().optional(),code:it([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:gt("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:gt("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:bn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(_t(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:gt("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()}),B2,L2,N({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),U2=Ue(()=>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(gt("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(gt("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:gt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(gt("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:_t(w(),it([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(gt("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:_t(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:it([w(),N({type:w().optional(),code:it([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:gr(),annotations:_t(w(),bn()).optional()})),error:it([w(),N({type:w().optional(),code:it([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:gt("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:gt("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:bn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(_t(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=Ue(()=>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:it([Mt(),j().min(1).max(Nu)]).optional(),maxToolCalls:j().nullish(),metadata:gr().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 z2({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,D=V2({tool:T,options:S}),M=S?.namespace;if(M==null)g.push(D);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(D)}break}case"provider":{switch(T.id){case"openai.file_search":{const S=await Dt({value:T.args,schema:r2});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:h2});g.push({type:"shell",...S.environment&&{environment:Z2(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:b2});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:y2});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:Yg});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:s2});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:S2}),D=$=>({tool_names:$.toolNames}),M=S.requireApproval,ee=M==null?void 0:typeof M=="string"?M:M.never!=null?{never:D(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:Qg});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:m2});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 P=r.type;switch(P){case"auto":case"none":case"required":return{tools:g,toolChoice:P,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=P;throw new Mn({functionality:`tool choice type: ${T}`})}}}function V2({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 Z2(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:$2(i.skills)}}return{type:"local",skills:t.skills}}function $2(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 j2=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:P}){var T,S,D,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 En({provider:we,providerOptions:g,schema:Za});G==null&&we!=="openai"&&(G=await En({provider:"openai",providerOptions:g,schema:Za}));const pe=(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 de=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 z2({tools:E,toolChoice:A,allowedTools:(S=G?.allowedTools)!=null?S:void 0,toolNameMapping:de,customProviderToolNames:te}),{input:Te,warnings:Je}=await D2({prompt:v,toolNameMapping:de,systemMessageMode:(D=G?.systemMessageMode)!=null?D:pe?"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:_e("openai.local_shell"),hasShellTool:_e("openai.shell"),hasApplyPatchTool:_e("openai.apply_patch"),customProviderToolNames:te.size>0?te:void 0});W.push(...Je);const ze=($=G?.strictJsonSchema)!=null?$:!0;let Xe=G?.include;function Ve(ae){Xe==null?Xe=[ae]:Xe.includes(ae)||(Xe=[...Xe,ae])}function _e(ae){return E?.find(J=>J.type==="provider"&&J.id===ae)!=null}const We=typeof G?.logprobs=="number"?G?.logprobs:G?.logprobs===!0?Nu:void 0;We&&Ve("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&&Ve("web_search_call.action.sources"),_e("openai.code_interpreter")&&Ve("code_interpreter_call.outputs");const ye=G?.store;ye===!1&&pe&&Ve("reasoning.encrypted_content");const ct={model:this.modelId,input:Te,temperature:r,top_p:c,max_output_tokens:t,...(P?.type==="json"||G?.textVerbosity)&&{text:{...P?.type==="json"&&{format:P.schema!=null?{type:"json_schema",strict:ze,name:(re=P.name)!=null?re:"response",description:P.description,schema:P.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:ye,user:G?.user,instructions:G?.instructions,service_tier:G?.serviceTier,include:Xe,prompt_cache_key:G?.promptCacheKey,prompt_cache_options:G?.promptCacheOptions,prompt_cache_retention:G?.promptCacheRetention,safety_identifier:G?.safetyIdentifier,top_logprobs:We,truncation:G?.truncation,...pe&&(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}}}};pe?G?.reasoningEffort==="none"&&z.supportsNonReasoningParameters||(ct.temperature!=null&&(ct.temperature=void 0,W.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),ct.top_p!=null&&(ct.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 ct.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 ct.service_tier);const tt=(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,Ee=tt==="containerAuto"||tt==="containerReference";return{webSearchToolName:Ze,args:{...ct,tools:q,tool_choice:ke},warnings:[...W,...le],store:ye,toolNameMapping:de,providerOptionsName:we,isShellProviderExecuted:Ee}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,P,T,S,D,M,ee,$,F,re,Z,B,L,W,z,we,G,pe,de;const{args:te,warnings:q,webSearchToolName:ke,toolNameMapping:le,providerOptionsName:Te,isShellProviderExecuted:Je}=await this.getArgs(t),ze=this.config.url({path:"/responses",modelId:this.modelId}),Xe=$a(t.prompt),{responseHeaders:Ve,value:_e,rawValue:We}=await Zn({url:ze,headers:An(this.config.headers(),t.headers),body:te,failedResponseHandler:In,successfulResponseHandler:pr(U2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(_e.error)throw new Jt({message:_e.error.message,url:ze,requestBodyValues:te,statusCode:400,responseHeaders:Ve,responseBody:We,isRetryable:!1});const Ze=[],ye=[];let ct=!1;const tt=[];for(const J of _e.output)switch(J.type){case"reasoning":{J.summary.length===0&&J.summary.push({type:"summary_text",text:""});for(const xe of J.summary)Ze.push({type:"reasoning",text:xe.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 xe=(i=J.call_id)!=null?i:J.id,ie=J.execution==="server";ie&&tt.push(xe),Ze.push({type:"tool-call",toolCallId:xe,toolName:le.toCustomToolName("tool_search"),input:JSON.stringify({arguments:J.arguments,call_id:J.call_id}),...ie?{providerExecuted:!0}:{},providerMetadata:{[Te]:{itemId:J.id}}});break}case"tool_search_output":{const xe=(d=(c=J.call_id)!=null?c:tt.shift())!=null?d:J.id;Ze.push({type:"tool-result",toolCallId:xe,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(xe=>({stdout:xe.stdout,stderr:xe.stderr,outcome:xe.outcome.type==="exit"?{type:"exit",exitCode:xe.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const xe of J.content){(m=(f=t.providerOptions)==null?void 0:f[Te])!=null&&m.logprobs&&xe.logprobs&&ye.push(xe.logprobs);const ie={itemId:J.id,...J.phase!=null&&{phase:J.phase},...xe.annotations.length>0&&{annotations:xe.annotations}};Ze.push({type:"text",text:xe.text,providerMetadata:{[Te]:ie}});for(const ge of xe.annotations)ge.type==="url_citation"?Ze.push({type:"source",sourceType:"url",id:(g=(v=(x=this.config).generateId)==null?void 0:v.call(x))!=null?g:on(),url:ge.url,title:ge.title}):ge.type==="file_citation"?Ze.push({type:"source",sourceType:"document",id:(P=(A=(E=this.config).generateId)==null?void 0:A.call(E))!=null?P:on(),mediaType:"text/plain",title:ge.filename,filename:ge.filename,providerMetadata:{[Te]:{type:ge.type,fileId:ge.file_id,index:ge.index}}}):ge.type==="container_file_citation"?Ze.push({type:"source",sourceType:"document",id:(D=(S=(T=this.config).generateId)==null?void 0:S.call(T))!=null?D:on(),mediaType:"text/plain",title:ge.filename,filename:ge.filename,providerMetadata:{[Te]:{type:ge.type,fileId:ge.file_id,containerId:ge.container_id}}}):ge.type==="file_path"&&Ze.push({type:"source",sourceType:"document",id:($=(ee=(M=this.config).generateId)==null?void 0:ee.call(M))!=null?$:on(),mediaType:"application/octet-stream",title:ge.file_id,filename:ge.file_id,providerMetadata:{[Te]:{type:ge.type,fileId:ge.file_id,index:ge.index}}})}break}case"function_call":{ct=!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":{ct=!0;const xe=le.toCustomToolName(J.name);Ze.push({type:"tool-call",toolCallId:J.call_id,toolName:xe,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 xe=J.approval_request_id!=null&&(F=Xe[J.approval_request_id])!=null?F:J.id,ie=`mcp.${J.name}`;Ze.push({type:"tool-call",toolCallId:xe,toolName:ie,input:J.arguments,providerExecuted:!0,dynamic:!0}),Ze.push({type:"tool-result",toolCallId:xe,toolName:ie,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 xe=(re=J.approval_request_id)!=null?re:J.id,ie=(L=(B=(Z=this.config).generateId)==null?void 0:B.call(Z))!=null?L:on(),ge=`mcp.${J.name}`;Ze.push({type:"tool-call",toolCallId:ie,toolName:ge,input:J.arguments,providerExecuted:!0,dynamic:!0}),Ze.push({type:"tool-approval-request",approvalId:xe,toolCallId:ie});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(xe=>({attributes:xe.attributes,fileId:xe.file_id,filename:xe.filename,score:xe.score,text:xe.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 Ee={[Te]:{responseId:_e.id,...ye.length>0?{logprobs:ye}:{},...typeof _e.service_tier=="string"?{serviceTier:_e.service_tier}:{},...((we=_e.reasoning)==null?void 0:we.context)!=null?{reasoningContext:_e.reasoning.context}:{}}},ae=_e.usage;return{content:Ze,finishReason:{unified:gi({finishReason:(G=_e.incomplete_details)==null?void 0:G.reason,hasFunctionCall:ct}),raw:(de=(pe=_e.incomplete_details)==null?void 0:pe.reason)!=null?de:void 0},usage:za(ae),request:{body:te},response:{id:_e.id,timestamp:new Date(_e.created_at*1e3),modelId:_e.model,headers:Ve,body:We},providerMetadata:Ee,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:An(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:In,successfulResponseHandler:Ji(F2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=await es({stream:E,getError:de=>Wa(de)||ja(de)&&de.response.error!=null?de:void 0,isOutputChunk:sx,url:v,requestBodyValues:r,responseHeaders:g}),P=this,T=$a(t.prompt),S=new Map;let D={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(de){de.enqueue({type:"stream-start",warnings:i})},transform(de,te){var q,ke,le,Te,Je,ze,Xe,Ve,_e,We,Ze,ye,ct,tt,Ee,ae,J,xe,ie,ge,Fe,Ft,ut,qe,Me,kt,be,Bn,$n,Xt,jn,Ut,nr,an,At,rr,Ln,yr,xt,me;if(t.includeRawChunks&&te.enqueue({type:"raw",rawValue:de.rawValue}),!de.success){const ne=W2(de.rawValue)?G2({value:de.rawValue,cause:de.error,url:v,requestBodyValues:r,responseHeaders:g}):de.error;D={unified:"error",raw:void 0},te.enqueue({type:"error",error:ne});return}const O=de.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,De=d.toCustomToolName("tool_search"),Ie=O.item.execution==="server";F[O.output_index]={toolName:De,toolCallId:ne,toolSearchExecution:(q=O.item.execution)!=null?q:"server"},Ie&&te.enqueue({type:"tool-input-start",id:ne,toolName:De,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:De}=O.item;if(F[O.output_index]={toolName:d.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:De.type==="delete_file",endEmitted:De.type==="delete_file"}},te.enqueue({type:"tool-input-start",id:ne,toolName:d.toCustomToolName("apply_patch")}),De.type==="delete_file"){const Ie=JSON.stringify({callId:ne,operation:De});te.enqueue({type:"tool-input-delta",id:ne,delta:Ie}),te.enqueue({type:"tool-input-end",id:ne})}else te.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${dr(ne)}","operation":{"type":"${dr(De.type)}","path":"${dr(De.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(X2(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:(ze=(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?ze: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],De=O.item.execution==="server";if(ne!=null){const Ie=De?ne.toolCallId:(Xe=O.item.call_id)!=null?Xe:O.item.id;De?we.push(Ie):te.enqueue({type:"tool-input-start",id:Ie,toolName:ne.toolName}),te.enqueue({type:"tool-input-end",id:Ie}),te.enqueue({type:"tool-call",toolCallId:Ie,toolName:ne.toolName,input:JSON.stringify({arguments:O.item.arguments,call_id:De?null:Ie}),...De?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:O.item.id}}})}F[O.output_index]=void 0}else if(O.item.type==="tool_search_output"){const ne=(_e=(Ve=O.item.call_id)!=null?Ve:we.shift())!=null?_e: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=(We=O.item.approval_request_id)!=null?We:void 0,De=ne!=null&&(ye=(Ze=S.get(ne))!=null?Ze:T[ne])!=null?ye:O.item.id,Ie=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:De,toolName:Ie,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-result",toolCallId:De,toolName:Ie,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:dr(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=(Ee=(tt=(ct=P.config).generateId)==null?void 0:tt.call(ct))!=null?Ee:on(),De=(ae=O.item.approval_request_id)!=null?ae:O.item.id;S.set(De,ne);const Ie=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:ne,toolName:Ie,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-approval-request",approvalId:De,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],De=Object.entries(ne.summaryParts).filter(([Ie,Oe])=>Oe==="active"||Oe==="can-conclude").map(([Ie])=>Ie);for(const Ie of De)te.enqueue({type:"reasoning-end",id:`${O.item.id}:${Ie}`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(J=O.item.encrypted_content)!=null?J:null}}});delete L[O.item.id]}}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(Q2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(rx(O)){const ne=F[O.output_index];ne?.applyPatch&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:dr(O.delta)}),ne.applyPatch.hasDiff=!0)}else if(ox(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:dr(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(ex(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(tx(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:dr(O.delta)})}else if(nx(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(K2(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(H2(O))te.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),(ie=(xe=t.providerOptions)==null?void 0:xe[m])!=null&&ie.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 De of Object.keys(ne.summaryParts))ne.summaryParts[De]==="can-conclude"&&(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${De}`,providerMetadata:{[m]:{itemId:O.item_id}}}),ne.summaryParts[De]="concluded");te.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id,reasoningEncryptedContent:(Fe=(ge=L[O.item_id])==null?void 0:ge.encryptedContent)!=null?Fe: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(Y2(O))D={unified:gi({finishReason:(Ft=O.response.incomplete_details)==null?void 0:Ft.reason,hasFunctionCall:B}),raw:(qe=(ut=O.response.incomplete_details)==null?void 0:ut.reason)!=null?qe:void 0},M=O.response.usage,typeof O.response.service_tier=="string"&&(W=O.response.service_tier),((Me=O.response.reasoning)==null?void 0:Me.context)!=null&&(z=O.response.reasoning.context);else if(ja(O)){const ne=(kt=O.response.incomplete_details)==null?void 0:kt.reason;D={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 ix(O)?(re.push(O.annotation),O.annotation.type==="url_citation"?te.enqueue({type:"source",sourceType:"url",id:(jn=(Xt=($n=P.config).generateId)==null?void 0:Xt.call($n))!=null?jn:on(),url:O.annotation.url,title:O.annotation.title}):O.annotation.type==="file_citation"?te.enqueue({type:"source",sourceType:"document",id:(an=(nr=(Ut=P.config).generateId)==null?void 0:nr.call(Ut))!=null?an:on(),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=(rr=(At=P.config).generateId)==null?void 0:rr.call(At))!=null?Ln:on(),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:(me=(xt=(yr=P.config).generateId)==null?void 0:xt.call(yr))!=null?me:on(),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,D={unified:"error",raw:"error"},te.enqueue({type:"error",error:O}))},flush(de){const te={[m]:{responseId:$,...ee.length>0?{logprobs:ee}:{},...W!==void 0?{serviceTier:W}:{},...z!==void 0?{reasoningContext:z}:{}}};de.enqueue({type:"finish",finishReason:D,usage:za(M),providerMetadata:te})}})),request:{body:r},response:{headers:g}}}};function H2(t){return t.type==="response.output_text.delta"}function W2(t){const r=q2(t);return r!=null&&Array.isArray(r.choices)&&typeof r.type!="string"}function G2({value:t,cause:r,url:i,requestBodyValues:c,responseHeaders:d}){return new Jt({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 q2(t){return typeof t=="object"&&t!=null?t:void 0}function X2(t){return t.type==="response.output_item.done"}function Y2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ja(t){return t.type==="response.failed"}function K2(t){return t.type==="response.created"}function J2(t){return t.type==="response.function_call_arguments.delta"}function Q2(t){return t.type==="response.custom_tool_call_input.delta"}function ex(t){return t.type==="response.image_generation_call.partial_image"}function tx(t){return t.type==="response.code_interpreter_call_code.delta"}function nx(t){return t.type==="response.code_interpreter_call_code.done"}function rx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function ox(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function ix(t){return t.type==="response.output_text.annotation.added"}function Wa(t){return t.type==="error"}function sx(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 dr(t){return JSON.stringify(t).slice(1,-1)}var ax=Ue(()=>Le(N({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),lx=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 En({provider:"openai",providerOptions:m,schema:ax}),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 P=E[A];P!==void 0&&(g[A]=P)}}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:An(this.config.headers(),t.headers),body:f,failedResponseHandler:In,successfulResponseHandler:yg(),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}}}},cx=Ue(()=>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()}))),ux=Ue(()=>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"},dx=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 En({provider:"openai",providerOptions:i,schema:ux}),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:P,responseHeaders:T,rawValue:S}=await xu({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:An(this.config.headers(),t.headers),formData:E,failedResponseHandler:In,successfulResponseHandler:pr(cx),abortSignal:t.abortSignal,fetch:this.config.fetch}),D=P.language!=null&&P.language in qa?qa[P.language]:void 0;return{text:P.text,segments:(x=(m=(d=P.segments)==null?void 0:d.map(M=>({text:M.text,startSecond:M.start,endSecond:M.end})))!=null?m:(f=P.words)==null?void 0:f.map(M=>({text:M.word,startSecond:M.start,endSecond:M.end})))!=null?x:[],language:D,durationInSeconds:(v=P.duration)!=null?v:void 0,warnings:A,response:{timestamp:g,modelId:this.modelId,headers:T,body:S}}}},fx="3.0.87";function Ou(t={}){var r,i;const c=(r=wg(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/${fx}`),m=D=>new Ng(D,{provider:`${d}.chat`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),x=D=>new Dg(D,{provider:`${d}.completion`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),v=D=>new Fg(D,{provider:`${d}.embedding`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),g=D=>new jg(D,{provider:`${d}.image`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),E=D=>new dx(D,{provider:`${d}.transcription`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),A=D=>new lx(D,{provider:`${d}.speech`,url:({path:M})=>`${c}${M}`,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 T(D)},T=D=>new j2(D,{provider:`${d}.responses`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),S=function(D){return P(D)};return S.specificationVersion="v3",S.languageModel=P,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=R2,S}Ou();const hx={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 px{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 mx(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 gx{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
|
|
56
56
|
当前时间:${new Date().toLocaleDateString()}。
|
|
57
57
|
${this.staticPrompt}
|
|
58
58
|
${this.skillMetaPrompt}
|
|
59
59
|
${this.tempPrompt}
|
|
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 xx(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 yx 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 gx,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:xx(this.llmConfig.providerOptions,hx),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 px({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 mx(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 wx=({systemPrompt:t,llmConfig:r,emit:i})=>{const c=new yx({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 _x(){}const Pn=Object.assign,ts=typeof window<"u",Zo=t=>t!==null&&typeof t=="object",tr=t=>t!=null,Pi=t=>typeof t=="function",vx=t=>Zo(t)&&Pi(t.then)&&Pi(t.catch),ku=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),Cx=()=>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 bx(t,r,i){return r.reduce((c,d)=>(c[d]=t[d],c),{})}const Po=null,un=[Number,String],pr={type:Boolean,default:!0},Ax=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 Ex(){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 Ix=/scroll|auto|overlay/i,Sx=ns?window:void 0;function Tx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Ka(t,r=Sx){let i=t;for(;i&&i!==r&&Tx(i);){const{overflowY:c}=window.getComputedStyle(i);if(Ix.test(c))return i;i=i.parentNode}return r}Cx();const Nx=t=>t.stopPropagation();function Du(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Nx(t)}Ex();function vn(t){if(tr(t))return ku(t)?`${t}px`:String(t)}function Ox(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 kx(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const Rx=/-(\w)/g,Pu=t=>t.replace(Rx,(r,i)=>i.toUpperCase()),Mx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Dx}=Object.prototype;function Px(t,r,i){const c=r[i];tr(c)&&(!Dx.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=>{Px(t,r,i)}),t}var Bx={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":Bx}),Lx={messages(){return Qa[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Bu(Qa,t)}};var Fx=Lx;function Ux(t){const r=Pu(t)+".";return(i,...c)=>{const d=Fx.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 zx(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,zx(r),Ux(r)]}const Vx="van-haptics-feedback",el=5;function Zx(t,{args:r=[],done:i,canceled:c,error:d}){if(t){const f=t.apply(null,r);vx(f)?f.then(m=>{m?i():c&&c()}).catch(d||_x):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 $x=Symbol();function Lu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[jx,tl]=yr("badge"),Hx={dot:Boolean,max:un,tag:dn("div"),color:String,offset:Array,content:un,showZero:pr,position:dn("top-right")};var Wx=_.defineComponent({name:jx,props:Hx,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 Gx=lo(Wx);let Fu=2e3;const qx=()=>++Fu,Xx=t=>{Fu=t},[Uu,Yx]=yr("config-provider"),zu=Symbol(Uu),Kx={tag:dn("div"),theme:dn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:dn("local"),iconPrefix:String};function Jx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function Qx(t){const r={};return Object.keys(t).forEach(i=>{const c=Jx(Mx(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:Kx,setup(t,{slots:r}){const i=_.computed(()=>Qx(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&&Xx(t.zIndex)}),()=>_.createVNode(t.tag,{class:Yx(),style:t.themeVarsScope==="local"?i.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[ey,nl]=yr("icon"),ty=t=>t?.includes("/"),ny={dot:Boolean,tag:dn("i"),name:String,size:un,badge:un,color:String,badgeProps:Object,classPrefix:String};var ry=_.defineComponent({name:ey,props:ny,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=ty(m);return _.createVNode(Gx,_.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(ry),[oy,Kr]=yr("loading"),iy=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Kr("line",String(r+1))},null)),sy=_.createVNode("svg",{class:Kr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),ay={size:un,type:dn("circular"),color:String,vertical:Boolean,textSize:un,textColor:String};var ly=_.defineComponent({name:oy,props:ay,setup(t,{slots:r}){const i=_.computed(()=>Pn({color:t.color},Ox(t.size))),c=()=>{const f=t.type==="spinner"?iy:sy;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 cy=lo(ly),uy={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 dy(t,r){return t>r?"horizontal":r>t?"vertical":""}function fy(){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=dy(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 hy(t,r){const i=fy(),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},[py,my]=yr("overlay"),gy={show:Boolean,zIndex:un,duration:un,className:Po,lockScroll:pr,lazyRender:pr,customStyle:Object,teleport:[String,Object]};var xy=_.defineComponent({name:py,inheritAttrs:!1,props:gy,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(kx(t.zIndex),t.customStyle);return tr(t.duration)&&(v.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:v,class:[my(),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 yy=lo(xy),wy=Pn({},uy,{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}),[_y,il]=yr("popup");var vy=_.defineComponent({name:_y,inheritAttrs:!1,props:wy,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:qx(),r("open"))},A=()=>{d&&Zx(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(yy,_.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),Vx],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}),hy(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($x,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[T(),Z()]}):_.createVNode(_.Fragment,null,[T(),Z()])}});const Cy=lo(vy);let Wr=0;function by(t){t?(Wr||document.body.classList.add("van-toast--unclickable"),Wr++):Wr&&(Wr--,Wr||document.body.classList.remove("van-toast--unclickable"))}const[Ay,Or]=yr("toast"),Ey=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Iy={icon:String,show:Boolean,type:dn("text"),overlay:Boolean,message:un,iconSize:un,duration:Ax(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 Sy=_.defineComponent({name:Ay,props:Iy,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,by(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(cy,{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(Cy,_.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},bx(t,Ey)),{default:()=>[g(),E()]})}});function Ty(){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 Ny(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 Oy={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=[],ky=!1,sl=Pn({},Oy);const Ry=new Map;function Zu(t){return Zo(t)?t:{message:t}}function My(){const{instance:t}=Ny({setup(){const r=_.ref(""),{open:i,state:c,close:d,toggle:f}=Ty(),m=()=>{},x=()=>{const v={onClosed:m,"onUpdate:show":f};return _.createVNode(Sy,_.mergeProps(c,v),null)};return _.watch(r,v=>{c.message=v}),_.getCurrentInstance().render=x,{open:i,close:d,message:r}}});return t}function Dy(){if(!So.length||ky){const t=My();So.push(t)}return So[So.length-1]}function it(t={}){if(!ts)return{};const r=Dy(),i=Zu(t);return r.open(Pn({},sl,Ry.get(i.type||sl.type),i)),r}const Py=t=>r=>it(Pn({type:t},Zu(r))),$u=Py("loading"),By=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=Ly(d);f&&i.push({name:c,config:f})}return i}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},Ly=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}},Fy=(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 $=By(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 Uy(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 zy(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 Vy(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 Zy=["title"],$y=_.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
|
|
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(jy,{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 qy(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 Xy(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 Yy(t){return new Promise((r,i)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=i,c.readAsDataURL(t)})}function Ky(t){return t.type.startsWith("image/")}function Jy(t,r){const i=r*1024*1024;return t.size<=i}async function Qy(t){if(t.length===0)return[];const r=[];for(const i of t)if(i.rawFile)try{const c=await Yy(i.rawFile);Ky(i.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),it({type:"fail",message:"文件处理失败"})}return r}function ew(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(!Jy(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 tw(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}=ew({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 Qy(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 nw(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 rw=(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 ow=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Li.UNKWOWN_ERROR}},t})(),iw=(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 sw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qr={exports:{}},aw=qr.exports,ul;function lw(){return ul||(ul=1,(function(t,r){(function(i,c){c(r)})(aw,(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){
|
|
64
|
-
`){return this.buildToString(e,n,o)}buildToString(e,n,o){let s=new
|
|
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"],
|
|
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
|
|
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 xx(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 yx 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 Xr.AgentModelProvider(x),this.promptManager=new gx,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:xx(this.llmConfig.providerOptions,hx),prepareStep:({messages:T})=>{this.cleanGetSkillContentToolResult(T);const S=this.cleanupOldSnapshotsInMessages(T),D=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(ee=>{D.push(...Object.keys(ee||{}))});const M=Array.from(new Set(D)).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 D=S.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},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 px({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{g.resolve(),i.onDone()})}}).traverse(v),P={role:"assistant",content:"",uiContent:[]};return _.watch(A,T=>{if(!T)i.onData(P);else{const D=T.steps.map(M=>M.contents).flat().map(M=>{if(M.type==="text")return mx(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||"未知错误"}`};D.push(M)}(T.steps.length>=1||T?.error)&&i.onData({...P,uiContent:D.flat(),usage:T.totalUsage||null})}},{deep:!0}),g.promise}chat(r){throw new Error("Method not implemented.")}}const wx=({systemPrompt:t,llmConfig:r,emit:i})=>{const c=new yx({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:P,inputMessage:T,sendMessage:S,abortRequest:D,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 pe of B)pe.type==="image"&&pe.image&&we.push({type:"image",content:pe.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:P,inputMessage:T,sendMessage:S,abortRequest:D,senderRef:F,handleSendMessage:re,createConversation:m,switchConversation:v,deleteConversation:g,getCurrentConversation:x}};function _x(){}const Pn=Object.assign,ts=typeof window<"u",Zo=t=>t!==null&&typeof t=="object",er=t=>t!=null,Pi=t=>typeof t=="function",vx=t=>Zo(t)&&Pi(t.then)&&Pi(t.catch),ku=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),Cx=()=>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 bx(t,r,i){return r.reduce((c,d)=>(c[d]=t[d],c),{})}const Po=null,dn=[Number,String],hr={type:Boolean,default:!0},Ax=t=>({type:Number,default:t}),fn=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 P=_.unref(A);P&&!x&&(P.addEventListener(t,r,{capture:f,passive:d}),x=!0)},g=A=>{if(m)return;const P=_.unref(A);P&&x&&(P.removeEventListener(t,r,f),x=!1)};_.onUnmounted(()=>g(c)),_.onDeactivated(()=>g(c)),Ru(()=>v(c));let E;return _.isRef(c)&&(E=_.watch(c,(A,P)=>{g(P),v(A)})),()=>{E?.(),g(c),m=!0}}var Eo,yi;function Ex(){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 Ix=/scroll|auto|overlay/i,Sx=ns?window:void 0;function Tx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Ka(t,r=Sx){let i=t;for(;i&&i!==r&&Tx(i);){const{overflowY:c}=window.getComputedStyle(i);if(Ix.test(c))return i;i=i.parentNode}return r}Cx();const Nx=t=>t.stopPropagation();function Du(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Nx(t)}Ex();function Cn(t){if(er(t))return ku(t)?`${t}px`:String(t)}function Ox(t){if(er(t)){if(Array.isArray(t))return{width:Cn(t[0]),height:Cn(t[1])};const r=Cn(t);return{width:r,height:r}}}function kx(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const Rx=/-(\w)/g,Pu=t=>t.replace(Rx,(r,i)=>i.toUpperCase()),Mx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Dx}=Object.prototype;function Px(t,r,i){const c=r[i];er(c)&&(!Dx.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=>{Px(t,r,i)}),t}var Bx={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":Bx}),Lx={messages(){return Qa[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Bu(Qa,t)}};var Fx=Lx;function Ux(t){const r=Pu(t)+".";return(i,...c)=>{const d=Fx.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 zx(t){return(r,i)=>(r&&typeof r!="string"&&(i=r,r=""),r=r?`${t}__${r}`:t,`${r}${Bi(r,i)}`)}function xr(t){const r=`van-${t}`;return[r,zx(r),Ux(r)]}const Vx="van-haptics-feedback",el=5;function Zx(t,{args:r=[],done:i,canceled:c,error:d}){if(t){const f=t.apply(null,r);vx(f)?f.then(m=>{m?i():c&&c()}).catch(d||_x):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 $x=Symbol();function Lu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[jx,tl]=xr("badge"),Hx={dot:Boolean,max:dn,tag:fn("div"),color:String,offset:Array,content:dn,showZero:hr,position:fn("top-right")};var Wx=_.defineComponent({name:jx,props:Hx,setup(t,{slots:r}){const i=()=>{if(r.content)return!0;const{content:x,showZero:v}=t;return er(x)&&x!==""&&(v||x!==0&&x!=="0")},c=()=>{const{dot:x,max:v,content:g}=t;if(!x&&i())return r.content?r.content():er(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,P]=E.split("-");r.default?(typeof g=="number"?x[A]=Cn(A==="top"?g:-g):x[A]=A==="top"?Cn(g):d(g),typeof v=="number"?x[P]=Cn(P==="left"?v:-v):x[P]=P==="left"?Cn(v):d(v)):(x.marginTop=Cn(g),x.marginLeft=Cn(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 Gx=lo(Wx);let Fu=2e3;const qx=()=>++Fu,Xx=t=>{Fu=t},[Uu,Yx]=xr("config-provider"),zu=Symbol(Uu),Kx={tag:fn("div"),theme:fn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:fn("local"),iconPrefix:String};function Jx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function Qx(t){const r={};return Object.keys(t).forEach(i=>{const c=Jx(Mx(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:Kx,setup(t,{slots:r}){const i=_.computed(()=>Qx(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&&Xx(t.zIndex)}),()=>_.createVNode(t.tag,{class:Yx(),style:t.themeVarsScope==="local"?i.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[ey,nl]=xr("icon"),ty=t=>t?.includes("/"),ny={dot:Boolean,tag:fn("i"),name:String,size:dn,badge:dn,color:String,badgeProps:Object,classPrefix:String};var ry=_.defineComponent({name:ey,props:ny,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=ty(m);return _.createVNode(Gx,_.mergeProps({dot:f,tag:d,class:[c.value,E?"":`${c.value}-${m}`],style:{color:g,fontSize:Cn(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(ry),[oy,Kr]=xr("loading"),iy=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Kr("line",String(r+1))},null)),sy=_.createVNode("svg",{class:Kr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),ay={size:dn,type:fn("circular"),color:String,vertical:Boolean,textSize:dn,textColor:String};var ly=_.defineComponent({name:oy,props:ay,setup(t,{slots:r}){const i=_.computed(()=>Pn({color:t.color},Ox(t.size))),c=()=>{const f=t.type==="spinner"?iy:sy;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:Cn(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 cy=lo(ly),uy={show:Boolean,zIndex:dn,overlay:hr,duration:dn,teleport:[String,Object],lockScroll:hr,lazyRender:hr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Po,transitionAppear:Boolean,closeOnClickOverlay:hr};function dy(t,r){return t>r?"horizontal":r>t?"vertical":""}function fy(){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 D=10;(!m.value||d.value<D&&f.value<D)&&(m.value=dy(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 jr=0;const rl="van-overflow-hidden";function hy(t,r){const i=fy(),c="01",d="10",f=E=>{i.move(E);const A=i.deltaY.value>0?d:c;let P=Ka(E.target,t.value);for(;P.scrollHeight<=P.offsetHeight&&P!==t.value&&P.parentElement;)P=Ka(P.parentElement,t.value);const{scrollHeight:T,offsetHeight:S,scrollTop:D}=P;let M="11";D===0?M=S>=T?"00":"01":D+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}),jr||document.body.classList.add(rl),jr++},x=()=>{jr&&(document.removeEventListener("touchstart",i.start),document.removeEventListener("touchmove",f),jr--,jr||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},[py,my]=xr("overlay"),gy={show:Boolean,zIndex:dn,duration:dn,className:Po,lockScroll:hr,lazyRender:hr,customStyle:Object,teleport:[String,Object]};var xy=_.defineComponent({name:py,inheritAttrs:!1,props:gy,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(kx(t.zIndex),t.customStyle);return er(t.duration)&&(v.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:v,class:[my(),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 yy=lo(xy),wy=Pn({},uy,{round:Boolean,position:fn("center"),closeIcon:fn("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:fn("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[_y,il]=xr("popup");var vy=_.defineComponent({name:_y,inheritAttrs:!1,props:wy,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(er(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:qx(),r("open"))},A=()=>{d&&Zx(t.beforeClose,{done(){d=!1,r("close"),r("update:show",!1)}})},P=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(yy,_.mergeProps(B,ol(),{onClick:P}),{default:c["overlay-content"]})}},S=B=>{r("clickCloseIcon",B),A()},D=()=>{if(t.closeable)return _.createVNode(rs,{role:"button",tabindex:0,name:t.closeIcon,class:[il("close-icon",t.closeIconPosition),Vx],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:pe}=t;if(!(!pe&&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),D()]),[[_.vShow,pe]])}),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}),hy(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($x,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[T(),Z()]}):_.createVNode(_.Fragment,null,[T(),Z()])}});const Cy=lo(vy);let Hr=0;function by(t){t?(Hr||document.body.classList.add("van-toast--unclickable"),Hr++):Hr&&(Hr--,Hr||document.body.classList.remove("van-toast--unclickable"))}const[Ay,Nr]=xr("toast"),Ey=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Iy={icon:String,show:Boolean,type:fn("text"),overlay:Boolean,message:dn,iconSize:dn,duration:Ax(2e3),position:fn("middle"),teleport:[String,Object],wordBreak:String,className:Po,iconPrefix:String,transition:fn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Po,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:dn};var Sy=_.defineComponent({name:Ay,props:Iy,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,by(d))},m=A=>r("update:show",A),x=()=>{t.closeOnClick&&m(!1)},v=()=>clearTimeout(c),g=()=>{const{icon:A,type:P,iconSize:T,iconPrefix:S,loadingType:D}=t;if(A||P==="success"||P==="fail")return _.createVNode(rs,{name:A||P,size:T,class:Nr("icon"),classPrefix:S},null);if(P==="loading")return _.createVNode(cy,{class:Nr("loading"),size:T,type:D},null)},E=()=>{const{type:A,message:P}=t;if(i.message)return _.createVNode("div",{class:Nr("text")},[i.message()]);if(er(P)&&P!=="")return A==="html"?_.createVNode("div",{key:0,class:Nr("text"),innerHTML:String(P)},null):_.createVNode("div",{class:Nr("text")},[P])};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(Cy,_.mergeProps({class:[Nr([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:x,onClosed:v,"onUpdate:show":m},bx(t,Ey)),{default:()=>[g(),E()]})}});function Ty(){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 Ny(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 Oy={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=[],ky=!1,sl=Pn({},Oy);const Ry=new Map;function Zu(t){return Zo(t)?t:{message:t}}function My(){const{instance:t}=Ny({setup(){const r=_.ref(""),{open:i,state:c,close:d,toggle:f}=Ty(),m=()=>{},x=()=>{const v={onClosed:m,"onUpdate:show":f};return _.createVNode(Sy,_.mergeProps(c,v),null)};return _.watch(r,v=>{c.message=v}),_.getCurrentInstance().render=x,{open:i,close:d,message:r}}});return t}function Dy(){if(!So.length||ky){const t=My();So.push(t)}return So[So.length-1]}function ot(t={}){if(!ts)return{};const r=Dy(),i=Zu(t);return r.open(Pn({},sl,Ry.get(i.type||sl.type),i)),r}const Py=t=>r=>ot(Pn({type:t},Zu(r))),$u=Py("loading"),By=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=Ly(d);f&&i.push({name:c,config:f})}return i}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},Ly=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}},Fy=(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"){ot("添加工具失败:code 类型需要 JSON 字符串格式");return}const $=By(m);if($.length===0){ot("添加工具失败: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?ot(`成功添加 ${F} 个工具`):F>0?ot(`成功添加 ${F} 个工具,${re} 个失败`):ot("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){ot("添加工具失败:数据格式不正确");return}const{description:x,headers:v,name:g,thumbnail:E,type:A,url:P}=m;if(!g||!P||!A){ot("添加工具失败:缺少必要参数(名称、URL或类型)");return}const S=`mcp-server-${`custom-${g}-${Date.now()}`}`;let D;if(typeof v=="string"&&v.trim())try{D=JSON.parse(v)}catch($){console.warn("Failed to parse headers JSON:",$)}else typeof v=="object"&&(D=v);await c(S,{type:A,url:P,headers:D,useAISdkClient:!0},g,x,E)?(await t.closeAll(),ot("添加工具完成")):ot("重复添加工具或无法获取工具列表")}catch(x){console.error("handleCustomAdd error:",x),ot(`添加工具失败:${x instanceof Error?x.message:"未知错误"}`)}}}};function Uy(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))},P=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(pe=>pe.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 P({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:P,addPluginFromMarket:async Z=>{Z.addState="loading";const B={type:Z.type,url:Z.url,headers:Z.headers,useAISdkClient:!0},L=await P({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 P({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 zy(){if(typeof window>"u"||typeof document>"u")return null;const t=window!==window.top;try{return(t?window.parent.document:document).modelContext||null}catch{return null}}function Vy(t){const{onToolCatalogChanged:r}=t;let i=!1,c=!1,d=!1,f=null;const m=async()=>{if(!(!r||i)){if(c){d=!0;return}c=!0;try{do{d=!1;try{await r()}catch(A){console.warn("[useRouteBasedTools] refresh tool catalog failed:",A)}}while(d&&!i)}finally{c=!1}}},x=()=>{m()};let v=!1;const g=()=>{v||(i=!1,v=!0,f=zy(),f?.addEventListener?.("toolchange",x))},E=()=>{v&&(i=!0,d=!1,v=!1,f?.removeEventListener?.("toolchange",x),f=null)};_.onMounted(()=>{g()}),_.onUnmounted(()=>{E()})}function Zy(t){const{skillsRef:r,customAgentProvider:i}=t,c=_.shallowRef([]);_.watchEffect(async()=>{const x=r?.value;c.value=x?await Xr.getSkillOverviews(x):[]});const d=_.computed(()=>{const x=c.value;return x.length>0?Xr.formatSkillsForSystemPrompt(x):""}),f=_.computed(()=>{const x=r?.value;return x?Xr.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 $y=["title"],jy=_.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,$y))}}),tr=(t,r)=>{const i=t.__vccOpts||t;for(const[c,d]of r)i[c]=d;return i},Hy=tr(jy,[["__scopeId","data-v-000098b4"]]),Wy={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 Gy(t,r){return _.openBlock(),_.createElementBlock("svg",Wy,[...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:Gy};function qy(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 D=r.value[T].uiContent.map(M=>M.content).join(`
|
|
62
|
+
`);try{await navigator.clipboard.writeText(D),T!==void 0&&(m.value[T]=!0,setTimeout(()=>{m.value[T]=!1},3e3))}catch(M){console.error("复制失败:",M),ot("复制失败,请重试")}},A=async T=>{const S=r.value.findLastIndex((M,ee)=>M.role==="user"&&ee<=T);if(S===-1){console.warn("未找到可重新生成的用户消息"),ot("无法重新生成消息");return}const D=r.value[S];if(r.value=r.value.slice(0,S),Array.isArray(D.content)){const ee=D.content.find(F=>F.type==="text")?.text||"",$=D.content.filter(F=>F.type!=="text");c.value=ee,await d(ee,$.length>0?$:void 0)}else c.value=D.content,await d(D.content)},P={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(Zt.IconButton,{icon:Rr.IconRefresh,size:24,onClick:()=>A(T)}),_.h(Id,{effect:"light",content:g(T),placement:"right",visibleArrow:!1},()=>_.h(Zt.IconButton,{icon:Rr.IconCopy,size:24,onClick:()=>E(T)})),r.value[T].usage?_.h(Hy,{usage:r.value[T].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:P,copyingStates:m,isProcessing:x,latestAssistantMessageIndex:v,copyTooltipContent:g,copyMessageToClipboard:E,regenerateMessage:A}}function Xy(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 D=d();D.aiSdkMessages=S},handleHistorySelect:S=>{f(),i(S.id);const D=d();x.agent.responseMessages=D.aiSdkMessages,v.value=!1,g()},handleHistoryUpdateTitle:(S,D)=>{D.title=S},handleHistoryDelete:(S,D)=>{if(S.id==="delete"){if(m.currentId===D.id){ot("不允许删除当前会话");return}c(D.id)}},scrollToBottom:g}}function Yy(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,P=!1;const T=async $=>{if($u("添加工具中..."),$){const F=await g($,i.value);ot(F?"添加工具完成":"重复添加工具或添加失败")}else ot("添加工具失败")},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):ot("添加工具失败,请检查识别码是否正确"),E.value=""}catch(F){console.error("识别码处理失败:",F),ot("添加工具失败,请检查识别码是否正确"),E.value=""}return!0}return!1},D=()=>{const $=F=>{A&&(A.destroy(),A=null),A=Xr.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?!P&&re&&($(F),P=!0):($(F),P=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"&&D(),M()},initializeRemoter:D,watchSessionIdChanges:M}}function Ky(t){return new Promise((r,i)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=i,c.readAsDataURL(t)})}function Jy(t){return t.type.startsWith("image/")}function Qy(t,r){const i=r*1024*1024;return t.size<=i}async function ew(t){if(t.length===0)return[];const r=[];for(const i of t)if(i.rawFile)try{const c=await Ky(i.rawFile);Jy(i.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),ot({type:"fail",message:"文件处理失败"})}return r}function tw(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))){ot({type:"fail",message:`不支持的文件类型: ${x.type}`});continue}if(!Qy(x,f)){ot({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 nw(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}=tw({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(),ot("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:T=>{x(T)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(ot("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await ew(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 rw(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 ow=(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 iw=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Li.UNKWOWN_ERROR}},t})(),sw=(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 kr=(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 aw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Gr={exports:{}},lw=Gr.exports,ul;function cw(){return ul||(ul=1,(function(t,r){(function(i,c){c(r)})(lw,(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 P{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 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 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 D{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 D.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);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 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 pe{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 fe=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let he=0;he<o&&(s||a||l);he++){const ce=e[he]&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&&(fe||h+p+y>0)?pe.UTF8:a&&(pe.ASSUME_SHIFT_JIS||V>=3||H>=3)?pe.SHIFT_JIS:s&&a?V===2&&I===2||Q*10>=o?pe.SHIFT_JIS:pe.ISO88591:s?pe.ISO88591:a?pe.SHIFT_JIS:l?pe.UTF8:pe.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)}}pe.SHIFT_JIS=z.SJIS.getName(),pe.GB2312="GB2312",pe.ISO88591=z.ISO8859_1.getName(),pe.EUC_JP="EUC_JP",pe.UTF8=z.UTF8.getName(),pe.PLATFORM_DEFAULT_ENCODING=pe.UTF8,pe.ASSUME_SHIFT_JIS=!1;class de{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+=pe.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){D.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 de;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 fe=-2;fe<=2;fe++){const he=l[I+fe];H+=he[V-2]+he[V-1]+he[V]+he[V+1]+he[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,fe=y*s+I;Q<le.BLOCK_SIZE;Q++,fe+=s){for(let he=0;he<le.BLOCK_SIZE;he++){const ce=e[fe+he]&255;R+=ce,ce<U&&(U=ce),ce>V&&(V=ce)}if(V-U>le.MIN_DYNAMIC_RANGE)for(Q++,fe+=s;Q<le.BLOCK_SIZE;Q++,fe+=s)for(let he=0;he<le.BLOCK_SIZE;he++)R+=e[fe+he]&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 de;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 ze extends Te{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=ze.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return ze.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*ze.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=ze.makeBufferFromCanvasImageData(n),this}invert(){return new Je(this)}}ze.DEGREE_TO_RADIANS=Math.PI/180;class Xe{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 Ve=(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 _e{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 Ve(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 Ve(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new Xe(n.deviceId,n.label))})}findDeviceById(e){return Ve(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(o=>o.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return Ve(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return Ve(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 Ve(this,void 0,void 0,function*(){const o=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(o,n)})}decodeOnceFromStream(e,n){return Ve(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 Ve(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,o)})}decodeFromVideoDevice(e,n,o){return Ve(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 Ve(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 Ve(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 Ve(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 Ve(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 Ve(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return Ve(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 ze(n),s=new le(o);return new P(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 We{constructor(e,n,o=n==null?0:8*n.length,s,a,l=D.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=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 o=new Array(n.length+e.length);D.arraycopy(n,0,o,0,n.length),D.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 ye=Ze,ct;(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"})(ct||(ct={}));var tt=ct;class Ee{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),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 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;D.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 xe extends g{}xe.kind="ArithmeticException";class ie 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 xe;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}}ie.AZTEC_DATA_12=new ie(4201,4096,1),ie.AZTEC_DATA_10=new ie(1033,1024,1),ie.AZTEC_DATA_6=new ie(67,64,1),ie.AZTEC_PARAM=new ie(19,16,1),ie.QR_CODE_FIELD_256=new ie(285,256,0),ie.DATA_MATRIX_FIELD_256=new ie(301,256,1),ie.AZTEC_DATA_8=ie.DATA_MATRIX_FIELD_256,ie.MAXICODE_FIELD_64=ie.AZTEC_DATA_6;class ge extends g{}ge.kind="ReedSolomonException";class Fe extends g{}Fe.kind="IllegalStateException";class Ft{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 ge("Bad error location");e[U]=ie.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 ge("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 fe=l.getDegree()-a.getDegree(),he=s.multiply(l.getCoefficient(l.getDegree()),Q);V=V.addOrSubtract(s.buildMonomial(fe,he)),l=l.addOrSubtract(a.multiplyByMonomial(fe,he))}if(h=V.multiply(u).addOrSubtract(U),l.getDegree()>=a.getDegree())throw new Fe("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new ge("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 ge("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 ut;(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"})(ut||(ut={}));class qe{decode(e){this.ddata=e;let n=e.getBits(),o=this.extractBits(n),s=this.correctBits(o),a=qe.convertBoolArrayToByteArray(s),l=qe.getEncodedData(s),u=new Ee(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=ut.UPPER,s=ut.UPPER,a="",l=0;for(;l<n;)if(s===ut.BINARY){if(n-l<5)break;let u=qe.readCode(e,l,5);if(l+=5,u===0){if(n-l<11)break;u=qe.readCode(e,l,11)+31,l+=11}for(let h=0;h<u;h++){if(n-l<8){l=n;break}const p=qe.readCode(e,l,8);a+=pe.castAsNonUtf8Char(p),l+=8}s=o}else{let u=s===ut.DIGIT?4:5;if(n-l<u)break;let h=qe.readCode(e,l,u);l+=u;let p=qe.getCharacter(s,h);p.startsWith("CTRL_")?(o=s,s=qe.getTable(p.charAt(5)),p.charAt(6)==="L"&&(o=s)):(a+=p,s=o)}return a}static getTable(e){switch(e){case"L":return ut.LOWER;case"P":return ut.PUNCT;case"M":return ut.MIXED;case"D":return ut.DIGIT;case"B":return ut.BINARY;case"U":default:return ut.UPPER}}static getCharacter(e,n){switch(e){case ut.UPPER:return qe.UPPER_TABLE[n];case ut.LOWER:return qe.LOWER_TABLE[n];case ut.MIXED:return qe.MIXED_TABLE[n];case ut.PUNCT:return qe.PUNCT_TABLE[n];case ut.DIGIT:return qe.DIGIT_TABLE[n];default:throw new Fe("Bad table")}}correctBits(e){let n,o;this.ddata.getNbLayers()<=2?(o=6,n=ie.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(o=8,n=ie.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(o=10,n=ie.AZTEC_DATA_10):(o=12,n=ie.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]=qe.readCode(e,l,o);try{new Ft(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?qe.readCode(e,n,8):qe.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]=qe.readByte(e,8*o);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}qe.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"],qe.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"],qe.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"],qe.PUNCT_TABLE=["","\r",`\r
|
|
67
|
+
`,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],qe.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class Me{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 kt{static floatToIntBits(e){return e}}kt.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*kt.floatToIntBits(this.x)+kt.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 Me.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 Xt{constructor(e,n,o,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=Xt.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 he=1;V===null&&he<U;he++)V=this.getBlackPointOnSegment(e,s-he,e+he,s);if(V==null)throw new q;let H=null;for(let he=1;H===null&&he<U;he++)H=this.getBlackPointOnSegment(e,o+he,e+he,o);if(H==null)throw new q;let Q=null;for(let he=1;Q===null&&he<U;he++)Q=this.getBlackPointOnSegment(n,o+he,n-he,o);if(Q==null)throw new q;let fe=null;for(let he=1;fe===null&&he<U;he++)fe=this.getBlackPointOnSegment(n,s-he,n-he,s);if(fe==null)throw new q;return this.centerEdges(fe,V,Q,H)}else throw new q}getBlackPointOnSegment(e,n,o,s){const a=Me.round(Me.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=Me.round(e+p*l),b=Me.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=Xt.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}}Xt.INIT_SIZE=10,Xt.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 Ut{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=Ut.quadrilateralToSquare(e,n,o,s,a,l,u,h);return Ut.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 Ut(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 Ut(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 Ut.squareToQuadrilateral(e,n,o,s,a,l,u,h).buildAdjoint()}buildAdjoint(){return new Ut(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 Ut(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 nr extends jn{sampleGrid(e,n,o,s,a,l,u,h,p,y,b,I,R,U,V,H,Q,fe,he){const ce=Ut.quadrilateralToQuadrilateral(s,a,l,u,h,p,y,b,I,R,U,V,H,Q,fe,he);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 an{static setGridSampler(e){an.gridSampler=e}static getInstance(){return an.gridSampler}}an.gridSampler=new nr;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 rr{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 Ft(ie.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 Xt(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=Me.round((e.getX()+s.getX()+n.getX()+o.getX())/4),l=Me.round((e.getY()+s.getY()+n.getY()+o.getY())/4);try{let u=new Xt(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=Me.round((e.getX()+s.getX()+n.getX()+o.getX())/4),l=Me.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=an.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(Me.round(u+b*p),Me.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(Me.round(u),Me.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=Me.round(e.getX()),o=Me.round(e.getY());return this.isValid(n,o)}distancePoint(e,n){return Me.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return Me.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 rr(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new qe().decode(y)}catch(y){o=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new qe().decode(y)}catch(y){throw o??y}let u=new We(l.getText(),l.getRawBytes(),l.getNumBits(),a,ye.AZTEC,D.currentTimeMillis()),h=l.getByteSegments();h!=null&&u.putMetadata(tt.BYTE_SEGMENTS,h);let p=l.getECLevel();return p!=null&&u.putMetadata(tt.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 yr extends _e{constructor(e=500){super(new Ln,e)}}class xt{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(tt.ORIENTATION)===!0&&(h=h+u.get(tt.ORIENTATION)%360),l.putMetadata(tt.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(tt.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;xt.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 me extends xt{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=me.MAX_AVG_VARIANCE,b=-1;for(let I=me.CODE_START_A;I<=me.CODE_START_C;I++){const R=xt.patternMatchVariance(a,me.CODE_PATTERNS[I],me.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){xt.recordPattern(e,o,n);let s=me.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<me.CODE_PATTERNS.length;l++){const u=me.CODE_PATTERNS[l],h=this.patternMatchVariance(n,u,me.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=me.findStartPattern(n),l=a[2];let u=0;const h=new Uint8Array(20);h[u++]=l;let p;switch(l){case me.CODE_START_A:p=me.CODE_CODE_A;break;case me.CODE_START_B:p=me.CODE_CODE_B;break;case me.CODE_START_C:p=me.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,fe=l,he=0,ce=!0,Ke=!1,je=!1;for(;!y;){const Sr=b;switch(b=!1,H=Q,Q=me.decodeCode(n,V,U),h[u++]=Q,Q!==me.CODE_STOP&&(ce=!0),Q!==me.CODE_STOP&&(he++,fe+=he*Q),R=U,U+=V.reduce((bd,Ad)=>bd+Ad,0),Q){case me.CODE_START_A:case me.CODE_START_B:case me.CODE_START_C:throw new L}switch(p){case me.CODE_CODE_A:if(Q<64)je===Ke?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),je=!1;else if(Q<96)je===Ke?I+=String.fromCharCode(Q-64):I+=String.fromCharCode(Q+64),je=!1;else switch(Q!==me.CODE_STOP&&(ce=!1),Q){case me.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case me.CODE_FNC_2:case me.CODE_FNC_3:break;case me.CODE_FNC_4_A:!Ke&&je?(Ke=!0,je=!1):Ke&&je?(Ke=!1,je=!1):je=!0;break;case me.CODE_SHIFT:b=!0,p=me.CODE_CODE_B;break;case me.CODE_CODE_B:p=me.CODE_CODE_B;break;case me.CODE_CODE_C:p=me.CODE_CODE_C;break;case me.CODE_STOP:y=!0;break}break;case me.CODE_CODE_B:if(Q<96)je===Ke?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),je=!1;else switch(Q!==me.CODE_STOP&&(ce=!1),Q){case me.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case me.CODE_FNC_2:case me.CODE_FNC_3:break;case me.CODE_FNC_4_B:!Ke&&je?(Ke=!0,je=!1):Ke&&je?(Ke=!1,je=!1):je=!0;break;case me.CODE_SHIFT:b=!0,p=me.CODE_CODE_A;break;case me.CODE_CODE_A:p=me.CODE_CODE_A;break;case me.CODE_CODE_C:p=me.CODE_CODE_C;break;case me.CODE_STOP:y=!0;break}break;case me.CODE_CODE_C:if(Q<100)Q<10&&(I+="0"),I+=Q;else switch(Q!==me.CODE_STOP&&(ce=!1),Q){case me.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case me.CODE_CODE_A:p=me.CODE_CODE_A;break;case me.CODE_CODE_B:p=me.CODE_CODE_B;break;case me.CODE_STOP:y=!0;break}break}Sr&&(p=p===me.CODE_CODE_A?me.CODE_CODE_B:me.CODE_CODE_A)}const nn=U-R;if(U=n.getNextUnset(U),!n.isRange(U,Math.min(n.getSize(),U+(U-R)/2),!1))throw new q;if(fe-=he*H,fe%103!==H)throw new T;const wn=I.length;if(wn===0)throw new q;wn>0&&ce&&(p===me.CODE_CODE_C?I=I.substring(0,wn-2):I=I.substring(0,wn-1));const rn=(a[1]+a[0])/2,ht=R+nn/2,Wt=h.length,ln=new Uint8Array(Wt);for(let Sr=0;Sr<Wt;Sr++)ln[Sr]=h[Sr];const Ir=[new be(rn,e),new be(ht,e)];return new We(I,ln,0,Ir,ye.CODE_128,new Date().getTime())}}me.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])],me.MAX_AVG_VARIANCE=.25,me.MAX_INDIVIDUAL_VARIANCE=.7,me.CODE_SHIFT=98,me.CODE_CODE_C=99,me.CODE_CODE_B=100,me.CODE_CODE_A=101,me.CODE_FNC_1=102,me.CODE_FNC_2=97,me.CODE_FNC_3=96,me.CODE_FNC_4_A=101,me.CODE_FNC_4_B=100,me.CODE_START_A=103,me.CODE_START_B=104,me.CODE_START_C=105,me.CODE_STOP=106;class O extends xt{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 We(I,null,0,[new be(R,e),new be(U,e)],ye.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 xt{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,o){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new de;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 We(u,null,0,I,ye.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;){xt.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(xt.patternMatchVariance(a,o,ne.MAX_INDIVIDUAL_VARIANCE)<ne.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,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=xt.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 De extends xt{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=De.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 De.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let o=parseInt(e.charAt(n-1),10);return De.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 De.findGuardPattern(e,n,!1,De.START_END_PATTERN,new Int32Array(De.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(xt.patternMatchVariance(a,s,De.MAX_INDIVIDUAL_VARIANCE)<De.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=xt.patternMatchVariance(n,p,De.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new q}}De.MAX_AVG_VARIANCE=.48,De.MAX_INDIVIDUAL_VARIANCE=.7,De.START_END_PATTERN=Int32Array.from([1,1,1]),De.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),De.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),De.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 Ie{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=Ie.parseExtensionString(l),h=[new be((o[0]+o[1])/2,e),new be(a,e)],p=new We(l,null,0,h,ye.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=De.decodeDigit(e,s,l,De.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(Ie.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=Ie.parseExtension5String(e);return n==null?null:new Map([[tt.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 We(l,null,0,h,ye.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=De.decodeDigit(e,s,l,De.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([[tt.ISSUE_NUMBER,parseInt(e)]])}}class nt{static decodeRow(e,n,o){let s=De.findGuardPattern(n,o,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new Ie().decodeRow(e,n,s)}catch{return new Oe().decodeRow(e,n,s)}}}nt.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class Ye extends De{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 We(I,null,0,H,V,new Date().getTime()),fe=0;try{let ce=nt.decodeRow(e,n,p[1]);Q.putMetadata(tt.UPC_EAN_EXTENSION,ce.getText()),Q.putAllMetadata(ce.getResultMetadata()),Q.addResultPoints(ce.getResultPoints()),fe=ce.getText().length}catch{}let he=o==null?null:o.get(B.ALLOWED_EAN_EXTENSIONS);if(he!=null){let ce=!1;for(let Ke in he)if(fe.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 ye.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 ye.EAN_8}}class ls extends Ye{constructor(){super(...arguments),this.ean13Reader=new Fn}getBarcodeFormat(){return ye.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 We(n.substring(1),null,null,e.getResultPoints(),ye.UPC_A);return e.getResultMetadata()!=null&&o.putAllMetadata(e.getResultMetadata()),o}else throw new q}reset(){this.ean13Reader.reset()}}class yn 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=yn.decodeDigit(e,s,l,yn.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=yn.determineNumSysAndCheckDigit(o,u);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return yn.findGuardPatternWithoutCounters(e,n,!0,yn.MIDDLE_END_PATTERN)}checkChecksum(e){return Ye.checkChecksum(yn.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 ye.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),o=new de;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()}}yn.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),yn.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 xt{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 yn)):(n.indexOf(ye.EAN_13)>-1&&o.push(new Fn),n.indexOf(ye.UPC_A)>-1&&o.push(new ls),n.indexOf(ye.EAN_8)>-1&&o.push(new as),n.indexOf(ye.UPC_E)>-1&&o.push(new yn)),this.readers=o}decodeRow(e,n,o){for(let s of this.readers)try{const a=s.decodeRow(e,n,o),l=a.getBarcodeFormat()===ye.EAN_13&&a.getText().charAt(0)==="0",u=o==null?null:o.get(B.POSSIBLE_FORMATS),h=u==null||u.includes(ye.UPC_A);if(l&&h){const p=a.getRawBytes(),y=new We(a.getText().substring(1),p,p?p.length:null,a.getResultPoints(),ye.UPC_A);return y.putAllMetadata(a.getResultMetadata()),y}return a}catch{}throw new q}reset(){for(let e of this.readers)e.reset()}}class Gt extends xt{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(xt.patternMatchVariance(e,n[o],Gt.MAX_INDIVIDUAL_VARIANCE)<Gt.MAX_AVG_VARIANCE)return o;throw new q}static count(e){return Me.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>=Gt.MIN_FINDER_PATTERN_RATIO&&s<=Gt.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}}Gt.MAX_AVG_VARIANCE=.2,Gt.MAX_INDIVIDUAL_VARIANCE=.45,Gt.MIN_FINDER_PATTERN_RATIO=9.5/12,Gt.MAX_FINDER_PATTERN_RATIO=12.5/14;class wr{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 wr))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 or{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 Qt extends jo{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===Qt.FNC1}}Qt.FNC1="$";class ir 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 pn 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===pn.FNC1}isSecondDigitFNC1(){return this.secondDigit===pn.FNC1}isAnyFNC1(){return this.firstDigit===pn.FNC1||this.secondDigit===pn.FNC1}}pn.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 _r{constructor(e){this.buffer=new de,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 pn(this.information.getSize(),pn.FNC1,pn.FNC1):new pn(this.information.getSize(),a-1,pn.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),o=(n-8)/11,s=(n-8)%11;return new pn(e+7,o,s)}extractNumericValueFromBitArray(e,n){return _r.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 ir(this.current.getPosition(),this.buffer.toString(),o.getRemainingValue()):new ir(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 ir(this.current.getPosition(),this.buffer.toString()):n=new ir(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new or(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new ir(this.current.getPosition(),this.buffer.toString());return new or(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new or(!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 ir(this.current.getPosition(),this.buffer.toString());return new or(!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 or(!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 ir(this.current.getPosition(),this.buffer.toString());return new or(!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 or(!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 Qt(e+5,Qt.FNC1);if(n>=5&&n<15)return new Qt(e+5,"0"+(n-5));let o=this.extractNumericValueFromBitArray(e,7);if(o>=64&&o<90)return new Qt(e+7,""+(o+1));if(o>=90&&o<116)return new Qt(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 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 o=this.extractNumericValueFromBitArray(e,6);return o>=16&&o<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 o=this.extractNumericValueFromBitArray(e,6);if(o>=32&&o<58)return new Qt(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 Fe("Decoding invalid alphanumeric value: "+o)}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 Ho{constructor(e){this.information=e,this.generalDecoder=new _r(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class en 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)}en.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)}}en.GTIN_SIZE=40;class vr extends en{constructor(e){super(e)}parseInformation(){let e=new de;e.append("(01)");let n=e.length(),o=this.getGeneralDecoder().extractNumericValueFromBitArray(vr.HEADER_SIZE,4);return e.append(o),this.encodeCompressedGtinWithoutAI(e,vr.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,vr.HEADER_SIZE+44)}}vr.HEADER_SIZE=4;class uo extends Ho{constructor(e){super(e)}parseInformation(){let e=new de;return this.getGeneralDecoder().decodeAllCodes(e,uo.HEADER_SIZE)}}uo.HEADER_SIZE=5;class fo extends en{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 de;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 en{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Nn.HEADER_SIZE+en.GTIN_SIZE)throw new q;let e=new de;this.encodeCompressedGtin(e,Nn.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Nn.HEADER_SIZE+en.GTIN_SIZE,Nn.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let o=this.getGeneralDecoder().decodeGeneralPurposeField(Nn.HEADER_SIZE+en.GTIN_SIZE+Nn.LAST_DIGIT_SIZE,null);return e.append(o.getNewString()),e.toString()}}Nn.HEADER_SIZE=8,Nn.LAST_DIGIT_SIZE=2;class Yt extends en{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Yt.HEADER_SIZE+en.GTIN_SIZE)throw new q;let e=new de;this.encodeCompressedGtin(e,Yt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Yt.HEADER_SIZE+en.GTIN_SIZE,Yt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let o=this.getGeneralDecoder().extractNumericValueFromBitArray(Yt.HEADER_SIZE+en.GTIN_SIZE+Yt.LAST_DIGIT_SIZE,Yt.FIRST_THREE_DIGITS_SIZE);o/100==0&&e.append("0"),o/10==0&&e.append("0"),e.append(o);let s=this.getGeneralDecoder().decodeGeneralPurposeField(Yt.HEADER_SIZE+en.GTIN_SIZE+Yt.LAST_DIGIT_SIZE+Yt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}Yt.HEADER_SIZE=8,Yt.LAST_DIGIT_SIZE=2,Yt.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 de;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 vr(C);if(!C.get(2))return new uo(C);switch(_r.extractNumericValueFromBitArray(C,1,4)){case 4:return new Yu(C);case 5:return new Ku(C)}switch(_r.extractNumericValueFromBitArray(C,1,5)){case 12:return new Nn(C);case 13:return new Yt(C)}switch(_r.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 Fe("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 Gt{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 We(s,null,null,u,ye.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();D.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 ht=0;ht<a.length;ht++)a[ht]=0;if(s)se.recordPatternInReverse(e,n.getStartEnd()[0],a);else{se.recordPattern(e,n.getStartEnd()[1],a);for(let ht=0,Wt=a.length-1;ht<Wt;ht++,Wt--){let ln=a[ht];a[ht]=a[Wt],a[Wt]=ln}}let l=17,u=Me.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 ht=0;ht<a.length;ht++){let Wt=1*a[ht]/u,ln=Wt+.5;if(ln<1){if(Wt<.3)throw new q;ln=1}else if(ln>8){if(Wt>8.7)throw new q;ln=8}let Ir=ht/2;(ht&1)==0?(p[Ir]=ln,b[Ir]=Wt-ln):(y[Ir]=ln,I[Ir]=Wt-ln)}this.adjustOddEvenCounts(l);let R=4*n.getValue()+(o?0:2)+(s?0:1)-1,U=0,V=0;for(let ht=p.length-1;ht>=0;ht--){if(se.isNotA1left(n,o,s)){let Wt=se.WEIGHTS[R][2*ht];V+=p[ht]*Wt}U+=p[ht]}let H=0;for(let ht=y.length-1;ht>=0;ht--)if(se.isNotA1left(n,o,s)){let Wt=se.WEIGHTS[R][2*ht+1];H+=y[ht]*Wt}let Q=V+H;if((U&1)!=0||U>13||U<4)throw new q;let fe=(13-U)/2,he=se.SYMBOL_WIDEST[fe],ce=9-he,Ke=Sn.getRSSvalue(p,he,!0),je=Sn.getRSSvalue(y,ce,!1),nn=se.EVEN_TOTAL_SUBSET[fe],wn=se.GSUM[fe],rn=Ke*nn+je+wn;return new wr(rn,Q)}static isNotA1left(e,n,o){return!(e.getValue()==0&&n&&o)}adjustOddEvenCounts(e){let n=Me.sum(new Int32Array(this.getOddCounts())),o=Me.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 wr{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 St extends Gt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,o){const s=this.decodePair(n,!1,e,o);St.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,o);St.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&&St.checkChecksum(l,u))return St.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 de;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 We(a.toString(),null,0,[u[0],u[1],h[0],h[1]],ye.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)xt.recordPatternInReverse(e,n.getStartEnd()[0],s);else{xt.recordPattern(e,n.getStartEnd()[1]+1,s);for(let H=0,Q=s.length-1;H<Q;H++,Q--){let fe=s[H];s[H]=s[Q],s[Q]=fe}}let a=o?16:15,l=Me.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,fe=Math.floor(Q+.5);fe<1?fe=1:fe>8&&(fe=8);let he=Math.floor(H/2);(H&1)===0?(u[he]=fe,p[he]=Q-fe):(h[he]=fe,y[he]=Q-fe)}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=St.OUTSIDE_ODD_WIDEST[H],fe=9-Q,he=Sn.getRSSvalue(u,Q,!1),ce=Sn.getRSSvalue(h,fe,!0),Ke=St.OUTSIDE_EVEN_TOTAL_SUBSET[H],je=St.OUTSIDE_GSUM[H];return new wr(he*Ke+ce+je,V)}else{if((U&1)!==0||U>10||U<4)throw new q;let H=(10-U)/2,Q=St.INSIDE_ODD_WIDEST[H],fe=9-Q,he=Sn.getRSSvalue(u,Q,!0),ce=Sn.getRSSvalue(h,fe,!1),Ke=St.INSIDE_ODD_TOTAL_SUBSET[H],je=St.INSIDE_GSUM[H];return new wr(ce*Ke+he+je,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(Gt.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);D.arraycopy(h,0,p,1,h.length-1),p[0]=u;const y=this.parseFinderValue(p,St.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=Me.sum(new Int32Array(this.getOddCounts())),s=Me.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;Gt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Gt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),u){if(h)throw new q;Gt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&Gt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}St.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],St.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],St.OUTSIDE_GSUM=[0,161,961,2015,2715],St.INSIDE_GSUM=[0,336,1036,1516],St.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],St.INSIDE_ODD_WIDEST=[2,4,6,8],St.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 Cr extends xt{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(ye.EAN_13)||o.includes(ye.UPC_A)||o.includes(ye.EAN_8)||o.includes(ye.UPC_E))&&this.readers.push(new $o(e)),o.includes(ye.CODE_39)&&this.readers.push(new O(s)),o.includes(ye.CODE_128)&&this.readers.push(new me),o.includes(ye.ITF)&&this.readers.push(new ne),o.includes(ye.RSS_14)&&this.readers.push(new St),o.includes(ye.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 me),this.readers.push(new ne),this.readers.push(new St),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 _e{constructor(e=500,n){super(new Cr(n),e,n)}}class st{constructor(e,n,o){this.ecCodewords=e,this.ecBlocks=[n],o&&this.ecBlocks.push(o)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class rt{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 st(5,new rt(1,3))),new Qe(2,12,12,10,10,new st(7,new rt(1,5))),new Qe(3,14,14,12,12,new st(10,new rt(1,8))),new Qe(4,16,16,14,14,new st(12,new rt(1,12))),new Qe(5,18,18,16,16,new st(14,new rt(1,18))),new Qe(6,20,20,18,18,new st(18,new rt(1,22))),new Qe(7,22,22,20,20,new st(20,new rt(1,30))),new Qe(8,24,24,22,22,new st(24,new rt(1,36))),new Qe(9,26,26,24,24,new st(28,new rt(1,44))),new Qe(10,32,32,14,14,new st(36,new rt(1,62))),new Qe(11,36,36,16,16,new st(42,new rt(1,86))),new Qe(12,40,40,18,18,new st(48,new rt(1,114))),new Qe(13,44,44,20,20,new st(56,new rt(1,144))),new Qe(14,48,48,22,22,new st(68,new rt(1,174))),new Qe(15,52,52,24,24,new st(42,new rt(2,102))),new Qe(16,64,64,14,14,new st(56,new rt(2,140))),new Qe(17,72,72,16,16,new st(36,new rt(4,92))),new Qe(18,80,80,18,18,new st(48,new rt(4,114))),new Qe(19,88,88,20,20,new st(56,new rt(4,144))),new Qe(20,96,96,22,22,new st(68,new rt(4,174))),new Qe(21,104,104,24,24,new st(56,new rt(6,136))),new Qe(22,120,120,18,18,new st(68,new rt(6,175))),new Qe(23,132,132,20,20,new st(62,new rt(8,163))),new Qe(24,144,144,22,22,new st(62,new rt(8,156),new rt(2,155))),new Qe(25,8,18,6,16,new st(7,new rt(1,5))),new Qe(26,8,32,6,14,new st(11,new rt(1,10))),new Qe(27,12,26,10,24,new st(14,new rt(1,16))),new Qe(28,12,36,10,16,new st(18,new rt(1,22))),new Qe(29,16,36,14,16,new st(24,new rt(1,32))),new Qe(30,16,48,14,22,new st(28,new rt(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 fe=0;fe<a;++fe){const he=R*(a+2)+1+fe;if(e.get(he,H)){const ce=U+fe;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(),fe=o.getECCodewords()+Q;l[u++]=new qo(Q,new Uint8Array(fe))}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,fe=I&&Q>7?V-1:V;l[Q].codewords[fe]=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 de,s=new de,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 Ee(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,pe.ISO88591))}catch(h){throw new Fe("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 Ft(ie.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 Xt(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 an.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 We(o.getText(),a,8*a.length,s,ye.DATA_MATRIX,D.currentTimeMillis()),u=o.getByteSegments();u!=null&&l.putMetadata(tt.BYTE_SEGMENTS,u);const h=o.getECLevel();return h!=null&&l.putMetadata(tt.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 _e{constructor(e=500){super(new Gn,e)}}var br;(function(C){C[C.L=0]="L",C[C.M=1]="M",C[C.Q=2]="Q",C[C.H=3]="H"})(br||(br={}));class mt{constructor(e,n,o){this.value=e,this.stringValue=n,this.bits=o,mt.FOR_BITS.set(o,this),mt.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return mt.L;case"M":return mt.M;case"Q":return mt.Q;case"H":return mt.H;default:throw new E(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof mt))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=mt.FOR_BITS.size)throw new A;return mt.FOR_BITS.get(e)}}mt.FOR_BITS=new Map,mt.FOR_VALUE=new Map,mt.L=new mt(br.L,"L",1),mt.M=new mt(br.M,"M",0),mt.Q=new mt(br.Q,"Q",3),mt.H=new mt(br.H,"H",2);class qt{constructor(e){this.errorCorrectionLevel=mt.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return F.bitCount(e^n)}static decodeFormatInformation(e,n){const o=qt.doDecodeFormatInformation(e,n);return o!==null?o:qt.doDecodeFormatInformation(e^qt.FORMAT_INFO_MASK_QR,n^qt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let o=Number.MAX_SAFE_INTEGER,s=0;for(const a of qt.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new qt(a[1]);let u=qt.numBitsDiffering(e,l);u<o&&(s=a[1],o=u),e!==n&&(u=qt.numBitsDiffering(n,l),u<o&&(s=a[1],o=u))}return o<=3?new qt(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof qt))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}qt.FORMAT_INFO_MASK_QR=21522,qt.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=qt.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 zt;(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"})(zt||(zt={}));class mn{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)}}mn.values=new Map([[zt.DATA_MASK_000,new mn(zt.DATA_MASK_000,(C,e)=>(C+e&1)===0)],[zt.DATA_MASK_001,new mn(zt.DATA_MASK_001,(C,e)=>(C&1)===0)],[zt.DATA_MASK_010,new mn(zt.DATA_MASK_010,(C,e)=>e%3===0)],[zt.DATA_MASK_011,new mn(zt.DATA_MASK_011,(C,e)=>(C+e)%3===0)],[zt.DATA_MASK_100,new mn(zt.DATA_MASK_100,(C,e)=>(Math.floor(C/2)+Math.floor(e/3)&1)===0)],[zt.DATA_MASK_101,new mn(zt.DATA_MASK_101,(C,e)=>C*e%6===0)],[zt.DATA_MASK_110,new mn(zt.DATA_MASK_110,(C,e)=>C*e%6<3)],[zt.DATA_MASK_111,new mn(zt.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=qt.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=mn.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=mn.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 gn;(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"})(gn||(gn={}));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(gn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Re.NUMERIC=new Re(gn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Re.ALPHANUMERIC=new Re(gn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Re.STRUCTURED_APPEND=new Re(gn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Re.BYTE=new Re(gn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Re.ECI=new Re(gn.ECI,"ECI",Int32Array.from([0,0,0]),7),Re.KANJI=new Re(gn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Re.FNC1_FIRST_POSITION=new Re(gn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Re.FNC1_SECOND_POSITION=new Re(gn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Re.HANZI=new Re(gn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class Et{static decode(e,n,o,s){const a=new Xo(e);let l=new de;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 Ee(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,pe.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,pe.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=pe.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 Ft(ie.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 Vt{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*Vt.MAX_MODULES));(u<Vt.MIN_SKIP||n)&&(u=Vt.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(Vt.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]++;Vt.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&&Vt.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:Vt.foundPatternCross(u)?Vt.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:Vt.foundPatternCross(u)?Vt.centerFromEnd(u,h):NaN}handlePossibleCenter(e,n,o,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=Vt.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()>=Vt.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()>=Vt.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]]}}Vt.CENTER_QUORUM=2,Vt.MIN_SKIP=3,Vt.MAX_MODULES=57;class Mr{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 Vt(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=Mr.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 fe=4;fe<=16;fe<<=1)try{p=this.findAlignmentInRegion(a,H,Q,fe);break}catch(he){if(!(he instanceof q))throw he}}const y=Mr.createTransform(n,o,s,p,l),b=Mr.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),Ut.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 an.getInstance().sampleGridWithTransform(e,o,o,n)}static computeDimension(e,n,o,s){const a=Me.round(be.distance(e,n)/s),l=Me.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 Me.distance(R,U,e,n);b++}if(h+=u,h>0){if(U===s)break;U+=y,h-=l}}return b===2?Me.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 Mr(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 We(o.getText(),o.getRawBytes(),void 0,s,ye.QR_CODE,void 0),l=o.getByteSegments();l!==null&&a.putMetadata(tt.BYTE_SEGMENTS,l);const u=o.getECLevel();return u!==null&&a.putMetadata(tt.ERROR_CORRECTION_LEVEL,u),o.hasStructuredAppend()&&(a.putMetadata(tt.STRUCTURED_APPEND_SEQUENCE,o.getStructuredAppendSequenceNumber()),a.putMetadata(tt.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 Me.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 He{static detectMultiple(e,n,o){let s=e.getBlackMatrix(),a=He.detect(o,s);return a.length||(s=s.clone(),s.rotate180(),a=He.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=He.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+=He.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 He.copyToResult(l,He.findRowsWithPattern(e,s,a,n,o,He.START_PATTERN),He.INDEXES_START_PATTERN),l[4]!=null&&(o=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),He.copyToResult(l,He.findRowsWithPattern(e,s,a,n,o,He.STOP_PATTERN),He.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+=He.ROW_STEP){let b=He.findGuardPattern(e,a,s,o,!1,l,p);if(b!=null){for(;s>0;){const I=He.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=He.findGuardPattern(e,I[0],y,o,!1,l,p);if(R!=null&&Math.abs(I[0]-R[0])<He.MAX_PATTERN_DRIFT&&Math.abs(I[1]-R[1])<He.MAX_PATTERN_DRIFT)I=R,b=0;else{if(b>He.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<He.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++<He.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(He.patternMatchVariance(u,l,He.MAX_INDIVIDUAL_VARIANCE)<He.MAX_AVG_VARIANCE)return new Int32Array([h,y]);h+=u[0]+u[1],D.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&&He.patternMatchVariance(u,l,He.MAX_INDIVIDUAL_VARIANCE)<He.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}}He.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),He.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),He.MAX_AVG_VARIANCE=.42,He.MAX_INDIVIDUAL_VARIANCE=.8,He.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),He.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),He.MAX_PIXEL_DRIFT=3,He.MAX_PATTERN_DRIFT=5,He.SKIPPED_ROW_COUNT_MAX=25,He.ROW_STEP=5,He.BARCODE_MIN_HEIGHT=10;class jt{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),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],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;D.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 jt(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 jt?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 jt(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 jt(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 jt(this.field,n)}multiplyScalar(e){if(e===0)return new jt(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 jt(this.field,o)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return new jt(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 jt(this.field,s)}toString(){let e=new de;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 xe;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 jt(this,new Int32Array([0])),this.one=new jt(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 jt(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 jt(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 jt(this.field,new Int32Array([this.field.subtract(0,V),1]));u=u.multiply(H)}let h=new jt(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(),fe=this.field.multiply(a.getCoefficient(a.getDegree()),H);U=U.add(this.field.buildMonomial(Q,fe)),a=a.subtract(s.multiplyByMonomial(Q,fe))}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 jt(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 sr{constructor(e,n,o,s,a){e instanceof sr?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 sr(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 sr(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 Dr{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+=Dr.form(e,n)}toString(){return this.buffer}}class Pr{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 o=1;o<Pr.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 Dr;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()}}Pr.MAX_NEARBY_DISTANCE=5;class Br{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 Pr{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 Br,o=new Br,s=new Br,a=new Br;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 Lr{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=Lr.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=Lr.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(Lr.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 Dr;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 Fr{constructor(e,n,o,s){this.rowNumber=Fr.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!==Fr.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}}Fr.BARCODE_ROW_UNKNOWN=-1;class tn{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,tn.RATIOS_TABLE[e]||(tn.RATIOS_TABLE[e]=new Array(Be.BARS_IN_MODULE)),tn.RATIOS_TABLE[e][Be.BARS_IN_MODULE-s-1]=Math.fround(a/Be.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=Me.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=tn.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=Me.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=kt.MAX_VALUE,a=-1;this.bSymbolTableReady||tn.initialize();for(let l=0;l<tn.RATIOS_TABLE.length;l++){let u=0,h=tn.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}}tn.bSymbolTableReady=!1,tn.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),D.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 dt;(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"})(dt||(dt={}));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 de(""),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 Ee(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 de;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 de;n=K.textCompaction(e,n+1,u),o.setFileName(u.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new de;n=K.textCompaction(e,n+1,h),o.setSender(h.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new de;n=K.textCompaction(e,n+1,p),o.setAddressee(p.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new de;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 de;n=K.numericCompaction(e,n+1,b),o.setTimestamp(ps.parseLong(b.toString()));break;case K.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new de;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 de;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=dt.ALPHA,l=dt.ALPHA,u=0;for(;u<o;){let h=e[u],p="";switch(a){case dt.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case K.LL:a=dt.LOWER;break;case K.ML:a=dt.MIXED;break;case K.PS:l=a,a=dt.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=dt.ALPHA;break}break;case dt.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case K.AS:l=a,a=dt.ALPHA_SHIFT;break;case K.ML:a=dt.MIXED;break;case K.PS:l=a,a=dt.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=dt.ALPHA;break}break;case dt.MIXED:if(h<K.PL)p=K.MIXED_CHARS[h];else switch(h){case K.PL:a=dt.PUNCT;break;case 26:p=" ";break;case K.LL:a=dt.LOWER;break;case K.AL:a=dt.ALPHA;break;case K.PS:l=a,a=dt.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=dt.ALPHA;break}break;case dt.PUNCT:if(h<K.PAL)p=K.PUNCT_CHARS[h];else switch(h){case K.PAL:a=dt.ALPHA;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=dt.ALPHA;break}break;case dt.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=dt.ALPHA;break}break;case dt.PUNCT_SHIFT:if(a=l,h<K.PAL)p=K.PUNCT_CHARS[h];else switch(h){case K.PAL:a=dt.ALPHA;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=dt.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 sr(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 Pr(h),b.setDetectionResultColumn(V,H);let Q=-1,fe=Q;for(let he=h.getMinY();he<=h.getMaxY();he++){if(Q=Ge.getStartColumn(b,V,he,R),Q<0||Q>h.getMaxX()){if(fe===-1)continue;Q=fe}let ce=Ge.detectCodeword(e,h.getMinX(),h.getMaxX(),R,Q,he,l,u);ce!=null&&(H.setCodeword(he,ce),fe=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=sr.merge(Ge.adjustBoundingBox(e),Ge.adjustBoundingBox(n));return new Lr(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 Br;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=Me.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=tn.getDecodedValue(p),R=Be.getCodeword(I);return R===-1?null:new Fr(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 Dr;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 Ht{decode(e,n=null){let o=Ht.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 Ht.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=He.detectMultiple(e,n,o);for(const l of a.getPoints()){const u=Ge.decode(a.getBits(),l[4],l[5],l[6],l[7],Ht.getMinCodewordWidth(l),Ht.getMaxCodewordWidth(l)),h=new We(u.getText(),u.getRawBytes(),void 0,l,ye.PDF_417);h.putMetadata(tt.ERROR_CORRECTION_LEVEL,u.getECLevel());const p=u.getOther();p!=null&&h.putMetadata(tt.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(Ht.getMaxWidth(e[0],e[4]),Ht.getMaxWidth(e[6],e[2])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN),Math.max(Ht.getMaxWidth(e[1],e[5]),Ht.getMaxWidth(e[7],e[3])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(Ht.getMinWidth(e[0],e[4]),Ht.getMinWidth(e[6],e[2])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN),Math.min(Ht.getMinWidth(e[1],e[5]),Ht.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===ye.UPC_A||l===ye.UPC_E||l===ye.EAN_13||l===ye.EAN_8||l===ye.CODABAR||l===ye.CODE_39||l===ye.CODE_93||l===ye.CODE_128||l===ye.ITF||l===ye.RSS_14||l===ye.RSS_EXPANDED);a&&!n&&s.push(new Cr(e,this.verbose)),o.includes(ye.QR_CODE)&&s.push(new qn),o.includes(ye.DATA_MATRIX)&&s.push(new Gn),o.includes(ye.AZTEC)&&s.push(new Ln),o.includes(ye.PDF_417)&&s.push(new Ht),a&&n&&s.push(new Cr(e,this.verbose))}s.length===0&&(n||s.push(new Cr(e,this.verbose)),s.push(new qn),s.push(new Gn),s.push(new Ln),s.push(new Ht),n&&s.push(new Cr(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 _e{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 _e{constructor(e=500){super(new Ht,e)}}class pd extends _e{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);D.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;D.arraycopy(h,0,e,o+p,h.length)}}class Tt{constructor(){}static applyMaskPenaltyRule1(e){return Tt.applyMaskPenaltyRule1Internal(e,!0)+Tt.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 Tt.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&&(Tt.isWhiteHorizontal(h,u-4,u)||Tt.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&&(Tt.isWhiteVertical(o,u,l-4,l)||Tt.isWhiteVertical(o,u,l+7,l+11))&&n++}return n*Tt.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)*Tt.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+=Tt.N1+(h-5)),h=1,p=b)}h>=5&&(o+=Tt.N1+(h-5))}return o}}Tt.N1=3,Tt.N2=3,Tt.N3=40,Tt.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 de;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 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 de;return e.append(`<<
|
|
71
71
|
`),e.append(" mode: "),e.append(this.mode?this.mode.toString():"null"),e.append(`
|
|
72
72
|
ecLevel: `),e.append(this.ecLevel?this.ecLevel.toString():"null"),e.append(`
|
|
73
73
|
version: `),e.append(this.version?this.version.toString():"null"),e.append(`
|
|
@@ -76,9 +76,9 @@ ${this.tempPrompt}
|
|
|
76
76
|
`),e.append(this.matrix.toString())):e.append(`
|
|
77
77
|
matrix: null
|
|
78
78
|
`),e.append(`>>
|
|
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][
|
|
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=lw();const cw=sw(yt),uw=Td({__proto__:null,default:cw},[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(),!uw)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})(),dw=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())})},fw=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 dw(this,void 0,void 0,function(){var i,c;return fw(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}}},hw=(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})(),pw=(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),mw=(function(t){os(r,t);function r(i){return t.call(this,"zoom",i)||this}return r})(pw),gw=(function(t){os(r,t);function r(i){return t.call(this,"torch",i)||this}return r})(Gu),xw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new mw(this.track)},t.prototype.torchFeature=function(){return new gw(this.track)},t})(),yw=(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 xw(this.getFirstTrackOrFail())},t})(),ww=(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,yw.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}}},_w=(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,ww.create(r)]})})},t})(),vw=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())})},Cw=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}}},bw=(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 vw(this,void 0,void 0,function(){var r,i,c,d,f,m,x;return Cw(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 Aw=(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})(),Ew=(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})(),Iw=(function(){function t(){}return t.create=function(){return new Ew(new Aw)},t})(),Sw=(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){Sw(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})(rw),Tw=(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 iw(this.verbose),this.qrcode=new hw(this.getSupportedFormats(i),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Iw.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=Tw.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)}};_w.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 bw.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];nw(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,ow.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 Nw={class:"scan-code"},Ow={class:"btn"},kw={class:"left-back"},Rw=_.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",Nw,[D[1]||(D[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",Ow,[_.createElementVNode("div",kw,[_.createVNode(T,{name:"arrow-left",onClick:v})])])],512),[[_.vShow,f.value]])]))])}}}),Mw=nr(Rw,[["__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 Dw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Pw=Object.prototype.toString,Bw=t=>Pw.call(t)==="[object Object]",No=()=>{};function wi(t){return Array.isArray(t)?t:[t]}function Lw(t,r,i){return _.watch(t,r,{...i,immediate:!0})}const qu=Dw?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 Lw(()=>{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=Bw(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 Fw(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 Uw=["data-active","disabled"],zw=_.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,Uw))}}),ss=nr(zw,[["__scopeId","data-v-6f582cce"]]),Vw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function Zw(t,r){return _.openBlock(),_.createElementBlock("svg",Vw,[...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 $w={render:Zw},jw={class:"button-text"},Hw={class:"dropdown-menu__items"},Ww=["onClick"],Gw=_.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 Fw(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",jw,_.toDisplayString(_.unref(d)?.label),1),_.createVNode(_.unref($w),{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",Hw,[(_.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,Ww))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):_.createCommentVNode("",!0)],512))}}),qw=nr(Gw,[["__scopeId","data-v-475491fd"]]),Xw={key:0,class:"active-count"},Yw=_.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",Xw,_.toDisplayString(i.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),Kw=nr(Yw,[["__scopeId","data-v-c2a16c66"]]),Jw={"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 Qw(t,r){return _.openBlock(),_.createElementBlock("svg",Jw,[...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 e_={render:Qw},t_=_.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(e_),{width:16,height:16}),d[0]||(d[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),n_=nr(t_,[["__scopeId","data-v-7f3b0372"]]),r_={class:"bubble-image-wrapper"},o_=["src"],i_=["src"],s_=_.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",r_,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,o_),(_.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,i_)])],32)):_.createCommentVNode("",!0)]))]))}}),a_=nr(s_,[["__scopeId","data-v-91c75579"]]),l_=`
|
|
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<ar.NUM_MASK_PATTERNS}}ar.NUM_MASK_PATTERNS=8;class ft extends g{}ft.kind="WriterException";class Pe{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,o,s,a){Pe.clearMatrix(a),Pe.embedBasicPatterns(o,a),Pe.embedTypeInfo(n,s,a),Pe.maybeEmbedVersionInfo(o,a),Pe.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){Pe.embedPositionDetectionPatternsAndSeparators(n),Pe.embedDarkDotAtLeftBottomCorner(n),Pe.maybeEmbedPositionAdjustmentPatterns(e,n),Pe.embedTimingPatterns(n)}static embedTypeInfo(e,n,o){const s=new re;Pe.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const u=s.get(s.getSize()-1-a),h=Pe.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;Pe.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(!Pe.isEmpty(o.get(p,u)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&Tt.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 ft("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=Pe.findMSBSet(n);for(e<<=o-1;Pe.findMSBSet(e)>=o;)e^=n<<Pe.findMSBSet(e)-o;return e}static makeTypeInfoBits(e,n,o){if(!ar.isValidMaskPattern(n))throw new ft("Invalid mask pattern");const s=e.getBits()<<3|n;o.appendBits(s,5);const a=Pe.calculateBCHCode(s,Pe.TYPE_INFO_POLY);o.appendBits(a,10);const l=new re;if(l.appendBits(Pe.TYPE_INFO_MASK_PATTERN,15),o.xor(l),o.getSize()!==15)throw new ft("should not happen but we got: "+o.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const o=Pe.calculateBCHCode(e.getVersionNumber(),Pe.VERSION_INFO_POLY);if(n.appendBits(o,12),n.getSize()!==18)throw new ft("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;Pe.isEmpty(e.get(n,6))&&e.setNumber(n,6,o),Pe.isEmpty(e.get(6,n))&&e.setNumber(6,n,o)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new ft;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,o){for(let s=0;s<8;++s){if(!Pe.isEmpty(o.get(e+s,n)))throw new ft;o.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,o){for(let s=0;s<7;++s){if(!Pe.isEmpty(o.get(e,n+s)))throw new ft;o.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,o){for(let s=0;s<5;++s){const a=Pe.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=Pe.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)o.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=Pe.POSITION_DETECTION_PATTERN[0].length;Pe.embedPositionDetectionPattern(0,0,e),Pe.embedPositionDetectionPattern(e.getWidth()-n,0,e),Pe.embedPositionDetectionPattern(0,e.getWidth()-n,e);const o=8;Pe.embedHorizontalSeparationPattern(0,o-1,e),Pe.embedHorizontalSeparationPattern(e.getWidth()-o,o-1,e),Pe.embedHorizontalSeparationPattern(0,e.getWidth()-o,e);const s=7;Pe.embedVerticalSeparationPattern(s,0,e),Pe.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),Pe.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const o=e.getVersionNumber()-1,s=Pe.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&&Pe.isEmpty(n.get(p,u))&&Pe.embedPositionAdjustmentPattern(p-2,u-2,n)}}}}Pe.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])]),Pe.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])]),Pe.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])]),Pe.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])]),Pe.VERSION_INFO_POLY=7973,Pe.TYPE_INFO_POLY=1335,Pe.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 yt{constructor(){}static calculateMaskPenalty(e){return Tt.applyMaskPenaltyRule1(e)+Tt.applyMaskPenaltyRule2(e)+Tt.applyMaskPenaltyRule3(e)+Tt.applyMaskPenaltyRule4(e)}static encode(e,n,o=null){let s=yt.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||yt.DEFAULT_BYTE_MODE_ENCODING!==s)){const he=z.getCharacterSetECIByName(s);he!==void 0&&this.appendECI(he,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 he=Number.parseInt(o.get(Bt.QR_VERSION).toString(),10);p=Ne.getVersionForNumber(he);const ce=this.calculateBitsNeeded(l,u,h,p);if(!this.willFit(ce,p,n))throw new ft("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 ar;V.setECLevel(n),V.setMode(l),V.setVersion(p);const H=p.getDimensionForVersion(),Q=new go(H,H),fe=this.chooseMaskPattern(U,n,p,Q);return V.setMaskPattern(fe),Pe.buildMatrix(U,n,p,fe,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<yt.ALPHANUMERIC_TABLE.length?yt.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(yt.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<ar.NUM_MASK_PATTERNS;u++){Pe.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(yt.willFit(e,s,n))return s}throw new ft("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 ft("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 ft("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,o,s,a,l){if(s>=o)throw new ft("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 ft("EC bytes mismatch");if(o!==h+u)throw new ft("RS blocks mismatch");if(e!==(b+R)*h+(I+U)*u)throw new ft("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 ft("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);yt.getNumDataBytesAndNumECBytesForBlockID(n,o,s,y,b,I);const R=b[0],U=new Uint8Array(R);e.toBytes(8*a,U,0,R);const V=yt.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 ft("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 ft("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(ie.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 ft(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,o,s){switch(n){case Re.NUMERIC:yt.appendNumericBytes(e,o);break;case Re.ALPHANUMERIC:yt.appendAlphanumericBytes(e,o);break;case Re.BYTE:yt.append8BitBytes(e,o,s);break;case Re.KANJI:yt.appendKanjiBytes(e,o);break;default:throw new ft("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=yt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const o=e.length;let s=0;for(;s<o;){const a=yt.getDigit(e.charAt(s));if(s+2<o){const l=yt.getDigit(e.charAt(s+1)),u=yt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+u,10),s+=3}else if(s+1<o){const l=yt.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=yt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new ft;if(s+1<o){const l=yt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new ft;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 ft(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 ft(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 ft("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)}}yt.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]),yt.DEFAULT_BYTE_MODE_ENCODING=z.UTF8.getName();class lr{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=mt.L,l=lr.QUIET_ZONE_SIZE;s!==null&&(s.get(Bt.ERROR_CORRECTION)!==void 0&&(a=mt.fromString(s.get(Bt.ERROR_CORRECTION).toString())),s.get(Bt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Bt.MARGIN).toString(),10)));const u=yt.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 Fe;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 fe=0,he=R;fe<l;fe++,he+=I)if(a.get(fe,H)===1){const ce=this.createSvgRectElement(he,Q,I,I);V.appendChild(ce)}return V}createSVGElement(e,n){const o=document.createElementNS(lr.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(lr.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}}lr.QUIET_ZONE_SIZE=4,lr.SVG_NS="http://www.w3.org/2000/svg";class Ar{encode(e,n,o,s,a){if(e.length===0)throw new A("Found empty contents");if(n!==ye.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=mt.L,u=Ar.QUIET_ZONE_SIZE;a!==null&&(a.get(Bt.ERROR_CORRECTION)!==void 0&&(l=mt.fromString(a.get(Bt.ERROR_CORRECTION).toString())),a.get(Bt.MARGIN)!==void 0&&(u=Number.parseInt(a.get(Bt.MARGIN).toString(),10)));const h=yt.encode(e,l,a);return Ar.renderResult(h,o,s,u)}static renderResult(e,n,o,s){const a=e.getMatrix();if(a===null)throw new Fe;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 fe=0,he=R;fe<l;fe++,he+=I)a.get(fe,H)===1&&V.setRegion(he,Q,I,I);return V}}Ar.QUIET_ZONE_SIZE=4;class gd{encode(e,n,o,s,a){let l;switch(n){case ye.QR_CODE:l=new Ar;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 D.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 D.arraycopy(this.yuvData,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;D.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 D.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 D.arraycopy(this.luminances,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;D.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 Er 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 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,"<"+F.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class oi extends Er{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 Ur(C,e,n){return new Er(C,e,n)}const wd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Yn=0,xo=1,xn=2,vs=3,kn=4,_d=new Er(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[xn][kn]=0,C[xn][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=Ur(s,l&65535,l>>16),o+=l>>16}let a=e===xn?4:5;return s=Ur(s,n,a),new Rn(s,e,0,o+a)}shiftAndAppend(e,n){let o=this.token,s=this.mode===xn?4:5;return o=Ur(o,Cs[this.mode][e],s),o=Ur(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===xn){let u=ii[o][Yn];n=Ur(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 pe.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=pe.getCharCode(" "),n=pe.getCharCode("."),o=pe.getCharCode(",");C[Yn][e]=1;const s=pe.getCharCode("Z"),a=pe.getCharCode("A");for(let I=a;I<=s;I++)C[Yn][I]=I-a+2;C[xo][e]=1;const l=pe.getCharCode("z"),u=pe.getCharCode("a");for(let I=u;I<=l;I++)C[xo][I]=I-u+2;C[xn][e]=1;const h=pe.getCharCode("9"),p=pe.getCharCode("0");for(let I=p;I<=h;I++)C[xn][I]=I-p+2;C[xn][o]=12,C[xn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
|
|
80
|
+
`,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)C[vs][pe.getCharCode(y[I])]=I;const b=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<b.length;I++)pe.getCharCode(b[I])>0&&(C[kn][pe.getCharCode(b[I])]=I);return C}const si=Cd($.createInt32Array(5,256));class zr{constructor(e){this.text=e}encode(){const e=pe.getCharCode(" "),n=pe.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 pe.getCharCode("\r"):l=u===n?2:0;break;case pe.getCharCode("."):l=u===e?3:0;break;case pe.getCharCode(","):l=u===e?4:0;break;case pe.getCharCode(":"):l=u===e?5:0;break;default:l=0}l>0?(o=zr.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 zr.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===xn){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(xn,16-o).latchAndAppend(xn,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 et{constructor(){}static encodeBytes(e){return et.encode(e,et.DEFAULT_EC_PERCENT,et.DEFAULT_AZTEC_LAYERS)}static encode(e,n,o){let s=new zr(e).encode(),a=F.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,u,h,p,y,b;if(o!==et.DEFAULT_AZTEC_LAYERS){if(u=o<0,h=Math.abs(o),h>(u?et.MAX_NB_BITS_COMPACT:et.MAX_NB_BITS))throw new A(pe.format("Illegal value %s for layers",o));p=et.totalBitsInLayer(h,u),y=et.WORD_SIZE[h];let ce=p-p%y;if(b=et.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>et.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(u=ce<=3,h=u?ce+1:ce,p=et.totalBitsInLayer(h,u),l>p)continue;(b==null||y!==et.WORD_SIZE[h])&&(y=et.WORD_SIZE[h],b=et.stuffBits(s,y));let Ke=p-p%y;if(!(u&&b.getSize()>y*64)&&b.getSize()+a<=Ke)break}}let I=et.generateCheckWords(b,p,y),R=b.getSize()/y,U=et.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 je=0;je<ce;je++){let nn=je+F.truncDivision(je,15);H[ce-je-1]=Ke-nn-1,H[ce+je]=Ke+nn+1}}let fe=new te(Q);for(let ce=0,Ke=0;ce<h;ce++){let je=(h-ce)*4+(u?9:12);for(let nn=0;nn<je;nn++){let wn=nn*2;for(let rn=0;rn<2;rn++)I.get(Ke+wn+rn)&&fe.set(H[ce*2+rn],H[ce*2+nn]),I.get(Ke+je*2+wn+rn)&&fe.set(H[ce*2+nn],H[V-1-ce*2-rn]),I.get(Ke+je*4+wn+rn)&&fe.set(H[V-1-ce*2-rn],H[V-1-ce*2-nn]),I.get(Ke+je*6+wn+rn)&&fe.set(H[V-1-ce*2-nn],H[ce*2+rn])}Ke+=je*8}if(et.drawModeMessage(fe,u,Q,U),u)et.drawBullsEye(fe,F.truncDivision(Q,2),5);else{et.drawBullsEye(fe,F.truncDivision(Q,2),7);for(let ce=0,Ke=0;ce<F.truncDivision(V,2)-1;ce+=15,Ke+=16)for(let je=F.truncDivision(Q,2)&1;je<Q;je+=2)fe.set(F.truncDivision(Q,2)-Ke,je),fe.set(F.truncDivision(Q,2)+Ke,je),fe.set(je,F.truncDivision(Q,2)-Ke),fe.set(je,F.truncDivision(Q,2)+Ke)}let he=new ws;return he.setCompact(u),he.setSize(Q),he.setLayers(h),he.setCodeWords(R),he.setMatrix(fe),he}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=et.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(o-1,11),s=et.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(et.getGF(o)),l=F.truncDivision(n,o),u=et.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 ie.AZTEC_PARAM;case 6:return ie.AZTEC_DATA_6;case 8:return ie.AZTEC_DATA_8;case 10:return ie.AZTEC_DATA_10;case 12:return ie.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}}et.DEFAULT_EC_PERCENT=33,et.DEFAULT_AZTEC_LAYERS=0,et.MAX_NB_BITS=32,et.MAX_NB_BITS_COMPACT=4,et.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=et.DEFAULT_EC_PERCENT,h=et.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!==ye.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=et.encode(pe.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 Fe;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=xe,i.AztecCode=ws,i.AztecCodeReader=Ln,i.AztecCodeWriter=yo,i.AztecDecoder=qe,i.AztecDetector=rr,i.AztecDetectorResult=$n,i.AztecEncoder=et,i.AztecHighLevelEncoder=zr,i.AztecPoint=At,i.BarcodeFormat=ye,i.Binarizer=S,i.BinaryBitmap=P,i.BitArray=re,i.BitMatrix=te,i.BitSource=Xo,i.BrowserAztecCodeReader=yr,i.BrowserBarcodeReader=Qu,i.BrowserCodeReader=_e,i.BrowserDatamatrixCodeReader=td,i.BrowserMultiFormatReader=fd,i.BrowserPDF417Reader=hd,i.BrowserQRCodeReader=pd,i.BrowserQRCodeSvgWriter=lr,i.CharacterSetECI=z,i.ChecksumException=T,i.Code128Reader=me,i.Code39Reader=O,i.DataMatrixDecodedBitStreamParser=Wn,i.DataMatrixReader=Gn,i.DecodeHintType=B,i.DecoderResult=Ee,i.DefaultGridSampler=nr,i.DetectorResult=Bn,i.EAN13Reader=Fn,i.EncodeHintType=Bt,i.Exception=g,i.FormatException=L,i.GenericGF=ie,i.GenericGFPoly=J,i.GlobalHistogramBinarizer=ke,i.GridSampler=jn,i.GridSamplerInstance=an,i.HTMLCanvasElementLuminanceSource=ze,i.HybridBinarizer=le,i.ITFReader=ne,i.IllegalArgumentException=A,i.IllegalStateException=Fe,i.InvertedLuminanceSource=Je,i.LuminanceSource=Te,i.MathUtils=Me,i.MultiFormatOneDReader=Cr,i.MultiFormatReader=xs,i.MultiFormatWriter=gd,i.NotFoundException=q,i.OneDReader=xt,i.PDF417DecodedBitStreamParser=K,i.PDF417DecoderErrorCorrection=ds,i.PDF417Reader=Ht,i.PDF417ResultMetadata=hs,i.PerspectiveTransform=Ut,i.PlanarYUVLuminanceSource=On,i.QRCodeByteMatrix=go,i.QRCodeDataMask=mn,i.QRCodeDecodedBitStreamParser=Et,i.QRCodeDecoderErrorCorrectionLevel=mt,i.QRCodeDecoderFormatInformation=qt,i.QRCodeEncoder=yt,i.QRCodeEncoderQRCode=ar,i.QRCodeMaskUtil=Tt,i.QRCodeMatrixUtil=Pe,i.QRCodeMode=Re,i.QRCodeReader=qn,i.QRCodeVersion=Ne,i.QRCodeWriter=Ar,i.RGBLuminanceSource=ni,i.RSS14Reader=St,i.RSSExpandedReader=se,i.ReaderException=mo,i.ReedSolomonDecoder=Ft,i.ReedSolomonEncoder=ti,i.ReedSolomonException=ge,i.Result=We,i.ResultMetadataType=tt,i.ResultPoint=be,i.StringUtils=pe,i.UnsupportedOperationException=we,i.VideoInputDevice=Xe,i.WhiteRectangleDetector=Xt,i.WriterException=ft,i.ZXingArrays=$,i.ZXingCharset=ys,i.ZXingInteger=F,i.ZXingStandardCharsets=ri,i.ZXingStringBuilder=de,i.ZXingStringEncoding=G,i.ZXingSystem=D,i.createAbstractExpandedDecoder=cs,Object.defineProperty(i,"__esModule",{value:!0})}))})(Gr,Gr.exports)),Gr.exports}var wt=cw();const uw=aw(wt),dw=Td({__proto__:null,default:uw},[wt]);var dl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,wt.BarcodeFormat.QR_CODE],[Ce.AZTEC,wt.BarcodeFormat.AZTEC],[Ce.CODABAR,wt.BarcodeFormat.CODABAR],[Ce.CODE_39,wt.BarcodeFormat.CODE_39],[Ce.CODE_93,wt.BarcodeFormat.CODE_93],[Ce.CODE_128,wt.BarcodeFormat.CODE_128],[Ce.DATA_MATRIX,wt.BarcodeFormat.DATA_MATRIX],[Ce.MAXICODE,wt.BarcodeFormat.MAXICODE],[Ce.ITF,wt.BarcodeFormat.ITF],[Ce.EAN_13,wt.BarcodeFormat.EAN_13],[Ce.EAN_8,wt.BarcodeFormat.EAN_8],[Ce.PDF_417,wt.BarcodeFormat.PDF_417],[Ce.RSS_14,wt.BarcodeFormat.RSS_14],[Ce.RSS_EXPANDED,wt.BarcodeFormat.RSS_EXPANDED],[Ce.UPC_A,wt.BarcodeFormat.UPC_A],[Ce.UPC_E,wt.BarcodeFormat.UPC_E],[Ce.UPC_EAN_EXTENSION,wt.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!dw)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(wt.DecodeHintType.POSSIBLE_FORMATS,d),f.set(wt.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 wt.MultiFormatReader(this.verbose,this.hints),c=new wt.HTMLCanvasElementLuminanceSource(r),d=new wt.BinaryBitmap(new wt.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})(),fw=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())})},hw=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 fw(this,void 0,void 0,function(){var i,c;return hw(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}}},pw=(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})(),mw=(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),gw=(function(t){os(r,t);function r(i){return t.call(this,"zoom",i)||this}return r})(mw),xw=(function(t){os(r,t);function r(i){return t.call(this,"torch",i)||this}return r})(Gu),yw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new gw(this.track)},t.prototype.torchFeature=function(){return new xw(this.track)},t})(),ww=(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 yw(this.getFirstTrackOrFail())},t})(),_w=(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,ww.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}}},vw=(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,_w.create(r)]})})},t})(),Cw=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())})},bw=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}}},Aw=(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=kr.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=kr.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 Cw(this,void 0,void 0,function(){var r,i,c,d,f,m,x;return bw(this,function(v){switch(v.label){case 0:return r=function(g){for(var E=g.getVideoTracks(),A=0,P=E;A<P.length;A++){var T=P[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})(),Nt;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(Nt||(Nt={}));var Ew=(function(){function t(){this.state=Nt.NOT_STARTED,this.onGoingTransactionNewState=Nt.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===Nt.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=Nt.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===Nt.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=Nt.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==Nt.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case Nt.UNKNOWN:throw"Transition from unknown is not allowed";case Nt.NOT_STARTED:this.failIfNewStateIs(r,[Nt.PAUSED]);break;case Nt.SCANNING:break;case Nt.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})(),Iw=(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()===Nt.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==Nt.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===Nt.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===Nt.PAUSED},t})(),Sw=(function(){function t(){}return t.create=function(){return new Iw(new Ew)},t})(),Tw=(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)}})(),cn=(function(t){Tw(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})(ow),Nw=(function(){function t(r,i){this.logger=i,this.fps=cn.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=cn.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 sw(this.verbose),this.qrcode=new pw(this.getSupportedFormats(i),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Sw.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=Nw.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:cn.DEFAULT_WIDTH,E.style.position="relative",this.shouldScan=!0,this.element=E;var A=this,P=this.stateManagerProxy.startTransition(Nt.SCANNING);return new Promise(function(T,S){var D=g?x.videoConstraints:A.createVideoConstraints(r);if(!D){P.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)}};vw.failIfNotSupported().then(function($){$.create(D).then(function(F){return F.render(f.element,M,ee).then(function(re){A.renderedCamera=re,P.execute(),T(null)}).catch(function(re){P.cancel(),S(re)})}).catch(function(F){P.cancel(),S(kr.errorGettingUserMedia(F))})}).catch(function($){P.cancel(),S(kr.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(Nt.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(Nt.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(Nt.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(cn.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:cn.DEFAULT_WIDTH,A=Math.max(g.clientHeight?g.clientHeight:v,cn.FILE_SCAN_MIN_HEIGHT),P=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,P.x,P.y,P.width,P.height)}var D=cn.FILE_SCAN_HIDDEN_CANVAS_PADDING,M=Math.max(m.width,P.width),ee=Math.max(m.height,P.height),$=M+2*D,F=ee+2*D,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,D,D,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 Aw.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];rw(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<cn.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(cn.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=kr.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=kr.codeParseError(d);return i(f,iw.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 P=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(){P()})):P()}).catch(function(T){d.logger.logError("Error happend while scanning context",T),P()})}},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 P=typeof A;throw"Invalid type of 'deviceId' = ".concat(P)}}}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?cn.BORDER_SHADER_MATCH_COLOR:cn.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(cn.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=cn.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 Ow={class:"scan-code"},kw={class:"btn"},Rw={class:"left-back"},Mw=_.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){ot("摄像头无访问权限!");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):ot("无效的二维码")}catch{ot("无效的二维码")}E()}).catch(A=>{console.log(A),ot({message:"二维码识别失败",duration:3e3})})},x=()=>{g().then(()=>{m()})},v=()=>{E()},g=()=>xl.getCameras().then(A=>{A&&A.length&&(d.html5QrCode=new xl("reader"))}).catch(()=>{ot({message:"摄像头无访问权限!",duration:3e3})}),E=()=>{d.html5QrCode&&d.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),ot("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{d.html5QrCode&&d.html5QrCode.isScanning&&E()}),(A,P)=>{const T=rs;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref(Zt.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:P[0]||(P[0]=S=>x())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",Ow,[P[1]||(P[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",kw,[_.createElementVNode("div",Rw,[_.createVNode(T,{name:"arrow-left",onClick:v})])])],512),[[_.vShow,f.value]])]))])}}}),Dw=tr(Mw,[["__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 P=typeof r=="string"?r:r.value;if(P&&E.some(T=>T.id===P))return P}const A=E.find(P=>P.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(P=>P.id===E)?f.value=E:console.warn(`[useModel] Model not found: ${E}`)}}}const Pw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Bw=Object.prototype.toString,Lw=t=>Bw.call(t)==="[object Object]",No=()=>{};function wi(t){return Array.isArray(t)?t:[t]}function Fw(t,r,i){return _.watch(t,r,{...i,immediate:!0})}const qu=Pw?window:void 0;function qr(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 Fw(()=>{var c,d;return[(c=(d=i.value)===null||d===void 0?void 0:d.map(f=>qr(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=Lw(m)?{...m}:m,E=c.flatMap(A=>d.flatMap(P=>f.map(T=>r(A,P,T,g))));v(()=>{E.forEach(A=>A())})},{flush:"post"})}function Uw(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 $=qr(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 P=M=>{const ee=qr(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),P(M))},{passive:!0,capture:f}),_i(c,"pointerdown",M=>{const ee=qr(t);v=!g(M)&&!!(ee&&!M.composedPath().includes(ee))},{passive:!0}),m&&_i(c,"blur",M=>{setTimeout(()=>{const ee=qr(t);let $=c.document.activeElement;for(;$?.shadowRoot;)$=$.shadowRoot.activeElement;$?.tagName==="IFRAME"&&!ee?.contains(c.document.activeElement)&&r(M)},0)},{passive:!0})].filter(Boolean),D=()=>S.forEach(M=>M());return x?{stop:D,cancel:()=>{v=!1},trigger:M=>{v=!0,P(M),v=!1}}:D}const zw=["data-active","disabled"],Vw=_.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,zw))}}),ss=tr(Vw,[["__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 $w(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 jw={render:$w},Hw={class:"button-text"},Ww={class:"dropdown-menu__items"},Gw=["onClick"],qw=_.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),P=_.ref(null);return Uw(P,()=>{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",Hw,_.toDisplayString(_.unref(d)?.label),1),_.createVNode(_.unref(jw),{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:P},[_.createElementVNode("div",Ww,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),D=>(_.openBlock(),_.createElementBlock("div",{key:D.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":D.id===i.value}]),onClick:_.withModifiers(M=>v(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,Gw))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):_.createCommentVNode("",!0)],512))}}),Xw=tr(qw,[["__scopeId","data-v-475491fd"]]),Yw={key:0,class:"active-count"},Kw=_.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(Rr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),d[1]||(d[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),i.value>0?(_.openBlock(),_.createElementBlock("span",Yw,_.toDisplayString(i.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),Jw=tr(Kw,[["__scopeId","data-v-c2a16c66"]]),Qw={"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 e_(t,r){return _.openBlock(),_.createElementBlock("svg",Qw,[...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 t_={render:e_},n_=_.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(t_),{width:16,height:16}),d[0]||(d[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),r_=tr(n_,[["__scopeId","data-v-7f3b0372"]]),o_={class:"bubble-image-wrapper"},i_=["src"],s_=["src"],a_=_.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",o_,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,i_),(_.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,s_)])],32)):_.createCommentVNode("",!0)]))]))}}),l_=tr(a_,[["__scopeId","data-v-91c75579"]]),c_=`
|
|
82
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">
|
|
83
83
|
<defs>
|
|
84
84
|
<clipPath id="clip657_188316">
|
|
@@ -91,4 +91,4 @@ ${this.tempPrompt}
|
|
|
91
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>
|
|
92
92
|
</g>
|
|
93
93
|
</svg>
|
|
94
|
-
`,c_=btoa(l_),wl=`data:image/svg+xml;base64,${c_}`,vi=(t,r)=>{const[i,c]=t.split("#");return{id:r,text:i,inputMessage:c}},u_=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客户端失败"},d_=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},f_={class:"tr-container__title"},h_={style:{flex:"1"}},p_={class:"chat-input"},m_={class:"chat-input-pills"},g_={class:"attachments-container"},x_={class:"action-buttons"},y_=_.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:$}=tw({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}=wx({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}=Vy({skillsRef:Je,customAgentProvider:re}),$e=async(Ee,Oe)=>me(Ee,Oe,xe),{welcomeIcon:Ue,roles:Ze}=Gy({props:c,messages:B,messageState:L,inputMessage:W,handleSendMessage:$e}),{showHistory:qe,handleCreateConversation:ze,handleHistorySelect:ie,handleHistoryUpdateTitle:de,handleHistoryDelete:_e}=qy({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:a_};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}=Uy(F,g,wl);zy({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=u_(c),rr=_.computed(()=>c.pillItems??Ft.pillItems),sn=_.computed(()=>c.promptItems??Ft.promptItems),At=Ft.lang,{handleScanSuccess:or,handleSessionIdInput:Ln,initialize:wr}=Xy({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(d_(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}=Fy(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",f_,_.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(Mw,{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",p_,[_.renderSlot(Ee.$slots,"suggestions",{},()=>[_.createElementVNode("div",m_,[(_.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",x_,[_.createVNode(Kw,{"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(qw,{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(n_,{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",g_,[_.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",{},()=>[_.createElementVNode("div",h_,[_.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,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(y_,[["__scopeId","data-v-635a2faf"]]);Fi.install=function(t){t.component("tiny-remoter",Fi)};exports.TinyRemoter=Fi;exports.useModel=is;
|
|
94
|
+
`,u_=btoa(c_),wl=`data:image/svg+xml;base64,${u_}`,vi=(t,r)=>{const[i,c]=t.split("#");return{id:r,text:i,inputMessage:c}},d_=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客户端失败"},f_=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},h_={class:"tr-container__title"},p_={style:{flex:"1"}},m_={class:"chat-input"},g_={class:"chat-input-pills"},x_={class:"attachments-container"},y_={class:"action-buttons"},w_=_.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(Rr.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),P=_.computed(()=>{const Ie=E?.value?.length?A.value:c.llmConfig;return Ie?!!(Ie.baseURL&&Ie.genuiUrl):!1}),{hasMultimodalSupport:T,attachments:S,onFilesSelected:D,checkCanSendAttachments:M,processAttachments:ee,cleanupAttachments:$}=nw({selectedModel:A,selectedModelId:x}),{agent:F,customAgentProvider:re,conversationState:Z,messages:B,messageState:L,inputMessage:W,abortRequest:z,senderRef:we,sendMessage:G,handleSendMessage:pe,addMessage:de,send:te,createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te}=wx({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:d});_.watch(()=>c.systemPrompt,Ie=>{re.promptManager.setStatic(Ie)}),re.isGenuiEnabled=v,re.debugStream=c.debugStream;const Je=_.toRef(c,"skills"),{processSkillMentions:ze}=Zy({skillsRef:Je,customAgentProvider:re}),Xe=async(Ie,Oe)=>pe(Ie,Oe,ze),{welcomeIcon:Ve,roles:_e}=qy({props:c,messages:B,messageState:L,inputMessage:W,handleSendMessage:Xe}),{showHistory:We,handleCreateConversation:Ze,handleHistorySelect:ye,handleHistoryUpdateTitle:ct,handleHistoryDelete:tt}=Xy({createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te,abortRequest:z,conversationState:Z,customAgentProvider:re}),Ee=()=>{if(A.value){const Ie=A.value;re.updateLLMConfig({model:Ie.model||"",baseURL:Ie.baseURL||"",genuiUrl:Ie.genuiUrl||"",apiKey:Ie.apiKey||"",providerType:Ie.providerType,useReActMode:Ie.useReActMode,llm:Ie.llm,providerOptions:Ie.providerOptions,headers:Ie.headers})}else re.updateLLMConfig(re.llmConfig)};c.llmConfigs&&_.watch(A,Ee,{immediate:!0}),_.watch(v,Ee,{immediate:!0});const ae={markdown:new Zt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":Ie=>_.h(Ed.GenuiRenderer,{...Ie,customActions:{continueChat:{execute:(Oe,nt)=>{const Ye=typeof Oe=="string"?Oe:Oe.message,Fn=`${Ye},相关参数为:${JSON.stringify(nt?.state||{})}`;de({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:l_};function J(Ie,Oe){ae[Ie]=Oe}const{installedPlugins:xe,marketPlugins:ie,pluginVisible:ge,loadMcpServerToPlugin:Fe,togglePlugin:Ft,toggleTool:ut,deletePlugin:qe,addPluginCore:Me,addPluginFromMarket:kt,addPluginFromScan:be,handleClientDisconnected:Bn,searchPlugin:$n,syncInstalledPluginTools:Xt}=Uy(F,g,wl);Vy({onToolCatalogChanged:async()=>{await F.refreshTools(),Xt()}}),ie.value=[...c.customMarketMcpServers];const jn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Ut=d_(c),nr=_.computed(()=>c.pillItems??Ut.pillItems),an=_.computed(()=>c.promptItems??Ut.promptItems),At=Ut.lang,{handleScanSuccess:rr,handleSessionIdInput:Ln,initialize:yr}=Yy({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}),xt=async Ie=>{if(await Ln(W.value)||!M())return;const nt=await ee();try{await Xe(Ie,nt),$()}catch(Ye){console.error("发送消息失败:",Ye)}},me=_.computed(()=>Kn.GeneratingStatus.includes(L.status)?At[c.locale].thinking:At[c.locale].placeholder),O=_.computed(()=>Kn.GeneratingStatus.includes(L.status)),ne=Ie=>{W.value=Ie.inputMessage};yr(),_.onMounted(async()=>{setTimeout(()=>{Ze()},100),F.onError=Oe=>{Oe&&ot(f_(Oe))};const Ie=ie.value.filter(Oe=>Oe.addState==="added"&&Oe.enabled);for(const Oe of Ie)await kt(Oe);if(c.mcpServers)for(const[Oe,nt]of Object.entries(c.mcpServers))await Fe(Oe,nt)});const{handleCustomAdd:De}=Fy(F,xe,wl);return r({agent:F,welcomeIcon:Ve,messages:B,messageState:L,roles:_e,inputMessage:W,senderRef:we,abortRequest:z,sendMessage:G,loadMcpServerToPlugin:Fe,handleClientDisconnected:Bn,addMessage:de,installedPlugins:xe,addPluginCore:Me,deletePlugin:qe,registerContentRenderer:J,async refreshPluginTools(){await F.refreshTools(),Xt()}}),(Ie,Oe)=>(_.openBlock(),_.createBlock(_.unref(Zt.TrContainer),{show:m.value,"onUpdate:show":Oe[11]||(Oe[11]=nt=>m.value=nt),fullscreen:f.value,"onUpdate:fullscreen":Oe[12]||(Oe[12]=nt=>f.value=nt),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",h_,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot(Ie.$slots,"operations",{},()=>[_.createVNode(_.unref(Zt.TrIconButton),{icon:_.unref(Rr.IconNewSession),size:"28",svgSize:"20",onClick:Oe[0]||(Oe[0]=nt=>_.unref(Ze)())},null,8,["icon"]),_.createVNode(_.unref(Zt.TrIconButton),{icon:_.unref(Rr.IconHistory),size:"28",svgSize:"20",onClick:Oe[1]||(Oe[1]=nt=>We.value=!_.unref(We))},null,8,["icon"]),_.createVNode(Dw,{onScanSuccess:_.unref(rr)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(We)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:Oe[4]||(Oe[4]=nt=>We.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(Zt.TrHistory),{class:"tr-history-demo",selected:_.unref(Z).currentId,data:_.unref(Z).conversations,showRenameControls:!0,onClose:Oe[2]||(Oe[2]=nt=>We.value=!1),onItemClick:_.unref(ye),onItemTitleChange:_.unref(ct),onItemAction:_.unref(tt)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",m_,[_.renderSlot(Ie.$slots,"suggestions",{},()=>[_.createElementVNode("div",g_,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(nr.value,nt=>(_.openBlock(),_.createBlock(_.unref(Zt.TrDropdownMenu),{key:nt.id,items:nt.menus,onItemClick:ne,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref(Zt.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(nt.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref(Zt.TrSender),{ref_key:"senderRef",ref:we,mode:"multiple",modelValue:_.unref(W),"onUpdate:modelValue":Oe[9]||(Oe[9]=nt=>_.isRef(W)?W.value=nt:null),placeholder:me.value,clearable:!!_.unref(W),loading:O.value,showWordLimit:!0,maxLength:2e4,onSubmit:xt,onCancel:_.unref(z)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",y_,[_.createVNode(Jw,{"installed-plugins":_.unref(xe),onClick:Oe[6]||(Oe[6]=nt=>ge.value=!_.unref(ge))},null,8,["installed-plugins"]),_.unref(E)&&_.unref(E).length>0?(_.openBlock(),_.createBlock(Xw,{key:0,"model-configs":_.unref(E),"selected-model-id":x.value,"onUpdate:selectedModelId":Oe[7]||(Oe[7]=nt=>x.value=nt)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),P.value?(_.openBlock(),_.createBlock(r_,{key:1,"genui-enabled":v.value,"onUpdate:genuiEnabled":Oe[8]||(Oe[8]=nt=>v.value=nt)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(T)?(_.openBlock(),_.createBlock(_.unref(Zt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(D)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(S).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",x_,[_.createVNode(_.unref(Zt.TrAttachments),{items:_.unref(S),"onUpdate:items":Oe[5]||(Oe[5]=nt=>_.isRef(S)?S.value=nt:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref(Zt.TrMcpServerPicker),{visible:_.unref(ge),"onUpdate:visible":Oe[10]||(Oe[10]=nt=>_.isRef(ge)?ge.value=nt:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(xe),marketPlugins:_.unref(ie),"market-category-options":jn.value,"installed-search-fn":_.unref($n),"market-search-fn":_.unref($n),onPluginToggle:_.unref(Ft),onPluginAdd:_.unref(kt),onPluginDelete:_.unref(qe),onToolToggle:_.unref(ut),onPluginCreate:_.unref(De)},{"header-actions":_.withCtx(()=>[_.renderSlot(Ie.$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(Zt.TrBubbleProvider),{"content-renderers":ae},{default:_.withCtx(()=>[_.unref(B).length===0?_.renderSlot(Ie.$slots,"welcome",{},()=>[_.createElementVNode("div",p_,[_.createVNode(_.unref(Zt.TrWelcome),{title:_.unref(At)[t.locale].title,description:_.unref(At)[t.locale].description,icon:_.unref(Ve)},null,8,["title","description","icon"]),_.createVNode(_.unref(Zt.TrPrompts),{items:an.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0,0):(_.openBlock(),_.createBlock(_.unref(Zt.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(B),roles:_.unref(_e),"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=tr(w_,[["__scopeId","data-v-635a2faf"]]);Fi.install=function(t){t.component("tiny-remoter",Fi)};exports.TinyRemoter=Fi;exports.useModel=is;
|