@sylphx/flow 0.2.1 → 0.2.3

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.
Files changed (102) hide show
  1. package/assets/agents/coder.md +1 -1
  2. package/assets/agents/orchestrator.md +1 -1
  3. package/assets/agents/reviewer.md +1 -1
  4. package/assets/agents/writer.md +13 -13
  5. package/assets/slash-commands/context.md +112 -0
  6. package/dist/assets/agents/coder.md +32 -0
  7. package/dist/assets/agents/orchestrator.md +36 -0
  8. package/dist/assets/agents/reviewer.md +30 -0
  9. package/dist/assets/agents/writer.md +30 -0
  10. package/dist/assets/knowledge/data/sql.md +216 -0
  11. package/dist/assets/knowledge/guides/saas-template.md +85 -0
  12. package/dist/assets/knowledge/guides/system-prompt.md +344 -0
  13. package/dist/assets/knowledge/guides/tech-stack.md +92 -0
  14. package/dist/assets/knowledge/guides/ui-ux.md +44 -0
  15. package/dist/assets/knowledge/stacks/nextjs-app.md +165 -0
  16. package/dist/assets/knowledge/stacks/node-api.md +220 -0
  17. package/dist/assets/knowledge/stacks/react-app.md +232 -0
  18. package/dist/assets/knowledge/universal/deployment.md +109 -0
  19. package/dist/assets/knowledge/universal/performance.md +121 -0
  20. package/dist/assets/knowledge/universal/security.md +79 -0
  21. package/dist/assets/knowledge/universal/testing.md +111 -0
  22. package/dist/assets/output-styles/silent.md +23 -0
  23. package/dist/assets/rules/core.md +144 -0
  24. package/dist/assets/slash-commands/commit.md +23 -0
  25. package/dist/assets/slash-commands/context.md +112 -0
  26. package/dist/assets/slash-commands/explain.md +35 -0
  27. package/dist/assets/slash-commands/mep.md +63 -0
  28. package/dist/assets/slash-commands/review.md +39 -0
  29. package/dist/assets/slash-commands/test.md +30 -0
  30. package/dist/chunk-1rptg3yg.js +4 -0
  31. package/dist/chunk-1rptg3yg.js.map +10 -0
  32. package/dist/{chunk-124wqbdb.js → chunk-4fr8q0jy.js} +3 -3
  33. package/dist/{chunk-124wqbdb.js.map → chunk-4fr8q0jy.js.map} +1 -1
  34. package/dist/{chunk-f6y5vttn.js → chunk-5szm4n3x.js} +3 -3
  35. package/dist/{chunk-f6y5vttn.js.map → chunk-5szm4n3x.js.map} +1 -1
  36. package/dist/chunk-7nht27vs.js +4 -0
  37. package/dist/{chunk-g9t3me0w.js.map → chunk-7nht27vs.js.map} +2 -2
  38. package/dist/chunk-8krxe10w.js +3 -0
  39. package/dist/{chunk-e966bjm5.js.map → chunk-8krxe10w.js.map} +2 -2
  40. package/dist/{chunk-wpe7rw5c.js → chunk-8z1sf25t.js} +3 -3
  41. package/dist/{chunk-wpe7rw5c.js.map → chunk-8z1sf25t.js.map} +1 -1
  42. package/dist/chunk-9c2nr2fz.js +25 -0
  43. package/dist/chunk-9c2nr2fz.js.map +61 -0
  44. package/dist/{chunk-4p754rhd.js → chunk-asr22mbn.js} +2 -2
  45. package/dist/{chunk-4p754rhd.js.map → chunk-asr22mbn.js.map} +2 -2
  46. package/dist/chunk-bnxtqetr.js +23 -0
  47. package/dist/chunk-bnxtqetr.js.map +11 -0
  48. package/dist/chunk-cs1s5c3g.js +54 -0
  49. package/dist/chunk-cs1s5c3g.js.map +53 -0
  50. package/dist/chunk-cv1nhr27.js +2 -0
  51. package/dist/{chunk-hshjnpm0.js.map → chunk-cv1nhr27.js.map} +1 -1
  52. package/dist/chunk-d4hj6d4t.js +6 -0
  53. package/dist/chunk-d4hj6d4t.js.map +11 -0
  54. package/dist/chunk-f06ma45b.js +15 -0
  55. package/dist/chunk-f06ma45b.js.map +16 -0
  56. package/dist/chunk-fs3f7acb.js +4 -0
  57. package/dist/chunk-fs3f7acb.js.map +12 -0
  58. package/dist/{chunk-5r4afhzp.js → chunk-gh83x9ya.js} +3 -3
  59. package/dist/{chunk-5r4afhzp.js.map → chunk-gh83x9ya.js.map} +1 -1
  60. package/dist/{chunk-qa8b725g.js → chunk-gyq335sw.js} +6 -5
  61. package/dist/{chunk-qa8b725g.js.map → chunk-gyq335sw.js.map} +1 -1
  62. package/dist/{chunk-hs3nxzyz.js → chunk-hft1735c.js} +2 -2
  63. package/dist/{chunk-hs3nxzyz.js.map → chunk-hft1735c.js.map} +2 -2
  64. package/dist/chunk-hj6r7703.js +3 -0
  65. package/dist/{chunk-78bfvh46.js.map → chunk-hj6r7703.js.map} +2 -2
  66. package/dist/chunk-hxj4eapp.js +14 -0
  67. package/dist/chunk-hxj4eapp.js.map +20 -0
  68. package/dist/chunk-jgsq3xax.js +23 -0
  69. package/dist/chunk-jgsq3xax.js.map +132 -0
  70. package/dist/{chunk-646h52kd.js → chunk-m9nt0bj3.js} +3 -3
  71. package/dist/{chunk-646h52kd.js.map → chunk-m9nt0bj3.js.map} +1 -1
  72. package/dist/{chunk-bd11hvvz.js → chunk-ndah8mn9.js} +2 -2
  73. package/dist/{chunk-bd11hvvz.js.map → chunk-ndah8mn9.js.map} +1 -1
  74. package/dist/chunk-s6g21d1g.js +27 -0
  75. package/dist/{chunk-0h7sfwq3.js.map → chunk-s6g21d1g.js.map} +4 -5
  76. package/dist/{chunk-hshjnpm0.js → chunk-sxy6vp20.js} +2 -2
  77. package/dist/chunk-sxy6vp20.js.map +9 -0
  78. package/dist/chunk-vjf57v4h.js +4 -0
  79. package/dist/chunk-vjf57v4h.js.map +10 -0
  80. package/dist/{chunk-jxny6xft.js → chunk-w2vbmr93.js} +2 -2
  81. package/dist/{chunk-jxny6xft.js.map → chunk-w2vbmr93.js.map} +1 -1
  82. package/dist/chunk-wd9qbbe5.js +5 -0
  83. package/dist/chunk-wd9qbbe5.js.map +10 -0
  84. package/dist/chunk-wnaa55wn.js +108 -0
  85. package/dist/chunk-wnaa55wn.js.map +24 -0
  86. package/dist/chunk-wrx1n6q6.js +16 -0
  87. package/dist/chunk-wrx1n6q6.js.map +16 -0
  88. package/dist/chunk-xata5rw6.js +119 -0
  89. package/dist/{chunk-878q8xdr.js.map → chunk-xata5rw6.js.map} +7 -18
  90. package/dist/chunk-z2rtyk3d.js +7 -0
  91. package/dist/{chunk-ygdr4fw7.js.map → chunk-z2rtyk3d.js.map} +2 -2
  92. package/dist/index.js +446 -482
  93. package/dist/index.js.map +301 -202
  94. package/package.json +4 -1
  95. package/dist/chunk-0h7sfwq3.js +0 -27
  96. package/dist/chunk-78bfvh46.js +0 -3
  97. package/dist/chunk-878q8xdr.js +0 -86
  98. package/dist/chunk-e966bjm5.js +0 -3
  99. package/dist/chunk-fxwaa2mg.js +0 -4
  100. package/dist/chunk-fxwaa2mg.js.map +0 -10
  101. package/dist/chunk-g9t3me0w.js +0 -4
  102. package/dist/chunk-ygdr4fw7.js +0 -7
@@ -1,86 +0,0 @@
1
- import{ra as HY,sa as zY,ua as W}from"./chunk-qa8b725g.js";import{va as HN,wa as iq,ya as rJ}from"./chunk-hshjnpm0.js";var eJ=iq((tJ,gQ)=>{(function(Q){if(typeof gQ==="object"&&typeof gQ.exports==="object"){var Y=Q(rJ,tJ);if(Y!==void 0)gQ.exports=Y}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,Y){Object.defineProperty(Y,"__esModule",{value:!0}),Y.applyEdits=Y.modify=Y.format=Y.printParseErrorCode=Y.ParseErrorCode=Y.stripComments=Y.visit=Y.getNodeValue=Y.getNodePath=Y.findNodeAtOffset=Y.findNodeAtLocation=Y.parseTree=Y.parse=Y.getLocation=Y.SyntaxKind=Y.ScanError=Y.createScanner=void 0;let J=Q("./impl/format"),X=Q("./impl/edit"),B=Q("./impl/scanner"),q=Q("./impl/parser");Y.createScanner=B.createScanner;var G;(function(F){F[F.None=0]="None",F[F.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",F[F.UnexpectedEndOfString=2]="UnexpectedEndOfString",F[F.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",F[F.InvalidUnicode=4]="InvalidUnicode",F[F.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",F[F.InvalidCharacter=6]="InvalidCharacter"})(G||(Y.ScanError=G={}));var H;(function(F){F[F.OpenBraceToken=1]="OpenBraceToken",F[F.CloseBraceToken=2]="CloseBraceToken",F[F.OpenBracketToken=3]="OpenBracketToken",F[F.CloseBracketToken=4]="CloseBracketToken",F[F.CommaToken=5]="CommaToken",F[F.ColonToken=6]="ColonToken",F[F.NullKeyword=7]="NullKeyword",F[F.TrueKeyword=8]="TrueKeyword",F[F.FalseKeyword=9]="FalseKeyword",F[F.StringLiteral=10]="StringLiteral",F[F.NumericLiteral=11]="NumericLiteral",F[F.LineCommentTrivia=12]="LineCommentTrivia",F[F.BlockCommentTrivia=13]="BlockCommentTrivia",F[F.LineBreakTrivia=14]="LineBreakTrivia",F[F.Trivia=15]="Trivia",F[F.Unknown=16]="Unknown",F[F.EOF=17]="EOF"})(H||(Y.SyntaxKind=H={})),Y.getLocation=q.getLocation,Y.parse=q.parse,Y.parseTree=q.parseTree,Y.findNodeAtLocation=q.findNodeAtLocation,Y.findNodeAtOffset=q.findNodeAtOffset,Y.getNodePath=q.getNodePath,Y.getNodeValue=q.getNodeValue,Y.visit=q.visit,Y.stripComments=q.stripComments;var U;(function(F){F[F.InvalidSymbol=1]="InvalidSymbol",F[F.InvalidNumberFormat=2]="InvalidNumberFormat",F[F.PropertyNameExpected=3]="PropertyNameExpected",F[F.ValueExpected=4]="ValueExpected",F[F.ColonExpected=5]="ColonExpected",F[F.CommaExpected=6]="CommaExpected",F[F.CloseBraceExpected=7]="CloseBraceExpected",F[F.CloseBracketExpected=8]="CloseBracketExpected",F[F.EndOfFileExpected=9]="EndOfFileExpected",F[F.InvalidCommentToken=10]="InvalidCommentToken",F[F.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",F[F.UnexpectedEndOfString=12]="UnexpectedEndOfString",F[F.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",F[F.InvalidUnicode=14]="InvalidUnicode",F[F.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",F[F.InvalidCharacter=16]="InvalidCharacter"})(U||(Y.ParseErrorCode=U={}));function z(F){switch(F){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}Y.printParseErrorCode=z;function j(F,D,L){return J.format(F,D,L)}Y.format=j;function A(F,D,L,N){return X.setProperty(F,D,L,N)}Y.modify=A;function V(F,D){let L=D.slice(0).sort((K,M)=>{let w=K.offset-M.offset;if(w===0)return K.length-M.length;return w}),N=F.length;for(let K=L.length-1;K>=0;K--){let M=L[K];if(M.offset+M.length<=N)F=X.applyEdit(F,M);else throw Error("Overlapping edit");N=M.offset}return F}Y.applyEdits=V})});var M6="vercel.ai.error",$W=Symbol.for(M6),A6,fW=class Q extends Error{constructor({name:Y,message:J,cause:X}){super(J);this[A6]=!0,this.name=Y,this.cause=X}static isInstance(Y){return Q.hasMarker(Y,M6)}static hasMarker(Y,J){let X=Symbol.for(J);return Y!=null&&typeof Y==="object"&&X in Y&&typeof Y[X]==="boolean"&&Y[X]===!0}};A6=$W;var Q1=fW,V6="AI_APICallError",D6=`vercel.ai.error.${V6}`,hW=Symbol.for(D6),w6,a0=class extends Q1{constructor({message:Q,url:Y,requestBodyValues:J,statusCode:X,responseHeaders:B,responseBody:q,cause:G,isRetryable:H=X!=null&&(X===408||X===409||X===429||X>=500),data:U}){super({name:V6,message:Q,cause:G});this[w6]=!0,this.url=Y,this.requestBodyValues=J,this.statusCode=X,this.responseHeaders=B,this.responseBody=q,this.isRetryable=H,this.data=U}static isInstance(Q){return Q1.hasMarker(Q,D6)}};w6=hW;var O6="AI_EmptyResponseBodyError",R6=`vercel.ai.error.${O6}`,mW=Symbol.for(R6),Z6,E6=class extends Q1{constructor({message:Q="Empty response body"}={}){super({name:O6,message:Q});this[Z6]=!0}static isInstance(Q){return Q1.hasMarker(Q,R6)}};Z6=mW;function P6(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}var S6="AI_InvalidArgumentError",I6=`vercel.ai.error.${S6}`,uW=Symbol.for(I6),C6,a9=class extends Q1{constructor({message:Q,cause:Y,argument:J}){super({name:S6,message:Q,cause:Y});this[C6]=!0,this.argument=J}static isInstance(Q){return Q1.hasMarker(Q,I6)}};C6=uW;var b6="AI_InvalidPromptError",T6=`vercel.ai.error.${b6}`,cW=Symbol.for(T6),_6,jQ=class extends Q1{constructor({prompt:Q,message:Y,cause:J}){super({name:b6,message:`Invalid prompt: ${Y}`,cause:J});this[_6]=!0,this.prompt=Q}static isInstance(Q){return Q1.hasMarker(Q,T6)}};_6=cW;var k6="AI_InvalidResponseDataError",v6=`vercel.ai.error.${k6}`,dW=Symbol.for(v6),x6,_9=class extends Q1{constructor({data:Q,message:Y=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:k6,message:Y});this[x6]=!0,this.data=Q}static isInstance(Q){return Q1.hasMarker(Q,v6)}};x6=dW;var g6="AI_JSONParseError",y6=`vercel.ai.error.${g6}`,lW=Symbol.for(y6),$6,v8=class extends Q1{constructor({text:Q,cause:Y}){super({name:g6,message:`JSON parsing failed: Text: ${Q}.
2
- Error message: ${P6(Y)}`,cause:Y});this[$6]=!0,this.text=Q}static isInstance(Q){return Q1.hasMarker(Q,y6)}};$6=lW;var f6="AI_LoadAPIKeyError",h6=`vercel.ai.error.${f6}`,pW=Symbol.for(h6),m6,k9=class extends Q1{constructor({message:Q}){super({name:f6,message:Q});this[m6]=!0}static isInstance(Q){return Q1.hasMarker(Q,h6)}};m6=pW;var nW="AI_LoadSettingError",iW=`vercel.ai.error.${nW}`,aW=Symbol.for(iW),sW;sW=aW;var oW="AI_NoContentGeneratedError",rW=`vercel.ai.error.${oW}`,tW=Symbol.for(rW),eW;eW=tW;var u6="AI_NoSuchModelError",c6=`vercel.ai.error.${u6}`,Q4=Symbol.for(c6),d6,M9=class extends Q1{constructor({errorName:Q=u6,modelId:Y,modelType:J,message:X=`No such ${J}: ${Y}`}){super({name:Q,message:X});this[d6]=!0,this.modelId=Y,this.modelType=J}static isInstance(Q){return Q1.hasMarker(Q,c6)}};d6=Q4;var l6="AI_TooManyEmbeddingValuesForCallError",p6=`vercel.ai.error.${l6}`,X4=Symbol.for(p6),n6,s9=class extends Q1{constructor(Q){super({name:l6,message:`Too many values for a single embedding call. The ${Q.provider} model "${Q.modelId}" can only embed up to ${Q.maxEmbeddingsPerCall} values per call, but ${Q.values.length} values were provided.`});this[n6]=!0,this.provider=Q.provider,this.modelId=Q.modelId,this.maxEmbeddingsPerCall=Q.maxEmbeddingsPerCall,this.values=Q.values}static isInstance(Q){return Q1.hasMarker(Q,p6)}};n6=X4;var i6="AI_TypeValidationError",a6=`vercel.ai.error.${i6}`,Y4=Symbol.for(a6),s6,J4=class Q extends Q1{constructor({value:Y,cause:J}){super({name:i6,message:`Type validation failed: Value: ${JSON.stringify(Y)}.
3
- Error message: ${P6(J)}`,cause:J});this[s6]=!0,this.value=Y}static isInstance(Y){return Q1.hasMarker(Y,a6)}static wrap({value:Y,cause:J}){return Q.isInstance(J)&&J.value===Y?J:new Q({value:Y,cause:J})}};s6=Y4;var A9=J4,o6="AI_UnsupportedFunctionalityError",r6=`vercel.ai.error.${o6}`,W4=Symbol.for(r6),t6,I0=class extends Q1{constructor({functionality:Q,message:Y=`'${Q}' functionality not supported.`}){super({name:o6,message:Y});this[t6]=!0,this.functionality=Q}static isInstance(Q){return Q1.hasMarker(Q,r6)}};t6=W4;class QX extends Error{constructor(Q,Y){super(Q),this.name="ParseError",this.type=Y.type,this.field=Y.field,this.value=Y.value,this.line=Y.line}}function eQ(Q){}function e6(Q){if(typeof Q=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:Y=eQ,onError:J=eQ,onRetry:X=eQ,onComment:B}=Q,q="",G=!0,H,U="",z="";function j(L){let N=G?L.replace(/^\xEF\xBB\xBF/,""):L,[K,M]=G4(`${q}${N}`);for(let w of K)A(w);q=M,G=!1}function A(L){if(L===""){F();return}if(L.startsWith(":")){B&&B(L.slice(L.startsWith(": ")?2:1));return}let N=L.indexOf(":");if(N!==-1){let K=L.slice(0,N),M=L[N+1]===" "?2:1,w=L.slice(N+M);V(K,w,L);return}V(L,"",L)}function V(L,N,K){switch(L){case"event":z=N;break;case"data":U=`${U}${N}
4
- `;break;case"id":H=N.includes("\x00")?void 0:N;break;case"retry":/^\d+$/.test(N)?X(parseInt(N,10)):J(new QX(`Invalid \`retry\` value: "${N}"`,{type:"invalid-retry",value:N,line:K}));break;default:J(new QX(`Unknown field "${L.length>20?`${L.slice(0,20)}…`:L}"`,{type:"unknown-field",field:L,value:N,line:K}));break}}function F(){U.length>0&&Y({id:H,event:z||void 0,data:U.endsWith(`
5
- `)?U.slice(0,-1):U}),H=void 0,U="",z=""}function D(L={}){q&&L.consume&&A(q),G=!0,H=void 0,U="",z="",q=""}return{feed:j,reset:D}}function G4(Q){let Y=[],J="",X=0;for(;X<Q.length;){let B=Q.indexOf("\r",X),q=Q.indexOf(`
6
- `,X),G=-1;if(B!==-1&&q!==-1?G=Math.min(B,q):B!==-1?B===Q.length-1?G=-1:G=B:q!==-1&&(G=q),G===-1){J=Q.slice(X);break}else{let H=Q.slice(X,G);Y.push(H),X=G+1,Q[X-1]==="\r"&&Q[X]===`
7
- `&&X++}}return[Y,J]}class XX extends TransformStream{constructor({onError:Q,onRetry:Y,onComment:J}={}){let X;super({start(B){X=e6({onEvent:(q)=>{B.enqueue(q)},onError(q){Q==="terminate"?B.error(q):typeof Q=="function"&&Q(q)},onRetry:Y,onComment:J})},transform(B){X.feed(B)}})}}var C0;(function(Q){Q.assertEqual=(B)=>{};function Y(B){}Q.assertIs=Y;function J(B){throw Error()}Q.assertNever=J,Q.arrayToEnum=(B)=>{let q={};for(let G of B)q[G]=G;return q},Q.getValidEnumValues=(B)=>{let q=Q.objectKeys(B).filter((H)=>typeof B[B[H]]!=="number"),G={};for(let H of q)G[H]=B[H];return Q.objectValues(G)},Q.objectValues=(B)=>{return Q.objectKeys(B).map(function(q){return B[q]})},Q.objectKeys=typeof Object.keys==="function"?(B)=>Object.keys(B):(B)=>{let q=[];for(let G in B)if(Object.prototype.hasOwnProperty.call(B,G))q.push(G);return q},Q.find=(B,q)=>{for(let G of B)if(q(G))return G;return},Q.isInteger=typeof Number.isInteger==="function"?(B)=>Number.isInteger(B):(B)=>typeof B==="number"&&Number.isFinite(B)&&Math.floor(B)===B;function X(B,q=" | "){return B.map((G)=>typeof G==="string"?`'${G}'`:G).join(q)}Q.joinValues=X,Q.jsonStringifyReplacer=(B,q)=>{if(typeof q==="bigint")return q.toString();return q}})(C0||(C0={}));var QY;(function(Q){Q.mergeShapes=(Y,J)=>{return{...Y,...J}}})(QY||(QY={}));var Y0=C0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J9=(Q)=>{switch(typeof Q){case"undefined":return Y0.undefined;case"string":return Y0.string;case"number":return Number.isNaN(Q)?Y0.nan:Y0.number;case"boolean":return Y0.boolean;case"function":return Y0.function;case"bigint":return Y0.bigint;case"symbol":return Y0.symbol;case"object":if(Array.isArray(Q))return Y0.array;if(Q===null)return Y0.null;if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return Y0.promise;if(typeof Map<"u"&&Q instanceof Map)return Y0.map;if(typeof Set<"u"&&Q instanceof Set)return Y0.set;if(typeof Date<"u"&&Q instanceof Date)return Y0.date;return Y0.object;default:return Y0.unknown}};var s=C0.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class E1 extends Error{get errors(){return this.issues}constructor(Q){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let Y=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,Y);else this.__proto__=Y;this.name="ZodError",this.issues=Q}format(Q){let Y=Q||function(B){return B.message},J={_errors:[]},X=(B)=>{for(let q of B.issues)if(q.code==="invalid_union")q.unionErrors.map(X);else if(q.code==="invalid_return_type")X(q.returnTypeError);else if(q.code==="invalid_arguments")X(q.argumentsError);else if(q.path.length===0)J._errors.push(Y(q));else{let G=J,H=0;while(H<q.path.length){let U=q.path[H];if(H!==q.path.length-1)G[U]=G[U]||{_errors:[]};else G[U]=G[U]||{_errors:[]},G[U]._errors.push(Y(q));G=G[U],H++}}};return X(this),J}static assert(Q){if(!(Q instanceof E1))throw Error(`Not a ZodError: ${Q}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,C0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(Q=(Y)=>Y.message){let Y=Object.create(null),J=[];for(let X of this.issues)if(X.path.length>0){let B=X.path[0];Y[B]=Y[B]||[],Y[B].push(Q(X))}else J.push(Q(X));return{formErrors:J,fieldErrors:Y}}get formErrors(){return this.flatten()}}E1.create=(Q)=>{return new E1(Q)};var B4=(Q,Y)=>{let J;switch(Q.code){case s.invalid_type:if(Q.received===Y0.undefined)J="Required";else J=`Expected ${Q.expected}, received ${Q.received}`;break;case s.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify(Q.expected,C0.jsonStringifyReplacer)}`;break;case s.unrecognized_keys:J=`Unrecognized key(s) in object: ${C0.joinValues(Q.keys,", ")}`;break;case s.invalid_union:J="Invalid input";break;case s.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${C0.joinValues(Q.options)}`;break;case s.invalid_enum_value:J=`Invalid enum value. Expected ${C0.joinValues(Q.options)}, received '${Q.received}'`;break;case s.invalid_arguments:J="Invalid function arguments";break;case s.invalid_return_type:J="Invalid function return type";break;case s.invalid_date:J="Invalid date";break;case s.invalid_string:if(typeof Q.validation==="object")if("includes"in Q.validation){if(J=`Invalid input: must include "${Q.validation.includes}"`,typeof Q.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${Q.validation.position}`}else if("startsWith"in Q.validation)J=`Invalid input: must start with "${Q.validation.startsWith}"`;else if("endsWith"in Q.validation)J=`Invalid input: must end with "${Q.validation.endsWith}"`;else C0.assertNever(Q.validation);else if(Q.validation!=="regex")J=`Invalid ${Q.validation}`;else J="Invalid";break;case s.too_small:if(Q.type==="array")J=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at least":"more than"} ${Q.minimum} element(s)`;else if(Q.type==="string")J=`String must contain ${Q.exact?"exactly":Q.inclusive?"at least":"over"} ${Q.minimum} character(s)`;else if(Q.type==="number")J=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="bigint")J=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="date")J=`Date must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Q.minimum))}`;else J="Invalid input";break;case s.too_big:if(Q.type==="array")J=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at most":"less than"} ${Q.maximum} element(s)`;else if(Q.type==="string")J=`String must contain ${Q.exact?"exactly":Q.inclusive?"at most":"under"} ${Q.maximum} character(s)`;else if(Q.type==="number")J=`Number must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="bigint")J=`BigInt must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="date")J=`Date must be ${Q.exact?"exactly":Q.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Q.maximum))}`;else J="Invalid input";break;case s.custom:J="Invalid input";break;case s.invalid_intersection_types:J="Intersection results could not be merged";break;case s.not_multiple_of:J=`Number must be a multiple of ${Q.multipleOf}`;break;case s.not_finite:J="Number must be finite";break;default:J=Y.defaultError,C0.assertNever(Q)}return{message:J}},V9=B4;var q4=V9;function x8(){return q4}var KQ=(Q)=>{let{data:Y,path:J,errorMaps:X,issueData:B}=Q,q=[...J,...B.path||[]],G={...B,path:q};if(B.message!==void 0)return{...B,path:q,message:B.message};let H="",U=X.filter((z)=>!!z).slice().reverse();for(let z of U)H=z(G,{data:Y,defaultError:H}).message;return{...B,path:q,message:H}};function W0(Q,Y){let J=x8(),X=KQ({issueData:Y,data:Q.data,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,J,J===V9?void 0:V9].filter((B)=>!!B)});Q.common.issues.push(X)}class L1{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(Q,Y){let J=[];for(let X of Y){if(X.status==="aborted")return N0;if(X.status==="dirty")Q.dirty();J.push(X.value)}return{status:Q.value,value:J}}static async mergeObjectAsync(Q,Y){let J=[];for(let X of Y){let B=await X.key,q=await X.value;J.push({key:B,value:q})}return L1.mergeObjectSync(Q,J)}static mergeObjectSync(Q,Y){let J={};for(let X of Y){let{key:B,value:q}=X;if(B.status==="aborted")return N0;if(q.status==="aborted")return N0;if(B.status==="dirty")Q.dirty();if(q.status==="dirty")Q.dirty();if(B.value!=="__proto__"&&(typeof q.value<"u"||X.alwaysSet))J[B.value]=q.value}return{status:Q.value,value:J}}}var N0=Object.freeze({status:"aborted"}),o9=(Q)=>({status:"dirty",value:Q}),K1=(Q)=>({status:"valid",value:Q}),YX=(Q)=>Q.status==="aborted",JX=(Q)=>Q.status==="dirty",v9=(Q)=>Q.status==="valid",g8=(Q)=>typeof Promise<"u"&&Q instanceof Promise;var U0;(function(Q){Q.errToObj=(Y)=>typeof Y==="string"?{message:Y}:Y||{},Q.toString=(Y)=>typeof Y==="string"?Y:Y?.message})(U0||(U0={}));class x1{constructor(Q,Y,J,X){this._cachedPath=[],this.parent=Q,this.data=Y,this._path=J,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var XY=(Q,Y)=>{if(v9(Y))return{success:!0,data:Y.value};else{if(!Q.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new E1(Q.common.issues);return this._error=J,this._error}}}};function w0(Q){if(!Q)return{};let{errorMap:Y,invalid_type_error:J,required_error:X,description:B}=Q;if(Y&&(J||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Y)return{errorMap:Y,description:B};return{errorMap:(G,H)=>{let{message:U}=Q;if(G.code==="invalid_enum_value")return{message:U??H.defaultError};if(typeof H.data>"u")return{message:U??X??H.defaultError};if(G.code!=="invalid_type")return{message:H.defaultError};return{message:U??J??H.defaultError}},description:B}}class S0{get description(){return this._def.description}_getType(Q){return J9(Q.data)}_getOrReturnCtx(Q,Y){return Y||{common:Q.parent.common,data:Q.data,parsedType:J9(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}_processInputParams(Q){return{status:new L1,ctx:{common:Q.parent.common,data:Q.data,parsedType:J9(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}}_parseSync(Q){let Y=this._parse(Q);if(g8(Y))throw Error("Synchronous parse encountered promise.");return Y}_parseAsync(Q){let Y=this._parse(Q);return Promise.resolve(Y)}parse(Q,Y){let J=this.safeParse(Q,Y);if(J.success)return J.data;throw J.error}safeParse(Q,Y){let J={common:{issues:[],async:Y?.async??!1,contextualErrorMap:Y?.errorMap},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:J9(Q)},X=this._parseSync({data:Q,path:J.path,parent:J});return XY(J,X)}"~validate"(Q){let Y={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:J9(Q)};if(!this["~standard"].async)try{let J=this._parseSync({data:Q,path:[],parent:Y});return v9(J)?{value:J.value}:{issues:Y.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;Y.common={issues:[],async:!0}}return this._parseAsync({data:Q,path:[],parent:Y}).then((J)=>v9(J)?{value:J.value}:{issues:Y.common.issues})}async parseAsync(Q,Y){let J=await this.safeParseAsync(Q,Y);if(J.success)return J.data;throw J.error}async safeParseAsync(Q,Y){let J={common:{issues:[],contextualErrorMap:Y?.errorMap,async:!0},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:J9(Q)},X=this._parse({data:Q,path:J.path,parent:J}),B=await(g8(X)?X:Promise.resolve(X));return XY(J,B)}refine(Q,Y){let J=(X)=>{if(typeof Y==="string"||typeof Y>"u")return{message:Y};else if(typeof Y==="function")return Y(X);else return Y};return this._refinement((X,B)=>{let q=Q(X),G=()=>B.addIssue({code:s.custom,...J(X)});if(typeof Promise<"u"&&q instanceof Promise)return q.then((H)=>{if(!H)return G(),!1;else return!0});if(!q)return G(),!1;else return!0})}refinement(Q,Y){return this._refinement((J,X)=>{if(!Q(J))return X.addIssue(typeof Y==="function"?Y(J,X):Y),!1;else return!0})}_refinement(Q){return new n1({schema:this,typeName:e.ZodEffects,effect:{type:"refinement",refinement:Q}})}superRefine(Q){return this._refinement(Q)}constructor(Q){this.spa=this.safeParseAsync,this._def=Q,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(Y)=>this["~validate"](Y)}}optional(){return p1.create(this,this._def)}nullable(){return D9.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return l1.create(this)}promise(){return X8.create(this,this._def)}or(Q){return m8.create([this,Q],this._def)}and(Q){return u8.create(this,Q,this._def)}transform(Q){return new n1({...w0(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:Q}})}default(Q){let Y=typeof Q==="function"?Q:()=>Q;return new p8({...w0(this._def),innerType:this,defaultValue:Y,typeName:e.ZodDefault})}brand(){return new qX({typeName:e.ZodBranded,type:this,...w0(this._def)})}catch(Q){let Y=typeof Q==="function"?Q:()=>Q;return new n8({...w0(this._def),innerType:this,catchValue:Y,typeName:e.ZodCatch})}describe(Q){return new this.constructor({...this._def,description:Q})}pipe(Q){return ZQ.create(this,Q)}readonly(){return i8.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var H4=/^c[^\s-]{8,}$/i,z4=/^[0-9a-z]+$/,U4=/^[0-9A-HJKMNP-TV-Z]{26}$/i,L4=/^[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}$/i,F4=/^[a-z0-9_-]{21}$/i,N4=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,j4=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,K4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,M4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",WX,A4=/^(?:(?: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])$/,V4=/^(?:(?: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])$/,D4=/^(([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]))$/,w4=/^(([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])$/,O4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,R4=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,YY="((\\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])))",Z4=new RegExp(`^${YY}$`);function JY(Q){let Y="[0-5]\\d";if(Q.precision)Y=`${Y}\\.\\d{${Q.precision}}`;else if(Q.precision==null)Y=`${Y}(\\.\\d+)?`;let J=Q.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${Y})${J}`}function E4(Q){return new RegExp(`^${JY(Q)}$`)}function P4(Q){let Y=`${YY}T${JY(Q)}`,J=[];if(J.push(Q.local?"Z?":"Z"),Q.offset)J.push("([+-]\\d{2}:?\\d{2})");return Y=`${Y}(${J.join("|")})`,new RegExp(`^${Y}$`)}function S4(Q,Y){if((Y==="v4"||!Y)&&A4.test(Q))return!0;if((Y==="v6"||!Y)&&D4.test(Q))return!0;return!1}function I4(Q,Y){if(!N4.test(Q))return!1;try{let[J]=Q.split(".");if(!J)return!1;let X=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),B=JSON.parse(atob(X));if(typeof B!=="object"||B===null)return!1;if("typ"in B&&B?.typ!=="JWT")return!1;if(!B.alg)return!1;if(Y&&B.alg!==Y)return!1;return!0}catch{return!1}}function C4(Q,Y){if((Y==="v4"||!Y)&&V4.test(Q))return!0;if((Y==="v6"||!Y)&&w4.test(Q))return!0;return!1}class G9 extends S0{_parse(Q){if(this._def.coerce)Q.data=String(Q.data);if(this._getType(Q)!==Y0.string){let B=this._getOrReturnCtx(Q);return W0(B,{code:s.invalid_type,expected:Y0.string,received:B.parsedType}),N0}let J=new L1,X=void 0;for(let B of this._def.checks)if(B.kind==="min"){if(Q.data.length<B.value)X=this._getOrReturnCtx(Q,X),W0(X,{code:s.too_small,minimum:B.value,type:"string",inclusive:!0,exact:!1,message:B.message}),J.dirty()}else if(B.kind==="max"){if(Q.data.length>B.value)X=this._getOrReturnCtx(Q,X),W0(X,{code:s.too_big,maximum:B.value,type:"string",inclusive:!0,exact:!1,message:B.message}),J.dirty()}else if(B.kind==="length"){let q=Q.data.length>B.value,G=Q.data.length<B.value;if(q||G){if(X=this._getOrReturnCtx(Q,X),q)W0(X,{code:s.too_big,maximum:B.value,type:"string",inclusive:!0,exact:!0,message:B.message});else if(G)W0(X,{code:s.too_small,minimum:B.value,type:"string",inclusive:!0,exact:!0,message:B.message});J.dirty()}}else if(B.kind==="email"){if(!K4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"email",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="emoji"){if(!WX)WX=new RegExp(M4,"u");if(!WX.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"emoji",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="uuid"){if(!L4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"uuid",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="nanoid"){if(!F4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"nanoid",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="cuid"){if(!H4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"cuid",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="cuid2"){if(!z4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"cuid2",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="ulid"){if(!U4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"ulid",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="url")try{new URL(Q.data)}catch{X=this._getOrReturnCtx(Q,X),W0(X,{validation:"url",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="regex"){if(B.regex.lastIndex=0,!B.regex.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"regex",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="trim")Q.data=Q.data.trim();else if(B.kind==="includes"){if(!Q.data.includes(B.value,B.position))X=this._getOrReturnCtx(Q,X),W0(X,{code:s.invalid_string,validation:{includes:B.value,position:B.position},message:B.message}),J.dirty()}else if(B.kind==="toLowerCase")Q.data=Q.data.toLowerCase();else if(B.kind==="toUpperCase")Q.data=Q.data.toUpperCase();else if(B.kind==="startsWith"){if(!Q.data.startsWith(B.value))X=this._getOrReturnCtx(Q,X),W0(X,{code:s.invalid_string,validation:{startsWith:B.value},message:B.message}),J.dirty()}else if(B.kind==="endsWith"){if(!Q.data.endsWith(B.value))X=this._getOrReturnCtx(Q,X),W0(X,{code:s.invalid_string,validation:{endsWith:B.value},message:B.message}),J.dirty()}else if(B.kind==="datetime"){if(!P4(B).test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{code:s.invalid_string,validation:"datetime",message:B.message}),J.dirty()}else if(B.kind==="date"){if(!Z4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{code:s.invalid_string,validation:"date",message:B.message}),J.dirty()}else if(B.kind==="time"){if(!E4(B).test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{code:s.invalid_string,validation:"time",message:B.message}),J.dirty()}else if(B.kind==="duration"){if(!j4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"duration",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="ip"){if(!S4(Q.data,B.version))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"ip",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="jwt"){if(!I4(Q.data,B.alg))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"jwt",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="cidr"){if(!C4(Q.data,B.version))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"cidr",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="base64"){if(!O4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"base64",code:s.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="base64url"){if(!R4.test(Q.data))X=this._getOrReturnCtx(Q,X),W0(X,{validation:"base64url",code:s.invalid_string,message:B.message}),J.dirty()}else C0.assertNever(B);return{status:J.value,value:Q.data}}_regex(Q,Y,J){return this.refinement((X)=>Q.test(X),{validation:Y,code:s.invalid_string,...U0.errToObj(J)})}_addCheck(Q){return new G9({...this._def,checks:[...this._def.checks,Q]})}email(Q){return this._addCheck({kind:"email",...U0.errToObj(Q)})}url(Q){return this._addCheck({kind:"url",...U0.errToObj(Q)})}emoji(Q){return this._addCheck({kind:"emoji",...U0.errToObj(Q)})}uuid(Q){return this._addCheck({kind:"uuid",...U0.errToObj(Q)})}nanoid(Q){return this._addCheck({kind:"nanoid",...U0.errToObj(Q)})}cuid(Q){return this._addCheck({kind:"cuid",...U0.errToObj(Q)})}cuid2(Q){return this._addCheck({kind:"cuid2",...U0.errToObj(Q)})}ulid(Q){return this._addCheck({kind:"ulid",...U0.errToObj(Q)})}base64(Q){return this._addCheck({kind:"base64",...U0.errToObj(Q)})}base64url(Q){return this._addCheck({kind:"base64url",...U0.errToObj(Q)})}jwt(Q){return this._addCheck({kind:"jwt",...U0.errToObj(Q)})}ip(Q){return this._addCheck({kind:"ip",...U0.errToObj(Q)})}cidr(Q){return this._addCheck({kind:"cidr",...U0.errToObj(Q)})}datetime(Q){if(typeof Q==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:Q});return this._addCheck({kind:"datetime",precision:typeof Q?.precision>"u"?null:Q?.precision,offset:Q?.offset??!1,local:Q?.local??!1,...U0.errToObj(Q?.message)})}date(Q){return this._addCheck({kind:"date",message:Q})}time(Q){if(typeof Q==="string")return this._addCheck({kind:"time",precision:null,message:Q});return this._addCheck({kind:"time",precision:typeof Q?.precision>"u"?null:Q?.precision,...U0.errToObj(Q?.message)})}duration(Q){return this._addCheck({kind:"duration",...U0.errToObj(Q)})}regex(Q,Y){return this._addCheck({kind:"regex",regex:Q,...U0.errToObj(Y)})}includes(Q,Y){return this._addCheck({kind:"includes",value:Q,position:Y?.position,...U0.errToObj(Y?.message)})}startsWith(Q,Y){return this._addCheck({kind:"startsWith",value:Q,...U0.errToObj(Y)})}endsWith(Q,Y){return this._addCheck({kind:"endsWith",value:Q,...U0.errToObj(Y)})}min(Q,Y){return this._addCheck({kind:"min",value:Q,...U0.errToObj(Y)})}max(Q,Y){return this._addCheck({kind:"max",value:Q,...U0.errToObj(Y)})}length(Q,Y){return this._addCheck({kind:"length",value:Q,...U0.errToObj(Y)})}nonempty(Q){return this.min(1,U0.errToObj(Q))}trim(){return new G9({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G9({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G9({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((Q)=>Q.kind==="datetime")}get isDate(){return!!this._def.checks.find((Q)=>Q.kind==="date")}get isTime(){return!!this._def.checks.find((Q)=>Q.kind==="time")}get isDuration(){return!!this._def.checks.find((Q)=>Q.kind==="duration")}get isEmail(){return!!this._def.checks.find((Q)=>Q.kind==="email")}get isURL(){return!!this._def.checks.find((Q)=>Q.kind==="url")}get isEmoji(){return!!this._def.checks.find((Q)=>Q.kind==="emoji")}get isUUID(){return!!this._def.checks.find((Q)=>Q.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((Q)=>Q.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((Q)=>Q.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((Q)=>Q.kind==="cuid2")}get isULID(){return!!this._def.checks.find((Q)=>Q.kind==="ulid")}get isIP(){return!!this._def.checks.find((Q)=>Q.kind==="ip")}get isCIDR(){return!!this._def.checks.find((Q)=>Q.kind==="cidr")}get isBase64(){return!!this._def.checks.find((Q)=>Q.kind==="base64")}get isBase64url(){return!!this._def.checks.find((Q)=>Q.kind==="base64url")}get minLength(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxLength(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q}}G9.create=(Q)=>{return new G9({checks:[],typeName:e.ZodString,coerce:Q?.coerce??!1,...w0(Q)})};function b4(Q,Y){let J=(Q.toString().split(".")[1]||"").length,X=(Y.toString().split(".")[1]||"").length,B=J>X?J:X,q=Number.parseInt(Q.toFixed(B).replace(".","")),G=Number.parseInt(Y.toFixed(B).replace(".",""));return q%G/10**B}class t9 extends S0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(Q){if(this._def.coerce)Q.data=Number(Q.data);if(this._getType(Q)!==Y0.number){let B=this._getOrReturnCtx(Q);return W0(B,{code:s.invalid_type,expected:Y0.number,received:B.parsedType}),N0}let J=void 0,X=new L1;for(let B of this._def.checks)if(B.kind==="int"){if(!C0.isInteger(Q.data))J=this._getOrReturnCtx(Q,J),W0(J,{code:s.invalid_type,expected:"integer",received:"float",message:B.message}),X.dirty()}else if(B.kind==="min"){if(B.inclusive?Q.data<B.value:Q.data<=B.value)J=this._getOrReturnCtx(Q,J),W0(J,{code:s.too_small,minimum:B.value,type:"number",inclusive:B.inclusive,exact:!1,message:B.message}),X.dirty()}else if(B.kind==="max"){if(B.inclusive?Q.data>B.value:Q.data>=B.value)J=this._getOrReturnCtx(Q,J),W0(J,{code:s.too_big,maximum:B.value,type:"number",inclusive:B.inclusive,exact:!1,message:B.message}),X.dirty()}else if(B.kind==="multipleOf"){if(b4(Q.data,B.value)!==0)J=this._getOrReturnCtx(Q,J),W0(J,{code:s.not_multiple_of,multipleOf:B.value,message:B.message}),X.dirty()}else if(B.kind==="finite"){if(!Number.isFinite(Q.data))J=this._getOrReturnCtx(Q,J),W0(J,{code:s.not_finite,message:B.message}),X.dirty()}else C0.assertNever(B);return{status:X.value,value:Q.data}}gte(Q,Y){return this.setLimit("min",Q,!0,U0.toString(Y))}gt(Q,Y){return this.setLimit("min",Q,!1,U0.toString(Y))}lte(Q,Y){return this.setLimit("max",Q,!0,U0.toString(Y))}lt(Q,Y){return this.setLimit("max",Q,!1,U0.toString(Y))}setLimit(Q,Y,J,X){return new t9({...this._def,checks:[...this._def.checks,{kind:Q,value:Y,inclusive:J,message:U0.toString(X)}]})}_addCheck(Q){return new t9({...this._def,checks:[...this._def.checks,Q]})}int(Q){return this._addCheck({kind:"int",message:U0.toString(Q)})}positive(Q){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U0.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U0.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U0.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U0.toString(Q)})}multipleOf(Q,Y){return this._addCheck({kind:"multipleOf",value:Q,message:U0.toString(Y)})}finite(Q){return this._addCheck({kind:"finite",message:U0.toString(Q)})}safe(Q){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U0.toString(Q)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U0.toString(Q)})}get minValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q}get isInt(){return!!this._def.checks.find((Q)=>Q.kind==="int"||Q.kind==="multipleOf"&&C0.isInteger(Q.value))}get isFinite(){let Q=null,Y=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(Y===null||J.value>Y)Y=J.value}else if(J.kind==="max"){if(Q===null||J.value<Q)Q=J.value}return Number.isFinite(Y)&&Number.isFinite(Q)}}t9.create=(Q)=>{return new t9({checks:[],typeName:e.ZodNumber,coerce:Q?.coerce||!1,...w0(Q)})};class e9 extends S0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(Q){if(this._def.coerce)try{Q.data=BigInt(Q.data)}catch{return this._getInvalidInput(Q)}if(this._getType(Q)!==Y0.bigint)return this._getInvalidInput(Q);let J=void 0,X=new L1;for(let B of this._def.checks)if(B.kind==="min"){if(B.inclusive?Q.data<B.value:Q.data<=B.value)J=this._getOrReturnCtx(Q,J),W0(J,{code:s.too_small,type:"bigint",minimum:B.value,inclusive:B.inclusive,message:B.message}),X.dirty()}else if(B.kind==="max"){if(B.inclusive?Q.data>B.value:Q.data>=B.value)J=this._getOrReturnCtx(Q,J),W0(J,{code:s.too_big,type:"bigint",maximum:B.value,inclusive:B.inclusive,message:B.message}),X.dirty()}else if(B.kind==="multipleOf"){if(Q.data%B.value!==BigInt(0))J=this._getOrReturnCtx(Q,J),W0(J,{code:s.not_multiple_of,multipleOf:B.value,message:B.message}),X.dirty()}else C0.assertNever(B);return{status:X.value,value:Q.data}}_getInvalidInput(Q){let Y=this._getOrReturnCtx(Q);return W0(Y,{code:s.invalid_type,expected:Y0.bigint,received:Y.parsedType}),N0}gte(Q,Y){return this.setLimit("min",Q,!0,U0.toString(Y))}gt(Q,Y){return this.setLimit("min",Q,!1,U0.toString(Y))}lte(Q,Y){return this.setLimit("max",Q,!0,U0.toString(Y))}lt(Q,Y){return this.setLimit("max",Q,!1,U0.toString(Y))}setLimit(Q,Y,J,X){return new e9({...this._def,checks:[...this._def.checks,{kind:Q,value:Y,inclusive:J,message:U0.toString(X)}]})}_addCheck(Q){return new e9({...this._def,checks:[...this._def.checks,Q]})}positive(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U0.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U0.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U0.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U0.toString(Q)})}multipleOf(Q,Y){return this._addCheck({kind:"multipleOf",value:Q,message:U0.toString(Y)})}get minValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q}}e9.create=(Q)=>{return new e9({checks:[],typeName:e.ZodBigInt,coerce:Q?.coerce??!1,...w0(Q)})};class MQ extends S0{_parse(Q){if(this._def.coerce)Q.data=Boolean(Q.data);if(this._getType(Q)!==Y0.boolean){let J=this._getOrReturnCtx(Q);return W0(J,{code:s.invalid_type,expected:Y0.boolean,received:J.parsedType}),N0}return K1(Q.data)}}MQ.create=(Q)=>{return new MQ({typeName:e.ZodBoolean,coerce:Q?.coerce||!1,...w0(Q)})};class $8 extends S0{_parse(Q){if(this._def.coerce)Q.data=new Date(Q.data);if(this._getType(Q)!==Y0.date){let B=this._getOrReturnCtx(Q);return W0(B,{code:s.invalid_type,expected:Y0.date,received:B.parsedType}),N0}if(Number.isNaN(Q.data.getTime())){let B=this._getOrReturnCtx(Q);return W0(B,{code:s.invalid_date}),N0}let J=new L1,X=void 0;for(let B of this._def.checks)if(B.kind==="min"){if(Q.data.getTime()<B.value)X=this._getOrReturnCtx(Q,X),W0(X,{code:s.too_small,message:B.message,inclusive:!0,exact:!1,minimum:B.value,type:"date"}),J.dirty()}else if(B.kind==="max"){if(Q.data.getTime()>B.value)X=this._getOrReturnCtx(Q,X),W0(X,{code:s.too_big,message:B.message,inclusive:!0,exact:!1,maximum:B.value,type:"date"}),J.dirty()}else C0.assertNever(B);return{status:J.value,value:new Date(Q.data.getTime())}}_addCheck(Q){return new $8({...this._def,checks:[...this._def.checks,Q]})}min(Q,Y){return this._addCheck({kind:"min",value:Q.getTime(),message:U0.toString(Y)})}max(Q,Y){return this._addCheck({kind:"max",value:Q.getTime(),message:U0.toString(Y)})}get minDate(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q!=null?new Date(Q):null}get maxDate(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q!=null?new Date(Q):null}}$8.create=(Q)=>{return new $8({checks:[],coerce:Q?.coerce||!1,typeName:e.ZodDate,...w0(Q)})};class AQ extends S0{_parse(Q){if(this._getType(Q)!==Y0.symbol){let J=this._getOrReturnCtx(Q);return W0(J,{code:s.invalid_type,expected:Y0.symbol,received:J.parsedType}),N0}return K1(Q.data)}}AQ.create=(Q)=>{return new AQ({typeName:e.ZodSymbol,...w0(Q)})};class f8 extends S0{_parse(Q){if(this._getType(Q)!==Y0.undefined){let J=this._getOrReturnCtx(Q);return W0(J,{code:s.invalid_type,expected:Y0.undefined,received:J.parsedType}),N0}return K1(Q.data)}}f8.create=(Q)=>{return new f8({typeName:e.ZodUndefined,...w0(Q)})};class h8 extends S0{_parse(Q){if(this._getType(Q)!==Y0.null){let J=this._getOrReturnCtx(Q);return W0(J,{code:s.invalid_type,expected:Y0.null,received:J.parsedType}),N0}return K1(Q.data)}}h8.create=(Q)=>{return new h8({typeName:e.ZodNull,...w0(Q)})};class VQ extends S0{constructor(){super(...arguments);this._any=!0}_parse(Q){return K1(Q.data)}}VQ.create=(Q)=>{return new VQ({typeName:e.ZodAny,...w0(Q)})};class x9 extends S0{constructor(){super(...arguments);this._unknown=!0}_parse(Q){return K1(Q.data)}}x9.create=(Q)=>{return new x9({typeName:e.ZodUnknown,...w0(Q)})};class B9 extends S0{_parse(Q){let Y=this._getOrReturnCtx(Q);return W0(Y,{code:s.invalid_type,expected:Y0.never,received:Y.parsedType}),N0}}B9.create=(Q)=>{return new B9({typeName:e.ZodNever,...w0(Q)})};class DQ extends S0{_parse(Q){if(this._getType(Q)!==Y0.undefined){let J=this._getOrReturnCtx(Q);return W0(J,{code:s.invalid_type,expected:Y0.void,received:J.parsedType}),N0}return K1(Q.data)}}DQ.create=(Q)=>{return new DQ({typeName:e.ZodVoid,...w0(Q)})};class l1 extends S0{_parse(Q){let{ctx:Y,status:J}=this._processInputParams(Q),X=this._def;if(Y.parsedType!==Y0.array)return W0(Y,{code:s.invalid_type,expected:Y0.array,received:Y.parsedType}),N0;if(X.exactLength!==null){let q=Y.data.length>X.exactLength.value,G=Y.data.length<X.exactLength.value;if(q||G)W0(Y,{code:q?s.too_big:s.too_small,minimum:G?X.exactLength.value:void 0,maximum:q?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),J.dirty()}if(X.minLength!==null){if(Y.data.length<X.minLength.value)W0(Y,{code:s.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),J.dirty()}if(X.maxLength!==null){if(Y.data.length>X.maxLength.value)W0(Y,{code:s.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),J.dirty()}if(Y.common.async)return Promise.all([...Y.data].map((q,G)=>{return X.type._parseAsync(new x1(Y,q,Y.path,G))})).then((q)=>{return L1.mergeArray(J,q)});let B=[...Y.data].map((q,G)=>{return X.type._parseSync(new x1(Y,q,Y.path,G))});return L1.mergeArray(J,B)}get element(){return this._def.type}min(Q,Y){return new l1({...this._def,minLength:{value:Q,message:U0.toString(Y)}})}max(Q,Y){return new l1({...this._def,maxLength:{value:Q,message:U0.toString(Y)}})}length(Q,Y){return new l1({...this._def,exactLength:{value:Q,message:U0.toString(Y)}})}nonempty(Q){return this.min(1,Q)}}l1.create=(Q,Y)=>{return new l1({type:Q,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...w0(Y)})};function r9(Q){if(Q instanceof X1){let Y={};for(let J in Q.shape){let X=Q.shape[J];Y[J]=p1.create(r9(X))}return new X1({...Q._def,shape:()=>Y})}else if(Q instanceof l1)return new l1({...Q._def,type:r9(Q.element)});else if(Q instanceof p1)return p1.create(r9(Q.unwrap()));else if(Q instanceof D9)return D9.create(r9(Q.unwrap()));else if(Q instanceof q9)return q9.create(Q.items.map((Y)=>r9(Y)));else return Q}class X1 extends S0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let Q=this._def.shape(),Y=C0.objectKeys(Q);return this._cached={shape:Q,keys:Y},this._cached}_parse(Q){if(this._getType(Q)!==Y0.object){let U=this._getOrReturnCtx(Q);return W0(U,{code:s.invalid_type,expected:Y0.object,received:U.parsedType}),N0}let{status:J,ctx:X}=this._processInputParams(Q),{shape:B,keys:q}=this._getCached(),G=[];if(!(this._def.catchall instanceof B9&&this._def.unknownKeys==="strip")){for(let U in X.data)if(!q.includes(U))G.push(U)}let H=[];for(let U of q){let z=B[U],j=X.data[U];H.push({key:{status:"valid",value:U},value:z._parse(new x1(X,j,X.path,U)),alwaysSet:U in X.data})}if(this._def.catchall instanceof B9){let U=this._def.unknownKeys;if(U==="passthrough")for(let z of G)H.push({key:{status:"valid",value:z},value:{status:"valid",value:X.data[z]}});else if(U==="strict"){if(G.length>0)W0(X,{code:s.unrecognized_keys,keys:G}),J.dirty()}else if(U==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let U=this._def.catchall;for(let z of G){let j=X.data[z];H.push({key:{status:"valid",value:z},value:U._parse(new x1(X,j,X.path,z)),alwaysSet:z in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let U=[];for(let z of H){let j=await z.key,A=await z.value;U.push({key:j,value:A,alwaysSet:z.alwaysSet})}return U}).then((U)=>{return L1.mergeObjectSync(J,U)});else return L1.mergeObjectSync(J,H)}get shape(){return this._def.shape()}strict(Q){return U0.errToObj,new X1({...this._def,unknownKeys:"strict",...Q!==void 0?{errorMap:(Y,J)=>{let X=this._def.errorMap?.(Y,J).message??J.defaultError;if(Y.code==="unrecognized_keys")return{message:U0.errToObj(Q).message??X};return{message:X}}}:{}})}strip(){return new X1({...this._def,unknownKeys:"strip"})}passthrough(){return new X1({...this._def,unknownKeys:"passthrough"})}extend(Q){return new X1({...this._def,shape:()=>({...this._def.shape(),...Q})})}merge(Q){return new X1({unknownKeys:Q._def.unknownKeys,catchall:Q._def.catchall,shape:()=>({...this._def.shape(),...Q._def.shape()}),typeName:e.ZodObject})}setKey(Q,Y){return this.augment({[Q]:Y})}catchall(Q){return new X1({...this._def,catchall:Q})}pick(Q){let Y={};for(let J of C0.objectKeys(Q))if(Q[J]&&this.shape[J])Y[J]=this.shape[J];return new X1({...this._def,shape:()=>Y})}omit(Q){let Y={};for(let J of C0.objectKeys(this.shape))if(!Q[J])Y[J]=this.shape[J];return new X1({...this._def,shape:()=>Y})}deepPartial(){return r9(this)}partial(Q){let Y={};for(let J of C0.objectKeys(this.shape)){let X=this.shape[J];if(Q&&!Q[J])Y[J]=X;else Y[J]=X.optional()}return new X1({...this._def,shape:()=>Y})}required(Q){let Y={};for(let J of C0.objectKeys(this.shape))if(Q&&!Q[J])Y[J]=this.shape[J];else{let B=this.shape[J];while(B instanceof p1)B=B._def.innerType;Y[J]=B}return new X1({...this._def,shape:()=>Y})}keyof(){return WY(C0.objectKeys(this.shape))}}X1.create=(Q,Y)=>{return new X1({shape:()=>Q,unknownKeys:"strip",catchall:B9.create(),typeName:e.ZodObject,...w0(Y)})};X1.strictCreate=(Q,Y)=>{return new X1({shape:()=>Q,unknownKeys:"strict",catchall:B9.create(),typeName:e.ZodObject,...w0(Y)})};X1.lazycreate=(Q,Y)=>{return new X1({shape:Q,unknownKeys:"strip",catchall:B9.create(),typeName:e.ZodObject,...w0(Y)})};class m8 extends S0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=this._def.options;function X(B){for(let G of B)if(G.result.status==="valid")return G.result;for(let G of B)if(G.result.status==="dirty")return Y.common.issues.push(...G.ctx.common.issues),G.result;let q=B.map((G)=>new E1(G.ctx.common.issues));return W0(Y,{code:s.invalid_union,unionErrors:q}),N0}if(Y.common.async)return Promise.all(J.map(async(B)=>{let q={...Y,common:{...Y.common,issues:[]},parent:null};return{result:await B._parseAsync({data:Y.data,path:Y.path,parent:q}),ctx:q}})).then(X);else{let B=void 0,q=[];for(let H of J){let U={...Y,common:{...Y.common,issues:[]},parent:null},z=H._parseSync({data:Y.data,path:Y.path,parent:U});if(z.status==="valid")return z;else if(z.status==="dirty"&&!B)B={result:z,ctx:U};if(U.common.issues.length)q.push(U.common.issues)}if(B)return Y.common.issues.push(...B.ctx.common.issues),B.result;let G=q.map((H)=>new E1(H));return W0(Y,{code:s.invalid_union,unionErrors:G}),N0}}get options(){return this._def.options}}m8.create=(Q,Y)=>{return new m8({options:Q,typeName:e.ZodUnion,...w0(Y)})};var W9=(Q)=>{if(Q instanceof c8)return W9(Q.schema);else if(Q instanceof n1)return W9(Q.innerType());else if(Q instanceof d8)return[Q.value];else if(Q instanceof g9)return Q.options;else if(Q instanceof l8)return C0.objectValues(Q.enum);else if(Q instanceof p8)return W9(Q._def.innerType);else if(Q instanceof f8)return[void 0];else if(Q instanceof h8)return[null];else if(Q instanceof p1)return[void 0,...W9(Q.unwrap())];else if(Q instanceof D9)return[null,...W9(Q.unwrap())];else if(Q instanceof qX)return W9(Q.unwrap());else if(Q instanceof i8)return W9(Q.unwrap());else if(Q instanceof n8)return W9(Q._def.innerType);else return[]};class BX extends S0{_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==Y0.object)return W0(Y,{code:s.invalid_type,expected:Y0.object,received:Y.parsedType}),N0;let J=this.discriminator,X=Y.data[J],B=this.optionsMap.get(X);if(!B)return W0(Y,{code:s.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),N0;if(Y.common.async)return B._parseAsync({data:Y.data,path:Y.path,parent:Y});else return B._parseSync({data:Y.data,path:Y.path,parent:Y})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(Q,Y,J){let X=new Map;for(let B of Y){let q=W9(B.shape[Q]);if(!q.length)throw Error(`A discriminator value for key \`${Q}\` could not be extracted from all schema options`);for(let G of q){if(X.has(G))throw Error(`Discriminator property ${String(Q)} has duplicate value ${String(G)}`);X.set(G,B)}}return new BX({typeName:e.ZodDiscriminatedUnion,discriminator:Q,options:Y,optionsMap:X,...w0(J)})}}function GX(Q,Y){let J=J9(Q),X=J9(Y);if(Q===Y)return{valid:!0,data:Q};else if(J===Y0.object&&X===Y0.object){let B=C0.objectKeys(Y),q=C0.objectKeys(Q).filter((H)=>B.indexOf(H)!==-1),G={...Q,...Y};for(let H of q){let U=GX(Q[H],Y[H]);if(!U.valid)return{valid:!1};G[H]=U.data}return{valid:!0,data:G}}else if(J===Y0.array&&X===Y0.array){if(Q.length!==Y.length)return{valid:!1};let B=[];for(let q=0;q<Q.length;q++){let G=Q[q],H=Y[q],U=GX(G,H);if(!U.valid)return{valid:!1};B.push(U.data)}return{valid:!0,data:B}}else if(J===Y0.date&&X===Y0.date&&+Q===+Y)return{valid:!0,data:Q};else return{valid:!1}}class u8 extends S0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q),X=(B,q)=>{if(YX(B)||YX(q))return N0;let G=GX(B.value,q.value);if(!G.valid)return W0(J,{code:s.invalid_intersection_types}),N0;if(JX(B)||JX(q))Y.dirty();return{status:Y.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([B,q])=>X(B,q));else return X(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}u8.create=(Q,Y,J)=>{return new u8({left:Q,right:Y,typeName:e.ZodIntersection,...w0(J)})};class q9 extends S0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==Y0.array)return W0(J,{code:s.invalid_type,expected:Y0.array,received:J.parsedType}),N0;if(J.data.length<this._def.items.length)return W0(J,{code:s.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),N0;if(!this._def.rest&&J.data.length>this._def.items.length)W0(J,{code:s.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y.dirty();let B=[...J.data].map((q,G)=>{let H=this._def.items[G]||this._def.rest;if(!H)return null;return H._parse(new x1(J,q,J.path,G))}).filter((q)=>!!q);if(J.common.async)return Promise.all(B).then((q)=>{return L1.mergeArray(Y,q)});else return L1.mergeArray(Y,B)}get items(){return this._def.items}rest(Q){return new q9({...this._def,rest:Q})}}q9.create=(Q,Y)=>{if(!Array.isArray(Q))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new q9({items:Q,typeName:e.ZodTuple,rest:null,...w0(Y)})};class wQ extends S0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==Y0.object)return W0(J,{code:s.invalid_type,expected:Y0.object,received:J.parsedType}),N0;let X=[],B=this._def.keyType,q=this._def.valueType;for(let G in J.data)X.push({key:B._parse(new x1(J,G,J.path,G)),value:q._parse(new x1(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return L1.mergeObjectAsync(Y,X);else return L1.mergeObjectSync(Y,X)}get element(){return this._def.valueType}static create(Q,Y,J){if(Y instanceof S0)return new wQ({keyType:Q,valueType:Y,typeName:e.ZodRecord,...w0(J)});return new wQ({keyType:G9.create(),valueType:Q,typeName:e.ZodRecord,...w0(Y)})}}class OQ extends S0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==Y0.map)return W0(J,{code:s.invalid_type,expected:Y0.map,received:J.parsedType}),N0;let X=this._def.keyType,B=this._def.valueType,q=[...J.data.entries()].map(([G,H],U)=>{return{key:X._parse(new x1(J,G,J.path,[U,"key"])),value:B._parse(new x1(J,H,J.path,[U,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let H of q){let U=await H.key,z=await H.value;if(U.status==="aborted"||z.status==="aborted")return N0;if(U.status==="dirty"||z.status==="dirty")Y.dirty();G.set(U.value,z.value)}return{status:Y.value,value:G}})}else{let G=new Map;for(let H of q){let{key:U,value:z}=H;if(U.status==="aborted"||z.status==="aborted")return N0;if(U.status==="dirty"||z.status==="dirty")Y.dirty();G.set(U.value,z.value)}return{status:Y.value,value:G}}}}OQ.create=(Q,Y,J)=>{return new OQ({valueType:Y,keyType:Q,typeName:e.ZodMap,...w0(J)})};class Q8 extends S0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==Y0.set)return W0(J,{code:s.invalid_type,expected:Y0.set,received:J.parsedType}),N0;let X=this._def;if(X.minSize!==null){if(J.data.size<X.minSize.value)W0(J,{code:s.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),Y.dirty()}if(X.maxSize!==null){if(J.data.size>X.maxSize.value)W0(J,{code:s.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),Y.dirty()}let B=this._def.valueType;function q(H){let U=new Set;for(let z of H){if(z.status==="aborted")return N0;if(z.status==="dirty")Y.dirty();U.add(z.value)}return{status:Y.value,value:U}}let G=[...J.data.values()].map((H,U)=>B._parse(new x1(J,H,J.path,U)));if(J.common.async)return Promise.all(G).then((H)=>q(H));else return q(G)}min(Q,Y){return new Q8({...this._def,minSize:{value:Q,message:U0.toString(Y)}})}max(Q,Y){return new Q8({...this._def,maxSize:{value:Q,message:U0.toString(Y)}})}size(Q,Y){return this.min(Q,Y).max(Q,Y)}nonempty(Q){return this.min(1,Q)}}Q8.create=(Q,Y)=>{return new Q8({valueType:Q,minSize:null,maxSize:null,typeName:e.ZodSet,...w0(Y)})};class y8 extends S0{constructor(){super(...arguments);this.validate=this.implement}_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==Y0.function)return W0(Y,{code:s.invalid_type,expected:Y0.function,received:Y.parsedType}),N0;function J(G,H){return KQ({data:G,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,x8(),V9].filter((U)=>!!U),issueData:{code:s.invalid_arguments,argumentsError:H}})}function X(G,H){return KQ({data:G,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,x8(),V9].filter((U)=>!!U),issueData:{code:s.invalid_return_type,returnTypeError:H}})}let B={errorMap:Y.common.contextualErrorMap},q=Y.data;if(this._def.returns instanceof X8){let G=this;return K1(async function(...H){let U=new E1([]),z=await G._def.args.parseAsync(H,B).catch((V)=>{throw U.addIssue(J(H,V)),U}),j=await Reflect.apply(q,this,z);return await G._def.returns._def.type.parseAsync(j,B).catch((V)=>{throw U.addIssue(X(j,V)),U})})}else{let G=this;return K1(function(...H){let U=G._def.args.safeParse(H,B);if(!U.success)throw new E1([J(H,U.error)]);let z=Reflect.apply(q,this,U.data),j=G._def.returns.safeParse(z,B);if(!j.success)throw new E1([X(z,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...Q){return new y8({...this._def,args:q9.create(Q).rest(x9.create())})}returns(Q){return new y8({...this._def,returns:Q})}implement(Q){return this.parse(Q)}strictImplement(Q){return this.parse(Q)}static create(Q,Y,J){return new y8({args:Q?Q:q9.create([]).rest(x9.create()),returns:Y||x9.create(),typeName:e.ZodFunction,...w0(J)})}}class c8 extends S0{get schema(){return this._def.getter()}_parse(Q){let{ctx:Y}=this._processInputParams(Q);return this._def.getter()._parse({data:Y.data,path:Y.path,parent:Y})}}c8.create=(Q,Y)=>{return new c8({getter:Q,typeName:e.ZodLazy,...w0(Y)})};class d8 extends S0{_parse(Q){if(Q.data!==this._def.value){let Y=this._getOrReturnCtx(Q);return W0(Y,{received:Y.data,code:s.invalid_literal,expected:this._def.value}),N0}return{status:"valid",value:Q.data}}get value(){return this._def.value}}d8.create=(Q,Y)=>{return new d8({value:Q,typeName:e.ZodLiteral,...w0(Y)})};function WY(Q,Y){return new g9({values:Q,typeName:e.ZodEnum,...w0(Y)})}class g9 extends S0{_parse(Q){if(typeof Q.data!=="string"){let Y=this._getOrReturnCtx(Q),J=this._def.values;return W0(Y,{expected:C0.joinValues(J),received:Y.parsedType,code:s.invalid_type}),N0}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(Q.data)){let Y=this._getOrReturnCtx(Q),J=this._def.values;return W0(Y,{received:Y.data,code:s.invalid_enum_value,options:J}),N0}return K1(Q.data)}get options(){return this._def.values}get enum(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}get Values(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}get Enum(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}extract(Q,Y=this._def){return g9.create(Q,{...this._def,...Y})}exclude(Q,Y=this._def){return g9.create(this.options.filter((J)=>!Q.includes(J)),{...this._def,...Y})}}g9.create=WY;class l8 extends S0{_parse(Q){let Y=C0.getValidEnumValues(this._def.values),J=this._getOrReturnCtx(Q);if(J.parsedType!==Y0.string&&J.parsedType!==Y0.number){let X=C0.objectValues(Y);return W0(J,{expected:C0.joinValues(X),received:J.parsedType,code:s.invalid_type}),N0}if(!this._cache)this._cache=new Set(C0.getValidEnumValues(this._def.values));if(!this._cache.has(Q.data)){let X=C0.objectValues(Y);return W0(J,{received:J.data,code:s.invalid_enum_value,options:X}),N0}return K1(Q.data)}get enum(){return this._def.values}}l8.create=(Q,Y)=>{return new l8({values:Q,typeName:e.ZodNativeEnum,...w0(Y)})};class X8 extends S0{unwrap(){return this._def.type}_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==Y0.promise&&Y.common.async===!1)return W0(Y,{code:s.invalid_type,expected:Y0.promise,received:Y.parsedType}),N0;let J=Y.parsedType===Y0.promise?Y.data:Promise.resolve(Y.data);return K1(J.then((X)=>{return this._def.type.parseAsync(X,{path:Y.path,errorMap:Y.common.contextualErrorMap})}))}}X8.create=(Q,Y)=>{return new X8({type:Q,typeName:e.ZodPromise,...w0(Y)})};class n1 extends S0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q),X=this._def.effect||null,B={addIssue:(q)=>{if(W0(J,q),q.fatal)Y.abort();else Y.dirty()},get path(){return J.path}};if(B.addIssue=B.addIssue.bind(B),X.type==="preprocess"){let q=X.transform(J.data,B);if(J.common.async)return Promise.resolve(q).then(async(G)=>{if(Y.value==="aborted")return N0;let H=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(H.status==="aborted")return N0;if(H.status==="dirty")return o9(H.value);if(Y.value==="dirty")return o9(H.value);return H});else{if(Y.value==="aborted")return N0;let G=this._def.schema._parseSync({data:q,path:J.path,parent:J});if(G.status==="aborted")return N0;if(G.status==="dirty")return o9(G.value);if(Y.value==="dirty")return o9(G.value);return G}}if(X.type==="refinement"){let q=(G)=>{let H=X.refinement(G,B);if(J.common.async)return Promise.resolve(H);if(H instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return N0;if(G.status==="dirty")Y.dirty();return q(G.value),{status:Y.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return N0;if(G.status==="dirty")Y.dirty();return q(G.value).then(()=>{return{status:Y.value,value:G.value}})})}if(X.type==="transform")if(J.common.async===!1){let q=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!v9(q))return N0;let G=X.transform(q.value,B);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:Y.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((q)=>{if(!v9(q))return N0;return Promise.resolve(X.transform(q.value,B)).then((G)=>({status:Y.value,value:G}))});C0.assertNever(X)}}n1.create=(Q,Y,J)=>{return new n1({schema:Q,typeName:e.ZodEffects,effect:Y,...w0(J)})};n1.createWithPreprocess=(Q,Y,J)=>{return new n1({schema:Y,effect:{type:"preprocess",transform:Q},typeName:e.ZodEffects,...w0(J)})};class p1 extends S0{_parse(Q){if(this._getType(Q)===Y0.undefined)return K1(void 0);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}p1.create=(Q,Y)=>{return new p1({innerType:Q,typeName:e.ZodOptional,...w0(Y)})};class D9 extends S0{_parse(Q){if(this._getType(Q)===Y0.null)return K1(null);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}D9.create=(Q,Y)=>{return new D9({innerType:Q,typeName:e.ZodNullable,...w0(Y)})};class p8 extends S0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;if(Y.parsedType===Y0.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:Y.path,parent:Y})}removeDefault(){return this._def.innerType}}p8.create=(Q,Y)=>{return new p8({innerType:Q,typeName:e.ZodDefault,defaultValue:typeof Y.default==="function"?Y.default:()=>Y.default,...w0(Y)})};class n8 extends S0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J={...Y,common:{...Y.common,issues:[]}},X=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(g8(X))return X.then((B)=>{return{status:"valid",value:B.status==="valid"?B.value:this._def.catchValue({get error(){return new E1(J.common.issues)},input:J.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new E1(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}n8.create=(Q,Y)=>{return new n8({innerType:Q,typeName:e.ZodCatch,catchValue:typeof Y.catch==="function"?Y.catch:()=>Y.catch,...w0(Y)})};class RQ extends S0{_parse(Q){if(this._getType(Q)!==Y0.nan){let J=this._getOrReturnCtx(Q);return W0(J,{code:s.invalid_type,expected:Y0.nan,received:J.parsedType}),N0}return{status:"valid",value:Q.data}}}RQ.create=(Q)=>{return new RQ({typeName:e.ZodNaN,...w0(Q)})};var hj=Symbol("zod_brand");class qX extends S0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;return this._def.type._parse({data:J,path:Y.path,parent:Y})}unwrap(){return this._def.type}}class ZQ extends S0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.common.async)return(async()=>{let B=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(B.status==="aborted")return N0;if(B.status==="dirty")return Y.dirty(),o9(B.value);else return this._def.out._parseAsync({data:B.value,path:J.path,parent:J})})();else{let X=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(X.status==="aborted")return N0;if(X.status==="dirty")return Y.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:J.path,parent:J})}}static create(Q,Y){return new ZQ({in:Q,out:Y,typeName:e.ZodPipeline})}}class i8 extends S0{_parse(Q){let Y=this._def.innerType._parse(Q),J=(X)=>{if(v9(X))X.value=Object.freeze(X.value);return X};return g8(Y)?Y.then((X)=>J(X)):J(Y)}unwrap(){return this._def.innerType}}i8.create=(Q,Y)=>{return new i8({innerType:Q,typeName:e.ZodReadonly,...w0(Y)})};var mj={object:X1.lazycreate},e;(function(Q){Q.ZodString="ZodString",Q.ZodNumber="ZodNumber",Q.ZodNaN="ZodNaN",Q.ZodBigInt="ZodBigInt",Q.ZodBoolean="ZodBoolean",Q.ZodDate="ZodDate",Q.ZodSymbol="ZodSymbol",Q.ZodUndefined="ZodUndefined",Q.ZodNull="ZodNull",Q.ZodAny="ZodAny",Q.ZodUnknown="ZodUnknown",Q.ZodNever="ZodNever",Q.ZodVoid="ZodVoid",Q.ZodArray="ZodArray",Q.ZodObject="ZodObject",Q.ZodUnion="ZodUnion",Q.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Q.ZodIntersection="ZodIntersection",Q.ZodTuple="ZodTuple",Q.ZodRecord="ZodRecord",Q.ZodMap="ZodMap",Q.ZodSet="ZodSet",Q.ZodFunction="ZodFunction",Q.ZodLazy="ZodLazy",Q.ZodLiteral="ZodLiteral",Q.ZodEnum="ZodEnum",Q.ZodEffects="ZodEffects",Q.ZodNativeEnum="ZodNativeEnum",Q.ZodOptional="ZodOptional",Q.ZodNullable="ZodNullable",Q.ZodDefault="ZodDefault",Q.ZodCatch="ZodCatch",Q.ZodPromise="ZodPromise",Q.ZodBranded="ZodBranded",Q.ZodPipeline="ZodPipeline",Q.ZodReadonly="ZodReadonly"})(e||(e={}));var uj=G9.create,cj=t9.create,dj=RQ.create,lj=e9.create,pj=MQ.create,nj=$8.create,ij=AQ.create,aj=f8.create,sj=h8.create,oj=VQ.create,rj=x9.create,tj=B9.create,ej=DQ.create,QK=l1.create,XK=X1.create,YK=X1.strictCreate,JK=m8.create,WK=BX.create,GK=u8.create,BK=q9.create,qK=wQ.create,HK=OQ.create,zK=Q8.create,UK=y8.create,LK=c8.create,FK=d8.create,NK=g9.create,jK=l8.create,KK=X8.create,MK=n1.create,AK=p1.create,VK=D9.create,DK=n1.createWithPreprocess,wK=ZQ.create;function b0(...Q){return Q.reduce((Y,J)=>({...Y,...J!=null?J:{}}),{})}async function ZK(Q,Y){if(Q==null)return Promise.resolve();let J=Y==null?void 0:Y.abortSignal;return new Promise((X,B)=>{if(J==null?void 0:J.aborted){B(GY());return}let q=setTimeout(()=>{G(),X()},Q),G=()=>{clearTimeout(q),J==null||J.removeEventListener("abort",H)},H=()=>{G(),B(GY())};J==null||J.addEventListener("abort",H)})}function GY(){return new DOMException("Delay was aborted","AbortError")}function Y8(Q){return Object.fromEntries([...Q.headers])}var T4=({prefix:Q,size:Y=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:X="-"}={})=>{let B=()=>{let q=J.length,G=Array(Y);for(let H=0;H<Y;H++)G[H]=J[Math.random()*q|0];return G.join("")};if(Q==null)return B;if(J.includes(X))throw new a9({argument:"separator",message:`The separator "${X}" must not be part of the alphabet "${J}".`});return()=>`${Q}${X}${B()}`},s0=T4();function PK(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}function a8(Q){return(Q instanceof Error||Q instanceof DOMException)&&(Q.name==="AbortError"||Q.name==="ResponseAborted"||Q.name==="TimeoutError")}var _4=["fetch failed","failed to fetch"];function UY({error:Q,url:Y,requestBodyValues:J}){if(a8(Q))return Q;if(Q instanceof TypeError&&_4.includes(Q.message.toLowerCase())){let X=Q.cause;if(X!=null)return new a0({message:`Cannot connect to API: ${X.message}`,cause:X,url:Y,requestBodyValues:J,isRetryable:!0})}return Q}function LY(Q=globalThis){var Y,J,X;if(Q.window)return"runtime/browser";if((Y=Q.navigator)==null?void 0:Y.userAgent)return`runtime/${Q.navigator.userAgent.toLowerCase()}`;if((X=(J=Q.process)==null?void 0:J.versions)==null?void 0:X.node)return`runtime/node.js/${Q.process.version.substring(0)}`;if(Q.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function k4(Q){if(Q==null)return{};let Y={};if(Q instanceof Headers)Q.forEach((J,X)=>{Y[X.toLowerCase()]=J});else{if(!Array.isArray(Q))Q=Object.entries(Q);for(let[J,X]of Q)if(X!=null)Y[J.toLowerCase()]=X}return Y}function i1(Q,...Y){let J=new Headers(k4(Q)),X=J.get("user-agent")||"";return J.set("user-agent",[X,...Y].filter(Boolean).join(" ")),Object.fromEntries(J.entries())}var FY="3.0.15",v4=()=>globalThis.fetch,CK=async({url:Q,headers:Y={},successfulResponseHandler:J,failedResponseHandler:X,abortSignal:B,fetch:q=v4()})=>{try{let G=await q(Q,{method:"GET",headers:i1(Y,`ai-sdk/provider-utils/${FY}`,LY()),signal:B}),H=Y8(G);if(!G.ok){let U;try{U=await X({response:G,url:Q,requestBodyValues:{}})}catch(z){if(a8(z)||a0.isInstance(z))throw z;throw new a0({message:"Failed to process error response",cause:z,statusCode:G.status,url:Q,responseHeaders:H,requestBodyValues:{}})}throw U.value}try{return await J({response:G,url:Q,requestBodyValues:{}})}catch(U){if(U instanceof Error){if(a8(U)||a0.isInstance(U))throw U}throw new a0({message:"Failed to process successful response",cause:U,statusCode:G.status,url:Q,responseHeaders:H,requestBodyValues:{}})}}catch(G){throw UY({error:G,url:Q,requestBodyValues:{}})}};function bK({mediaType:Q,url:Y,supportedUrls:J}){return Y=Y.toLowerCase(),Q=Q.toLowerCase(),Object.entries(J).map(([X,B])=>{let q=X.toLowerCase();return q==="*"||q==="*/*"?{mediaTypePrefix:"",regexes:B}:{mediaTypePrefix:q.replace(/\*/,""),regexes:B}}).filter(({mediaTypePrefix:X})=>Q.startsWith(X)).flatMap(({regexes:X})=>X).some((X)=>X.test(Y))}function J8({apiKey:Q,environmentVariableName:Y,apiKeyParameterName:J="apiKey",description:X}){if(typeof Q==="string")return Q;if(Q!=null)throw new k9({message:`${X} API key must be a string.`});if(typeof process>"u")throw new k9({message:`${X} API key is missing. Pass it using the '${J}' parameter. Environment variables is not supported in this environment.`});if(Q=process.env[Y],Q==null)throw new k9({message:`${X} API key is missing. Pass it using the '${J}' parameter or the ${Y} environment variable.`});if(typeof Q!=="string")throw new k9({message:`${X} API key must be a string. The value of the ${Y} environment variable is not a string.`});return Q}function PQ({settingValue:Q,environmentVariableName:Y}){if(typeof Q==="string")return Q;if(Q!=null||typeof process>"u")return;if(Q=process.env[Y],Q==null||typeof Q!=="string")return;return Q}function NY(Q){var Y;let[J,X=""]=Q.toLowerCase().split("/");return(Y={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[X])!=null?Y:X}var x4=/"__proto__"\s*:/,g4=/"constructor"\s*:/;function y4(Q){let Y=JSON.parse(Q);if(Y===null||typeof Y!=="object")return Y;if(x4.test(Q)===!1&&g4.test(Q)===!1)return Y;return $4(Y)}function $4(Q){let Y=[Q];while(Y.length){let J=Y;Y=[];for(let X of J){if(Object.prototype.hasOwnProperty.call(X,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(X,"constructor")&&Object.prototype.hasOwnProperty.call(X.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let B in X){let q=X[B];if(q&&typeof q==="object")Y.push(q)}}}return Q}function FX(Q){let{stackTraceLimit:Y}=Error;Error.stackTraceLimit=0;try{return y4(Q)}finally{Error.stackTraceLimit=Y}}var EQ=Symbol.for("vercel.ai.validator");function f4(Q){return{[EQ]:!0,validate:Q}}function h4(Q){return typeof Q==="object"&&Q!==null&&EQ in Q&&Q[EQ]===!0&&"validate"in Q}function d0(Q){let Y;return()=>{if(Y==null)Y=Q();return Y}}function m4(Q){return h4(Q)?Q:typeof Q==="function"?Q():u4(Q)}function u4(Q){return f4(async(Y)=>{let J=await Q["~standard"].validate(Y);return J.issues==null?{success:!0,value:J.value}:{success:!1,error:new A9({value:Y,cause:J.issues})}})}async function q1({value:Q,schema:Y}){let J=await NX({value:Q,schema:Y});if(!J.success)throw A9.wrap({value:Q,cause:J.error});return J.value}async function NX({value:Q,schema:Y}){let J=m4(Y);try{if(J.validate==null)return{success:!0,value:Q,rawValue:Q};let X=await J.validate(Q);if(X.success)return{success:!0,value:X.value,rawValue:Q};return{success:!1,error:A9.wrap({value:Q,cause:X.error}),rawValue:Q}}catch(X){return{success:!1,error:A9.wrap({value:Q,cause:X}),rawValue:Q}}}async function c4({text:Q,schema:Y}){try{let J=FX(Q);if(Y==null)return J;return q1({value:J,schema:Y})}catch(J){if(v8.isInstance(J)||A9.isInstance(J))throw J;throw new v8({text:Q,cause:J})}}async function jY({text:Q,schema:Y}){try{let J=FX(Q);if(Y==null)return{success:!0,value:J,rawValue:J};return await NX({value:J,schema:Y})}catch(J){return{success:!1,error:v8.isInstance(J)?J:new v8({text:Q,cause:J}),rawValue:void 0}}}function W8(Q){try{return FX(Q),!0}catch(Y){return!1}}function d4({stream:Q,schema:Y}){return Q.pipeThrough(new TextDecoderStream).pipeThrough(new XX).pipeThrough(new TransformStream({async transform({data:J},X){if(J==="[DONE]")return;X.enqueue(await jY({text:J,schema:Y}))}}))}async function k0({provider:Q,providerOptions:Y,schema:J}){if((Y==null?void 0:Y[Q])==null)return;let X=await NX({value:Y[Q],schema:J});if(!X.success)throw new a9({argument:"providerOptions",message:`invalid ${Q} provider options`,cause:X.error});return X.value}var l4=()=>globalThis.fetch,T0=async({url:Q,headers:Y,body:J,failedResponseHandler:X,successfulResponseHandler:B,abortSignal:q,fetch:G})=>MY({url:Q,headers:{"Content-Type":"application/json",...Y},body:{content:JSON.stringify(J),values:J},failedResponseHandler:X,successfulResponseHandler:B,abortSignal:q,fetch:G}),KY=async({url:Q,headers:Y,formData:J,failedResponseHandler:X,successfulResponseHandler:B,abortSignal:q,fetch:G})=>MY({url:Q,headers:Y,body:{content:J,values:Object.fromEntries(J.entries())},failedResponseHandler:X,successfulResponseHandler:B,abortSignal:q,fetch:G}),MY=async({url:Q,headers:Y={},body:J,successfulResponseHandler:X,failedResponseHandler:B,abortSignal:q,fetch:G=l4()})=>{try{let H=await G(Q,{method:"POST",headers:i1(Y,`ai-sdk/provider-utils/${FY}`,LY()),body:J.content,signal:q}),U=Y8(H);if(!H.ok){let z;try{z=await B({response:H,url:Q,requestBodyValues:J.values})}catch(j){if(a8(j)||a0.isInstance(j))throw j;throw new a0({message:"Failed to process error response",cause:j,statusCode:H.status,url:Q,responseHeaders:U,requestBodyValues:J.values})}throw z.value}try{return await X({response:H,url:Q,requestBodyValues:J.values})}catch(z){if(z instanceof Error){if(a8(z)||a0.isInstance(z))throw z}throw new a0({message:"Failed to process successful response",cause:z,statusCode:H.status,url:Q,responseHeaders:U,requestBodyValues:J.values})}}catch(H){throw UY({error:H,url:Q,requestBodyValues:J.values})}};function AY(Q){return Q}function Y1({id:Q,name:Y,inputSchema:J}){return({execute:X,outputSchema:B,toModelOutput:q,onInputStart:G,onInputDelta:H,onInputAvailable:U,...z})=>AY({type:"provider-defined",id:Q,name:Y,args:z,inputSchema:J,outputSchema:B,execute:X,toModelOutput:q,onInputStart:G,onInputDelta:H,onInputAvailable:U})}function J1({id:Q,name:Y,inputSchema:J,outputSchema:X}){return({execute:B,toModelOutput:q,onInputStart:G,onInputDelta:H,onInputAvailable:U,...z})=>AY({type:"provider-defined",id:Q,name:Y,args:z,inputSchema:J,outputSchema:X,execute:B,toModelOutput:q,onInputStart:G,onInputDelta:H,onInputAvailable:U})}async function H9(Q){if(typeof Q==="function")Q=Q();return Promise.resolve(Q)}var V1=({errorSchema:Q,errorToMessage:Y,isRetryable:J})=>async({response:X,url:B,requestBodyValues:q})=>{let G=await X.text(),H=Y8(X);if(G.trim()==="")return{responseHeaders:H,value:new a0({message:X.statusText,url:B,requestBodyValues:q,statusCode:X.status,responseHeaders:H,responseBody:G,isRetryable:J==null?void 0:J(X)})};try{let U=await c4({text:G,schema:Q});return{responseHeaders:H,value:new a0({message:Y(U),url:B,requestBodyValues:q,statusCode:X.status,responseHeaders:H,responseBody:G,data:U,isRetryable:J==null?void 0:J(X,U)})}}catch(U){return{responseHeaders:H,value:new a0({message:X.statusText,url:B,requestBodyValues:q,statusCode:X.status,responseHeaders:H,responseBody:G,isRetryable:J==null?void 0:J(X)})}}},D1=(Q)=>async({response:Y})=>{let J=Y8(Y);if(Y.body==null)throw new E6({});return{responseHeaders:J,value:d4({stream:Y.body,schema:Q})}};var m0=(Q)=>async({response:Y,url:J,requestBodyValues:X})=>{let B=await Y.text(),q=await jY({text:B,schema:Q}),G=Y8(Y);if(!q.success)throw new a0({message:"Invalid JSON response",cause:q.error,statusCode:Y.status,responseHeaders:G,responseBody:B,url:J,requestBodyValues:X});return{responseHeaders:G,value:q.value,rawValue:q.rawValue}},VY=()=>async({response:Q,url:Y,requestBodyValues:J})=>{let X=Y8(Q);if(!Q.body)throw new a0({message:"Response body is empty",url:Y,requestBodyValues:J,statusCode:Q.status,responseHeaders:X,responseBody:void 0});try{let B=await Q.arrayBuffer();return{responseHeaders:X,value:new Uint8Array(B)}}catch(B){throw new a0({message:"Failed to read response as array buffer",url:Y,requestBodyValues:J,statusCode:Q.status,responseHeaders:X,responseBody:void 0,cause:B})}};var p4=(Q,Y)=>{let J=0;for(;J<Q.length&&J<Y.length;J++)if(Q[J]!==Y[J])break;return[(Q.length-J).toString(),...Y.slice(J)].join("/")},n4=Symbol("Let zodToJsonSchema decide on which parser to use"),BY={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"},i4=(Q)=>typeof Q==="string"?{...BY,name:Q}:{...BY,...Q};function P1(){return{}}function a4(Q,Y){var J,X,B;let q={type:"array"};if(((J=Q.type)==null?void 0:J._def)&&((B=(X=Q.type)==null?void 0:X._def)==null?void 0:B.typeName)!==e.ZodAny)q.items=h0(Q.type._def,{...Y,currentPath:[...Y.currentPath,"items"]});if(Q.minLength)q.minItems=Q.minLength.value;if(Q.maxLength)q.maxItems=Q.maxLength.value;if(Q.exactLength)q.minItems=Q.exactLength.value,q.maxItems=Q.exactLength.value;return q}function s4(Q){let Y={type:"integer",format:"int64"};if(!Q.checks)return Y;for(let J of Q.checks)switch(J.kind){case"min":if(J.inclusive)Y.minimum=J.value;else Y.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)Y.maximum=J.value;else Y.exclusiveMaximum=J.value;break;case"multipleOf":Y.multipleOf=J.value;break}return Y}function o4(){return{type:"boolean"}}function DY(Q,Y){return h0(Q.type._def,Y)}var r4=(Q,Y)=>{return h0(Q.innerType._def,Y)};function wY(Q,Y,J){let X=J!=null?J:Y.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((B,q)=>wY(Q,Y,B))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return t4(Q)}}var t4=(Q)=>{let Y={type:"integer",format:"unix-time"};for(let J of Q.checks)switch(J.kind){case"min":Y.minimum=J.value;break;case"max":Y.maximum=J.value;break}return Y};function e4(Q,Y){return{...h0(Q.innerType._def,Y),default:Q.defaultValue()}}function Q2(Q,Y){return Y.effectStrategy==="input"?h0(Q.schema._def,Y):P1()}function X2(Q){return{type:"string",enum:Array.from(Q.values)}}var Y2=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function J2(Q,Y){let J=[h0(Q.left._def,{...Y,currentPath:[...Y.currentPath,"allOf","0"]}),h0(Q.right._def,{...Y,currentPath:[...Y.currentPath,"allOf","1"]})].filter((B)=>!!B),X=[];return J.forEach((B)=>{if(Y2(B))X.push(...B.allOf);else{let q=B;if("additionalProperties"in B&&B.additionalProperties===!1){let{additionalProperties:G,...H}=B;q=H}X.push(q)}}),X.length?{allOf:X}:void 0}function W2(Q){let Y=typeof Q.value;if(Y!=="bigint"&&Y!=="number"&&Y!=="boolean"&&Y!=="string")return{type:Array.isArray(Q.value)?"array":"object"};return{type:Y==="bigint"?"integer":Y,const:Q.value}}var HX=void 0,g1={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:()=>{if(HX===void 0)HX=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return HX},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 OY(Q,Y){let J={type:"string"};if(Q.checks)for(let X of Q.checks)switch(X.kind){case"min":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,X.value):X.value;break;case"max":J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,X.value):X.value;break;case"email":switch(Y.emailStrategy){case"format:email":y1(J,"email",X.message,Y);break;case"format:idn-email":y1(J,"idn-email",X.message,Y);break;case"pattern:zod":M1(J,g1.email,X.message,Y);break}break;case"url":y1(J,"uri",X.message,Y);break;case"uuid":y1(J,"uuid",X.message,Y);break;case"regex":M1(J,X.regex,X.message,Y);break;case"cuid":M1(J,g1.cuid,X.message,Y);break;case"cuid2":M1(J,g1.cuid2,X.message,Y);break;case"startsWith":M1(J,RegExp(`^${zX(X.value,Y)}`),X.message,Y);break;case"endsWith":M1(J,RegExp(`${zX(X.value,Y)}$`),X.message,Y);break;case"datetime":y1(J,"date-time",X.message,Y);break;case"date":y1(J,"date",X.message,Y);break;case"time":y1(J,"time",X.message,Y);break;case"duration":y1(J,"duration",X.message,Y);break;case"length":J.minLength=typeof J.minLength==="number"?Math.max(J.minLength,X.value):X.value,J.maxLength=typeof J.maxLength==="number"?Math.min(J.maxLength,X.value):X.value;break;case"includes":{M1(J,RegExp(zX(X.value,Y)),X.message,Y);break}case"ip":{if(X.version!=="v6")y1(J,"ipv4",X.message,Y);if(X.version!=="v4")y1(J,"ipv6",X.message,Y);break}case"base64url":M1(J,g1.base64url,X.message,Y);break;case"jwt":M1(J,g1.jwt,X.message,Y);break;case"cidr":{if(X.version!=="v6")M1(J,g1.ipv4Cidr,X.message,Y);if(X.version!=="v4")M1(J,g1.ipv6Cidr,X.message,Y);break}case"emoji":M1(J,g1.emoji(),X.message,Y);break;case"ulid":{M1(J,g1.ulid,X.message,Y);break}case"base64":{switch(Y.base64Strategy){case"format:binary":{y1(J,"binary",X.message,Y);break}case"contentEncoding:base64":{J.contentEncoding="base64";break}case"pattern:zod":{M1(J,g1.base64,X.message,Y);break}}break}case"nanoid":M1(J,g1.nanoid,X.message,Y);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return J}function zX(Q,Y){return Y.patternStrategy==="escape"?B2(Q):Q}var G2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function B2(Q){let Y="";for(let J=0;J<Q.length;J++){if(!G2.has(Q[J]))Y+="\\";Y+=Q[J]}return Y}function y1(Q,Y,J,X){var B;if(Q.format||((B=Q.anyOf)==null?void 0:B.some((q)=>q.format))){if(!Q.anyOf)Q.anyOf=[];if(Q.format)Q.anyOf.push({format:Q.format}),delete Q.format;Q.anyOf.push({format:Y,...J&&X.errorMessages&&{errorMessage:{format:J}}})}else Q.format=Y}function M1(Q,Y,J,X){var B;if(Q.pattern||((B=Q.allOf)==null?void 0:B.some((q)=>q.pattern))){if(!Q.allOf)Q.allOf=[];if(Q.pattern)Q.allOf.push({pattern:Q.pattern}),delete Q.pattern;Q.allOf.push({pattern:qY(Y,X),...J&&X.errorMessages&&{errorMessage:{pattern:J}}})}else Q.pattern=qY(Y,X)}function qY(Q,Y){var J;if(!Y.applyRegexFlags||!Q.flags)return Q.source;let X={i:Q.flags.includes("i"),m:Q.flags.includes("m"),s:Q.flags.includes("s")},B=X.i?Q.source.toLowerCase():Q.source,q="",G=!1,H=!1,U=!1;for(let z=0;z<B.length;z++){if(G){q+=B[z],G=!1;continue}if(X.i){if(H){if(B[z].match(/[a-z]/)){if(U)q+=B[z],q+=`${B[z-2]}-${B[z]}`.toUpperCase(),U=!1;else if(B[z+1]==="-"&&((J=B[z+2])==null?void 0:J.match(/[a-z]/)))q+=B[z],U=!0;else q+=`${B[z]}${B[z].toUpperCase()}`;continue}}else if(B[z].match(/[a-z]/)){q+=`[${B[z]}${B[z].toUpperCase()}]`;continue}}if(X.m){if(B[z]==="^"){q+=`(^|(?<=[\r
8
- ]))`;continue}else if(B[z]==="$"){q+=`($|(?=[\r
9
- ]))`;continue}}if(X.s&&B[z]==="."){q+=H?`${B[z]}\r
10
- `:`[${B[z]}\r
11
- ]`;continue}if(q+=B[z],B[z]==="\\")G=!0;else if(H&&B[z]==="]")H=!1;else if(!H&&B[z]==="[")H=!0}try{new RegExp(q)}catch(z){return console.warn(`Could not convert regex pattern at ${Y.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return q}function RY(Q,Y){var J,X,B,q,G,H;let U={type:"object",additionalProperties:(J=h0(Q.valueType._def,{...Y,currentPath:[...Y.currentPath,"additionalProperties"]}))!=null?J:Y.allowedAdditionalProperties};if(((X=Q.keyType)==null?void 0:X._def.typeName)===e.ZodString&&((B=Q.keyType._def.checks)==null?void 0:B.length)){let{type:z,...j}=OY(Q.keyType._def,Y);return{...U,propertyNames:j}}else if(((q=Q.keyType)==null?void 0:q._def.typeName)===e.ZodEnum)return{...U,propertyNames:{enum:Q.keyType._def.values}};else if(((G=Q.keyType)==null?void 0:G._def.typeName)===e.ZodBranded&&Q.keyType._def.type._def.typeName===e.ZodString&&((H=Q.keyType._def.type._def.checks)==null?void 0:H.length)){let{type:z,...j}=DY(Q.keyType._def,Y);return{...U,propertyNames:j}}return U}function q2(Q,Y){if(Y.mapStrategy==="record")return RY(Q,Y);let J=h0(Q.keyType._def,{...Y,currentPath:[...Y.currentPath,"items","items","0"]})||P1(),X=h0(Q.valueType._def,{...Y,currentPath:[...Y.currentPath,"items","items","1"]})||P1();return{type:"array",maxItems:125,items:{type:"array",items:[J,X],minItems:2,maxItems:2}}}function H2(Q){let Y=Q.values,X=Object.keys(Q.values).filter((q)=>{return typeof Y[Y[q]]!=="number"}).map((q)=>Y[q]),B=Array.from(new Set(X.map((q)=>typeof q)));return{type:B.length===1?B[0]==="string"?"string":"number":["string","number"],enum:X}}function z2(){return{not:P1()}}function U2(){return{type:"null"}}var UX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function L2(Q,Y){let J=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(J.every((X)=>(X._def.typeName in UX)&&(!X._def.checks||!X._def.checks.length))){let X=J.reduce((B,q)=>{let G=UX[q._def.typeName];return G&&!B.includes(G)?[...B,G]:B},[]);return{type:X.length>1?X:X[0]}}else if(J.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=J.reduce((B,q)=>{let G=typeof q._def.value;switch(G){case"string":case"number":case"boolean":return[...B,G];case"bigint":return[...B,"integer"];case"object":if(q._def.value===null)return[...B,"null"];case"symbol":case"undefined":case"function":default:return B}},[]);if(X.length===J.length){let B=X.filter((q,G,H)=>H.indexOf(q)===G);return{type:B.length>1?B:B[0],enum:J.reduce((q,G)=>{return q.includes(G._def.value)?q:[...q,G._def.value]},[])}}}else if(J.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:J.reduce((X,B)=>[...X,...B._def.values.filter((q)=>!X.includes(q))],[])};return F2(Q,Y)}var F2=(Q,Y)=>{let J=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((X,B)=>h0(X._def,{...Y,currentPath:[...Y.currentPath,"anyOf",`${B}`]})).filter((X)=>!!X&&(!Y.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return J.length?{anyOf:J}:void 0};function N2(Q,Y){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length))return{type:[UX[Q.innerType._def.typeName],"null"]};let J=h0(Q.innerType._def,{...Y,currentPath:[...Y.currentPath,"anyOf","0"]});return J&&{anyOf:[J,{type:"null"}]}}function j2(Q){let Y={type:"number"};if(!Q.checks)return Y;for(let J of Q.checks)switch(J.kind){case"int":Y.type="integer";break;case"min":if(J.inclusive)Y.minimum=J.value;else Y.exclusiveMinimum=J.value;break;case"max":if(J.inclusive)Y.maximum=J.value;else Y.exclusiveMaximum=J.value;break;case"multipleOf":Y.multipleOf=J.value;break}return Y}function K2(Q,Y){let J={type:"object",properties:{}},X=[],B=Q.shape();for(let G in B){let H=B[G];if(H===void 0||H._def===void 0)continue;let U=A2(H),z=h0(H._def,{...Y,currentPath:[...Y.currentPath,"properties",G],propertyPath:[...Y.currentPath,"properties",G]});if(z===void 0)continue;if(J.properties[G]=z,!U)X.push(G)}if(X.length)J.required=X;let q=M2(Q,Y);if(q!==void 0)J.additionalProperties=q;return J}function M2(Q,Y){if(Q.catchall._def.typeName!=="ZodNever")return h0(Q.catchall._def,{...Y,currentPath:[...Y.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return Y.allowedAdditionalProperties;case"strict":return Y.rejectedAdditionalProperties;case"strip":return Y.removeAdditionalStrategy==="strict"?Y.allowedAdditionalProperties:Y.rejectedAdditionalProperties}}function A2(Q){try{return Q.isOptional()}catch(Y){return!0}}var V2=(Q,Y)=>{var J;if(Y.currentPath.toString()===((J=Y.propertyPath)==null?void 0:J.toString()))return h0(Q.innerType._def,Y);let X=h0(Q.innerType._def,{...Y,currentPath:[...Y.currentPath,"anyOf","1"]});return X?{anyOf:[{not:P1()},X]}:P1()},D2=(Q,Y)=>{if(Y.pipeStrategy==="input")return h0(Q.in._def,Y);else if(Y.pipeStrategy==="output")return h0(Q.out._def,Y);let J=h0(Q.in._def,{...Y,currentPath:[...Y.currentPath,"allOf","0"]}),X=h0(Q.out._def,{...Y,currentPath:[...Y.currentPath,"allOf",J?"1":"0"]});return{allOf:[J,X].filter((B)=>B!==void 0)}};function w2(Q,Y){return h0(Q.type._def,Y)}function O2(Q,Y){let X={type:"array",uniqueItems:!0,items:h0(Q.valueType._def,{...Y,currentPath:[...Y.currentPath,"items"]})};if(Q.minSize)X.minItems=Q.minSize.value;if(Q.maxSize)X.maxItems=Q.maxSize.value;return X}function R2(Q,Y){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((J,X)=>h0(J._def,{...Y,currentPath:[...Y.currentPath,"items",`${X}`]})).reduce((J,X)=>X===void 0?J:[...J,X],[]),additionalItems:h0(Q.rest._def,{...Y,currentPath:[...Y.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((J,X)=>h0(J._def,{...Y,currentPath:[...Y.currentPath,"items",`${X}`]})).reduce((J,X)=>X===void 0?J:[...J,X],[])}}function Z2(){return{not:P1()}}function E2(){return P1()}var P2=(Q,Y)=>{return h0(Q.innerType._def,Y)},S2=(Q,Y,J)=>{switch(Y){case e.ZodString:return OY(Q,J);case e.ZodNumber:return j2(Q);case e.ZodObject:return K2(Q,J);case e.ZodBigInt:return s4(Q);case e.ZodBoolean:return o4();case e.ZodDate:return wY(Q,J);case e.ZodUndefined:return Z2();case e.ZodNull:return U2();case e.ZodArray:return a4(Q,J);case e.ZodUnion:case e.ZodDiscriminatedUnion:return L2(Q,J);case e.ZodIntersection:return J2(Q,J);case e.ZodTuple:return R2(Q,J);case e.ZodRecord:return RY(Q,J);case e.ZodLiteral:return W2(Q);case e.ZodEnum:return X2(Q);case e.ZodNativeEnum:return H2(Q);case e.ZodNullable:return N2(Q,J);case e.ZodOptional:return V2(Q,J);case e.ZodMap:return q2(Q,J);case e.ZodSet:return O2(Q,J);case e.ZodLazy:return()=>Q.getter()._def;case e.ZodPromise:return w2(Q,J);case e.ZodNaN:case e.ZodNever:return z2();case e.ZodEffects:return Q2(Q,J);case e.ZodAny:return P1();case e.ZodUnknown:return E2();case e.ZodDefault:return e4(Q,J);case e.ZodBranded:return DY(Q,J);case e.ZodReadonly:return P2(Q,J);case e.ZodCatch:return r4(Q,J);case e.ZodPipeline:return D2(Q,J);case e.ZodFunction:case e.ZodVoid:case e.ZodSymbol:return;default:return((X)=>{return})(Y)}};function h0(Q,Y,J=!1){var X;let B=Y.seen.get(Q);if(Y.override){let U=(X=Y.override)==null?void 0:X.call(Y,Q,Y,B,J);if(U!==n4)return U}if(B&&!J){let U=I2(B,Y);if(U!==void 0)return U}let q={def:Q,path:Y.currentPath,jsonSchema:void 0};Y.seen.set(Q,q);let G=S2(Q,Q.typeName,Y),H=typeof G==="function"?h0(G(),Y):G;if(H)C2(Q,Y,H);if(Y.postProcess){let U=Y.postProcess(H,Q,Y);return q.jsonSchema=H,U}return q.jsonSchema=H,H}var I2=(Q,Y)=>{switch(Y.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:p4(Y.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<Y.currentPath.length&&Q.path.every((J,X)=>Y.currentPath[X]===J))return console.warn(`Recursive reference detected at ${Y.currentPath.join("/")}! Defaulting to any`),P1();return Y.$refStrategy==="seen"?P1():void 0}}},C2=(Q,Y,J)=>{if(Q.description)J.description=Q.description;return J},b2=(Q)=>{let Y=i4(Q),J=Y.name!==void 0?[...Y.basePath,Y.definitionPath,Y.name]:Y.basePath;return{...Y,currentPath:J,propertyPath:void 0,seen:new Map(Object.entries(Y.definitions).map(([X,B])=>[B._def,{def:B._def,path:[...Y.basePath,Y.definitionPath,X],jsonSchema:void 0}]))}},T2=(Q,Y)=>{var J;let X=b2(Y),B=typeof Y==="object"&&Y.definitions?Object.entries(Y.definitions).reduce((z,[j,A])=>{var V;return{...z,[j]:(V=h0(A._def,{...X,currentPath:[...X.basePath,X.definitionPath,j]},!0))!=null?V:P1()}},{}):void 0,q=typeof Y==="string"?Y:(Y==null?void 0:Y.nameStrategy)==="title"?void 0:Y==null?void 0:Y.name,G=(J=h0(Q._def,q===void 0?X:{...X,currentPath:[...X.basePath,X.definitionPath,q]},!1))!=null?J:P1(),H=typeof Y==="object"&&Y.name!==void 0&&Y.nameStrategy==="title"?Y.name:void 0;if(H!==void 0)G.title=H;let U=q===void 0?B?{...G,[X.definitionPath]:B}:G:{$ref:[...X.$refStrategy==="relative"?[]:X.basePath,X.definitionPath,q].join("/"),[X.definitionPath]:{...B,[q]:G}};return U.$schema="http://json-schema.org/draft-07/schema#",U},_2=T2;function k2(Q,Y){var J;let X=(J=Y==null?void 0:Y.useReferences)!=null?J:!1;return jX(()=>_2(Q,{$refStrategy:X?"root":"none"}),{validate:async(B)=>{let q=await Q.safeParseAsync(B);return q.success?{success:!0,value:q.data}:{success:!1,error:q.error}}})}function v2(Q,Y){var J;let X=(J=Y==null?void 0:Y.useReferences)!=null?J:!1;return jX(()=>HY(Q,{target:"draft-7",io:"output",reused:X?"ref":"inline"}),{validate:async(B)=>{let q=await zY(Q,B);return q.success?{success:!0,value:q.data}:{success:!1,error:q.error}}})}function x2(Q){return"_zod"in Q}function p(Q,Y){if(x2(Q))return v2(Q,Y);else return k2(Q,Y)}var LX=Symbol.for("vercel.ai.schema");function J0(Q){let Y;return()=>{if(Y==null)Y=Q();return Y}}function jX(Q,{validate:Y}={}){return{[LX]:!0,_type:void 0,[EQ]:!0,get jsonSchema(){if(typeof Q==="function")Q=Q();return Q},validate:Y}}function g2(Q){return typeof Q==="object"&&Q!==null&&LX in Q&&Q[LX]===!0&&"jsonSchema"in Q&&"validate"in Q}function uK(Q){return Q==null?jX({properties:{},additionalProperties:!1}):g2(Q)?Q:typeof Q==="function"?Q():p(Q)}var{btoa:y2,atob:$2}=globalThis;function ZY(Q){let Y=Q.replace(/-/g,"+").replace(/_/g,"/"),J=$2(Y);return Uint8Array.from(J,(X)=>X.codePointAt(0))}function f2(Q){let Y="";for(let J=0;J<Q.length;J++)Y+=String.fromCodePoint(Q[J]);return y2(Y)}function F1(Q){return Q instanceof Uint8Array?f2(Q):Q}function w9(Q){return Q==null?void 0:Q.replace(/\/$/,"")}function h2(Q){return Q!=null&&typeof Q[Symbol.asyncIterator]==="function"}async function*cK({execute:Q,input:Y,options:J}){let X=Q(Y,J);if(h2(X)){let B;for await(let q of X)B=q,yield{type:"preliminary",output:q};yield{type:"final",output:B}}else yield{type:"final",output:await X}}var m2="2.0.40",u2=J0(()=>p(W.object({type:W.literal("error"),error:W.object({type:W.string(),message:W.string()})}))),EY=V1({errorSchema:u2,errorToMessage:(Q)=>Q.error.message}),c2=J0(()=>p(W.object({type:W.literal("message"),id:W.string().nullish(),model:W.string().nullish(),content:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("text"),text:W.string(),citations:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("web_search_result_location"),cited_text:W.string(),url:W.string(),title:W.string(),encrypted_index:W.string()}),W.object({type:W.literal("page_location"),cited_text:W.string(),document_index:W.number(),document_title:W.string().nullable(),start_page_number:W.number(),end_page_number:W.number()}),W.object({type:W.literal("char_location"),cited_text:W.string(),document_index:W.number(),document_title:W.string().nullable(),start_char_index:W.number(),end_char_index:W.number()})])).optional()}),W.object({type:W.literal("thinking"),thinking:W.string(),signature:W.string()}),W.object({type:W.literal("redacted_thinking"),data:W.string()}),W.object({type:W.literal("tool_use"),id:W.string(),name:W.string(),input:W.unknown()}),W.object({type:W.literal("server_tool_use"),id:W.string(),name:W.string(),input:W.record(W.string(),W.unknown()).nullish()}),W.object({type:W.literal("web_fetch_tool_result"),tool_use_id:W.string(),content:W.union([W.object({type:W.literal("web_fetch_result"),url:W.string(),retrieved_at:W.string(),content:W.object({type:W.literal("document"),title:W.string().nullable(),citations:W.object({enabled:W.boolean()}).optional(),source:W.object({type:W.literal("text"),media_type:W.string(),data:W.string()})})}),W.object({type:W.literal("web_fetch_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("web_search_tool_result"),tool_use_id:W.string(),content:W.union([W.array(W.object({type:W.literal("web_search_result"),url:W.string(),title:W.string(),encrypted_content:W.string(),page_age:W.string().nullish()})),W.object({type:W.literal("web_search_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("code_execution_tool_result"),tool_use_id:W.string(),content:W.union([W.object({type:W.literal("code_execution_result"),stdout:W.string(),stderr:W.string(),return_code:W.number()}),W.object({type:W.literal("code_execution_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("bash_code_execution_tool_result"),tool_use_id:W.string(),content:W.discriminatedUnion("type",[W.object({type:W.literal("bash_code_execution_result"),content:W.array(W.object({type:W.literal("bash_code_execution_output"),file_id:W.string()})),stdout:W.string(),stderr:W.string(),return_code:W.number()}),W.object({type:W.literal("bash_code_execution_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("text_editor_code_execution_tool_result"),tool_use_id:W.string(),content:W.discriminatedUnion("type",[W.object({type:W.literal("text_editor_code_execution_tool_result_error"),error_code:W.string()}),W.object({type:W.literal("text_editor_code_execution_view_result"),content:W.string(),file_type:W.string(),num_lines:W.number().nullable(),start_line:W.number().nullable(),total_lines:W.number().nullable()}),W.object({type:W.literal("text_editor_code_execution_create_result"),is_file_update:W.boolean()}),W.object({type:W.literal("text_editor_code_execution_str_replace_result"),lines:W.array(W.string()).nullable(),new_lines:W.number().nullable(),new_start:W.number().nullable(),old_lines:W.number().nullable(),old_start:W.number().nullable()})])})])),stop_reason:W.string().nullish(),stop_sequence:W.string().nullish(),usage:W.looseObject({input_tokens:W.number(),output_tokens:W.number(),cache_creation_input_tokens:W.number().nullish(),cache_read_input_tokens:W.number().nullish()}),container:W.object({expires_at:W.string(),id:W.string(),skills:W.array(W.object({type:W.union([W.literal("anthropic"),W.literal("custom")]),skill_id:W.string(),version:W.string()})).nullish()}).nullish()}))),d2=J0(()=>p(W.discriminatedUnion("type",[W.object({type:W.literal("message_start"),message:W.object({id:W.string().nullish(),model:W.string().nullish(),usage:W.looseObject({input_tokens:W.number(),cache_creation_input_tokens:W.number().nullish(),cache_read_input_tokens:W.number().nullish()})})}),W.object({type:W.literal("content_block_start"),index:W.number(),content_block:W.discriminatedUnion("type",[W.object({type:W.literal("text"),text:W.string()}),W.object({type:W.literal("thinking"),thinking:W.string()}),W.object({type:W.literal("tool_use"),id:W.string(),name:W.string()}),W.object({type:W.literal("redacted_thinking"),data:W.string()}),W.object({type:W.literal("server_tool_use"),id:W.string(),name:W.string(),input:W.record(W.string(),W.unknown()).nullish()}),W.object({type:W.literal("web_fetch_tool_result"),tool_use_id:W.string(),content:W.union([W.object({type:W.literal("web_fetch_result"),url:W.string(),retrieved_at:W.string(),content:W.object({type:W.literal("document"),title:W.string().nullable(),citations:W.object({enabled:W.boolean()}).optional(),source:W.object({type:W.literal("text"),media_type:W.string(),data:W.string()})})}),W.object({type:W.literal("web_fetch_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("web_search_tool_result"),tool_use_id:W.string(),content:W.union([W.array(W.object({type:W.literal("web_search_result"),url:W.string(),title:W.string(),encrypted_content:W.string(),page_age:W.string().nullish()})),W.object({type:W.literal("web_search_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("code_execution_tool_result"),tool_use_id:W.string(),content:W.union([W.object({type:W.literal("code_execution_result"),stdout:W.string(),stderr:W.string(),return_code:W.number()}),W.object({type:W.literal("code_execution_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("bash_code_execution_tool_result"),tool_use_id:W.string(),content:W.discriminatedUnion("type",[W.object({type:W.literal("bash_code_execution_result"),content:W.array(W.object({type:W.literal("bash_code_execution_output"),file_id:W.string()})),stdout:W.string(),stderr:W.string(),return_code:W.number()}),W.object({type:W.literal("bash_code_execution_tool_result_error"),error_code:W.string()})])}),W.object({type:W.literal("text_editor_code_execution_tool_result"),tool_use_id:W.string(),content:W.discriminatedUnion("type",[W.object({type:W.literal("text_editor_code_execution_tool_result_error"),error_code:W.string()}),W.object({type:W.literal("text_editor_code_execution_view_result"),content:W.string(),file_type:W.string(),num_lines:W.number().nullable(),start_line:W.number().nullable(),total_lines:W.number().nullable()}),W.object({type:W.literal("text_editor_code_execution_create_result"),is_file_update:W.boolean()}),W.object({type:W.literal("text_editor_code_execution_str_replace_result"),lines:W.array(W.string()).nullable(),new_lines:W.number().nullable(),new_start:W.number().nullable(),old_lines:W.number().nullable(),old_start:W.number().nullable()})])})])}),W.object({type:W.literal("content_block_delta"),index:W.number(),delta:W.discriminatedUnion("type",[W.object({type:W.literal("input_json_delta"),partial_json:W.string()}),W.object({type:W.literal("text_delta"),text:W.string()}),W.object({type:W.literal("thinking_delta"),thinking:W.string()}),W.object({type:W.literal("signature_delta"),signature:W.string()}),W.object({type:W.literal("citations_delta"),citation:W.discriminatedUnion("type",[W.object({type:W.literal("web_search_result_location"),cited_text:W.string(),url:W.string(),title:W.string(),encrypted_index:W.string()}),W.object({type:W.literal("page_location"),cited_text:W.string(),document_index:W.number(),document_title:W.string().nullable(),start_page_number:W.number(),end_page_number:W.number()}),W.object({type:W.literal("char_location"),cited_text:W.string(),document_index:W.number(),document_title:W.string().nullable(),start_char_index:W.number(),end_char_index:W.number()})])})])}),W.object({type:W.literal("content_block_stop"),index:W.number()}),W.object({type:W.literal("error"),error:W.object({type:W.string(),message:W.string()})}),W.object({type:W.literal("message_delta"),delta:W.object({stop_reason:W.string().nullish(),stop_sequence:W.string().nullish(),container:W.object({expires_at:W.string(),id:W.string(),skills:W.array(W.object({type:W.union([W.literal("anthropic"),W.literal("custom")]),skill_id:W.string(),version:W.string()})).nullish()}).nullish()}),usage:W.looseObject({output_tokens:W.number(),cache_creation_input_tokens:W.number().nullish()})}),W.object({type:W.literal("message_stop")}),W.object({type:W.literal("ping")})]))),l2=J0(()=>p(W.object({signature:W.string().optional(),redactedData:W.string().optional()}))),PY=W.object({citations:W.object({enabled:W.boolean()}).optional(),title:W.string().optional(),context:W.string().optional()}),p2=W.object({sendReasoning:W.boolean().optional(),thinking:W.object({type:W.union([W.literal("enabled"),W.literal("disabled")]),budgetTokens:W.number().optional()}).optional(),disableParallelToolUse:W.boolean().optional(),cacheControl:W.object({type:W.literal("ephemeral"),ttl:W.union([W.literal("5m"),W.literal("1h")]).optional()}).optional(),container:W.object({id:W.string().optional(),skills:W.array(W.object({type:W.union([W.literal("anthropic"),W.literal("custom")]),skillId:W.string(),version:W.string().optional()})).optional()}).optional()}),SY=4;function n2(Q){var Y;let J=Q==null?void 0:Q.anthropic;return(Y=J==null?void 0:J.cacheControl)!=null?Y:J==null?void 0:J.cache_control}var KX=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(Q,Y){let J=n2(Q);if(!J)return;if(!Y.canCache){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`cache_control cannot be set on ${Y.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>SY){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`Maximum ${SY} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return J}getWarnings(){return this.warnings}},i2=J0(()=>p(W.object({maxCharacters:W.number().optional()}))),a2=J0(()=>p(W.object({command:W.enum(["view","create","str_replace","insert"]),path:W.string(),file_text:W.string().optional(),insert_line:W.number().int().optional(),new_str:W.string().optional(),old_str:W.string().optional(),view_range:W.array(W.number().int()).optional()}))),s2=Y1({id:"anthropic.text_editor_20250728",name:"str_replace_based_edit_tool",inputSchema:a2}),o2=(Q={})=>{return s2(Q)},r2=J0(()=>p(W.object({maxUses:W.number().optional(),allowedDomains:W.array(W.string()).optional(),blockedDomains:W.array(W.string()).optional(),userLocation:W.object({type:W.literal("approximate"),city:W.string().optional(),region:W.string().optional(),country:W.string().optional(),timezone:W.string().optional()}).optional()}))),bY=J0(()=>p(W.array(W.object({url:W.string(),title:W.string(),pageAge:W.string().nullable(),encryptedContent:W.string(),type:W.literal("web_search_result")})))),t2=J0(()=>p(W.object({query:W.string()}))),e2=J1({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:t2,outputSchema:bY}),Q7=(Q={})=>{return e2(Q)},X7=J0(()=>p(W.object({maxUses:W.number().optional(),allowedDomains:W.array(W.string()).optional(),blockedDomains:W.array(W.string()).optional(),citations:W.object({enabled:W.boolean()}).optional(),maxContentTokens:W.number().optional()}))),TY=J0(()=>p(W.object({type:W.literal("web_fetch_result"),url:W.string(),content:W.object({type:W.literal("document"),title:W.string(),citations:W.object({enabled:W.boolean()}).optional(),source:W.union([W.object({type:W.literal("base64"),mediaType:W.literal("application/pdf"),data:W.string()}),W.object({type:W.literal("text"),mediaType:W.literal("text/plain"),data:W.string()})])}),retrievedAt:W.string().nullable()}))),Y7=J0(()=>p(W.object({url:W.string()}))),J7=J1({id:"anthropic.web_fetch_20250910",name:"web_fetch",inputSchema:Y7,outputSchema:TY}),W7=(Q={})=>{return J7(Q)};async function G7({tools:Q,toolChoice:Y,disableParallelToolUse:J,cacheControlValidator:X}){Q=(Q==null?void 0:Q.length)?Q:void 0;let B=[],q=new Set,G=X||new KX;if(Q==null)return{tools:void 0,toolChoice:void 0,toolWarnings:B,betas:q};let H=[];for(let z of Q)switch(z.type){case"function":{let j=G.getCacheControl(z.providerOptions,{type:"tool definition",canCache:!0});H.push({name:z.name,description:z.description,input_schema:z.inputSchema,cache_control:j});break}case"provider-defined":{switch(z.id){case"anthropic.code_execution_20250522":{q.add("code-execution-2025-05-22"),H.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{q.add("code-execution-2025-08-25"),H.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.computer_20250124":{q.add("computer-use-2025-01-24"),H.push({name:"computer",type:"computer_20250124",display_width_px:z.args.displayWidthPx,display_height_px:z.args.displayHeightPx,display_number:z.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{q.add("computer-use-2024-10-22"),H.push({name:"computer",type:"computer_20241022",display_width_px:z.args.displayWidthPx,display_height_px:z.args.displayHeightPx,display_number:z.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{q.add("computer-use-2025-01-24"),H.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{q.add("computer-use-2024-10-22"),H.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{q.add("computer-use-2025-01-24"),H.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let j=await q1({value:z.args,schema:i2});H.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:j.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{q.add("computer-use-2025-01-24"),H.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{q.add("computer-use-2024-10-22"),H.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{q.add("context-management-2025-06-27"),H.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{q.add("web-fetch-2025-09-10");let j=await q1({value:z.args,schema:X7});H.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:j.maxUses,allowed_domains:j.allowedDomains,blocked_domains:j.blockedDomains,citations:j.citations,max_content_tokens:j.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let j=await q1({value:z.args,schema:r2});H.push({type:"web_search_20250305",name:"web_search",max_uses:j.maxUses,allowed_domains:j.allowedDomains,blocked_domains:j.blockedDomains,user_location:j.userLocation,cache_control:void 0});break}default:{B.push({type:"unsupported-tool",tool:z});break}}break}default:{B.push({type:"unsupported-tool",tool:z});break}}if(Y==null)return{tools:H,toolChoice:J?{type:"auto",disable_parallel_tool_use:J}:void 0,toolWarnings:B,betas:q};let U=Y.type;switch(U){case"auto":return{tools:H,toolChoice:{type:"auto",disable_parallel_tool_use:J},toolWarnings:B,betas:q};case"required":return{tools:H,toolChoice:{type:"any",disable_parallel_tool_use:J},toolWarnings:B,betas:q};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:B,betas:q};case"tool":return{tools:H,toolChoice:{type:"tool",name:Y.toolName,disable_parallel_tool_use:J},toolWarnings:B,betas:q};default:throw new I0({functionality:`tool choice type: ${U}`})}}var _Y=J0(()=>p(W.object({type:W.literal("code_execution_result"),stdout:W.string(),stderr:W.string(),return_code:W.number()}))),B7=J0(()=>p(W.object({code:W.string()}))),q7=J1({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:B7,outputSchema:_Y}),H7=(Q={})=>{return q7(Q)},kY=J0(()=>p(W.discriminatedUnion("type",[W.object({type:W.literal("bash_code_execution_result"),content:W.array(W.object({type:W.literal("bash_code_execution_output"),file_id:W.string()})),stdout:W.string(),stderr:W.string(),return_code:W.number()}),W.object({type:W.literal("bash_code_execution_tool_result_error"),error_code:W.string()}),W.object({type:W.literal("text_editor_code_execution_tool_result_error"),error_code:W.string()}),W.object({type:W.literal("text_editor_code_execution_view_result"),content:W.string(),file_type:W.string(),num_lines:W.number().nullable(),start_line:W.number().nullable(),total_lines:W.number().nullable()}),W.object({type:W.literal("text_editor_code_execution_create_result"),is_file_update:W.boolean()}),W.object({type:W.literal("text_editor_code_execution_str_replace_result"),lines:W.array(W.string()).nullable(),new_lines:W.number().nullable(),new_start:W.number().nullable(),old_lines:W.number().nullable(),old_start:W.number().nullable()})]))),z7=J0(()=>p(W.discriminatedUnion("type",[W.object({type:W.literal("bash_code_execution"),command:W.string()}),W.discriminatedUnion("command",[W.object({type:W.literal("text_editor_code_execution"),command:W.literal("view"),path:W.string()}),W.object({type:W.literal("text_editor_code_execution"),command:W.literal("create"),path:W.string(),file_text:W.string().nullish()}),W.object({type:W.literal("text_editor_code_execution"),command:W.literal("str_replace"),path:W.string(),old_str:W.string(),new_str:W.string()})])]))),U7=J1({id:"anthropic.code_execution_20250825",name:"code_execution",inputSchema:z7,outputSchema:kY}),L7=(Q={})=>{return U7(Q)};function F7(Q){if(typeof Q==="string")return Buffer.from(Q,"base64").toString("utf-8");if(Q instanceof Uint8Array)return new TextDecoder().decode(Q);if(Q instanceof URL)throw new I0({functionality:"URL-based text documents are not supported for citations"});throw new I0({functionality:`unsupported data type for text documents: ${typeof Q}`})}async function N7({prompt:Q,sendReasoning:Y,warnings:J,cacheControlValidator:X}){var B,q,G,H,U;let z=new Set,j=j7(Q),A=X||new KX,V=void 0,F=[];async function D(N){var K,M;let w=await k0({provider:"anthropic",providerOptions:N,schema:PY});return(M=(K=w==null?void 0:w.citations)==null?void 0:K.enabled)!=null?M:!1}async function L(N){let K=await k0({provider:"anthropic",providerOptions:N,schema:PY});return{title:K==null?void 0:K.title,context:K==null?void 0:K.context}}for(let N=0;N<j.length;N++){let K=j[N],M=N===j.length-1,w=K.type;switch(w){case"system":{if(V!=null)throw new I0({functionality:"Multiple system messages that are separated by user/assistant messages"});V=K.messages.map(({content:_,providerOptions:g})=>({type:"text",text:_,cache_control:A.getCacheControl(g,{type:"system message",canCache:!0})}));break}case"user":{let _=[];for(let g of K.messages){let{role:S,content:C}=g;switch(S){case"user":{for(let T=0;T<C.length;T++){let b=C[T],k=T===C.length-1,I=(B=A.getCacheControl(b.providerOptions,{type:"user message part",canCache:!0}))!=null?B:k?A.getCacheControl(g.providerOptions,{type:"user message",canCache:!0}):void 0;switch(b.type){case"text":{_.push({type:"text",text:b.text,cache_control:I});break}case"file":{if(b.mediaType.startsWith("image/"))_.push({type:"image",source:b.data instanceof URL?{type:"url",url:b.data.toString()}:{type:"base64",media_type:b.mediaType==="image/*"?"image/jpeg":b.mediaType,data:F1(b.data)},cache_control:I});else if(b.mediaType==="application/pdf"){z.add("pdfs-2024-09-25");let E=await D(b.providerOptions),R=await L(b.providerOptions);_.push({type:"document",source:b.data instanceof URL?{type:"url",url:b.data.toString()}:{type:"base64",media_type:"application/pdf",data:F1(b.data)},title:(q=R.title)!=null?q:b.filename,...R.context&&{context:R.context},...E&&{citations:{enabled:!0}},cache_control:I})}else if(b.mediaType==="text/plain"){let E=await D(b.providerOptions),R=await L(b.providerOptions);_.push({type:"document",source:b.data instanceof URL?{type:"url",url:b.data.toString()}:{type:"text",media_type:"text/plain",data:F7(b.data)},title:(G=R.title)!=null?G:b.filename,...R.context&&{context:R.context},...E&&{citations:{enabled:!0}},cache_control:I})}else throw new I0({functionality:`media type: ${b.mediaType}`});break}}}break}case"tool":{for(let T=0;T<C.length;T++){let b=C[T],k=T===C.length-1,I=(H=A.getCacheControl(b.providerOptions,{type:"tool result part",canCache:!0}))!=null?H:k?A.getCacheControl(g.providerOptions,{type:"tool result message",canCache:!0}):void 0,E=b.output,R;switch(E.type){case"content":R=E.value.map((Z)=>{switch(Z.type){case"text":return{type:"text",text:Z.text};case"media":{if(Z.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:Z.mediaType,data:Z.data}};if(Z.mediaType==="application/pdf")return z.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:Z.mediaType,data:Z.data}};throw new I0({functionality:`media type: ${Z.mediaType}`})}}});break;case"text":case"error-text":R=E.value;break;case"json":case"error-json":default:R=JSON.stringify(E.value);break}_.push({type:"tool_result",tool_use_id:b.toolCallId,content:R,is_error:E.type==="error-text"||E.type==="error-json"?!0:void 0,cache_control:I})}break}default:throw Error(`Unsupported role: ${S}`)}}F.push({role:"user",content:_});break}case"assistant":{let _=[];for(let g=0;g<K.messages.length;g++){let S=K.messages[g],C=g===K.messages.length-1,{content:T}=S;for(let b=0;b<T.length;b++){let k=T[b],I=b===T.length-1,E=(U=A.getCacheControl(k.providerOptions,{type:"assistant message part",canCache:!0}))!=null?U:I?A.getCacheControl(S.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(k.type){case"text":{_.push({type:"text",text:M&&C&&I?k.text.trim():k.text,cache_control:E});break}case"reasoning":{if(Y){let R=await k0({provider:"anthropic",providerOptions:k.providerOptions,schema:l2});if(R!=null)if(R.signature!=null)A.getCacheControl(k.providerOptions,{type:"thinking block",canCache:!1}),_.push({type:"thinking",thinking:k.text,signature:R.signature});else if(R.redactedData!=null)A.getCacheControl(k.providerOptions,{type:"redacted thinking block",canCache:!1}),_.push({type:"redacted_thinking",data:R.redactedData});else J.push({type:"other",message:"unsupported reasoning metadata"});else J.push({type:"other",message:"unsupported reasoning metadata"})}else J.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(k.providerExecuted){if(k.toolName==="code_execution"&&k.input!=null&&typeof k.input==="object"&&"type"in k.input&&typeof k.input.type==="string"&&(k.input.type==="bash_code_execution"||k.input.type==="text_editor_code_execution"))_.push({type:"server_tool_use",id:k.toolCallId,name:k.input.type,input:k.input,cache_control:E});else if(k.toolName==="code_execution"||k.toolName==="web_fetch"||k.toolName==="web_search")_.push({type:"server_tool_use",id:k.toolCallId,name:k.toolName,input:k.input,cache_control:E});else J.push({type:"other",message:`provider executed tool call for tool ${k.toolName} is not supported`});break}_.push({type:"tool_use",id:k.toolCallId,name:k.toolName,input:k.input,cache_control:E});break}case"tool-result":{if(k.toolName==="code_execution"){let R=k.output;if(R.type!=="json"){J.push({type:"other",message:`provider executed tool result output type ${R.type} for tool ${k.toolName} is not supported`});break}if(R.value==null||typeof R.value!=="object"||!("type"in R.value)||typeof R.value.type!=="string"){J.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${k.toolName}`});break}if(R.value.type==="code_execution_result"){let Z=await q1({value:R.value,schema:_Y});_.push({type:"code_execution_tool_result",tool_use_id:k.toolCallId,content:{type:Z.type,stdout:Z.stdout,stderr:Z.stderr,return_code:Z.return_code},cache_control:E})}else{let Z=await q1({value:R.value,schema:kY});_.push(Z.type==="bash_code_execution_result"||Z.type==="bash_code_execution_tool_result_error"?{type:"bash_code_execution_tool_result",tool_use_id:k.toolCallId,cache_control:E,content:Z}:{type:"text_editor_code_execution_tool_result",tool_use_id:k.toolCallId,cache_control:E,content:Z})}break}if(k.toolName==="web_fetch"){let R=k.output;if(R.type!=="json"){J.push({type:"other",message:`provider executed tool result output type ${R.type} for tool ${k.toolName} is not supported`});break}let Z=await q1({value:R.value,schema:TY});_.push({type:"web_fetch_tool_result",tool_use_id:k.toolCallId,content:{type:"web_fetch_result",url:Z.url,retrieved_at:Z.retrievedAt,content:{type:"document",title:Z.content.title,citations:Z.content.citations,source:{type:Z.content.source.type,media_type:Z.content.source.mediaType,data:Z.content.source.data}}},cache_control:E});break}if(k.toolName==="web_search"){let R=k.output;if(R.type!=="json"){J.push({type:"other",message:`provider executed tool result output type ${R.type} for tool ${k.toolName} is not supported`});break}let Z=await q1({value:R.value,schema:bY});_.push({type:"web_search_tool_result",tool_use_id:k.toolCallId,content:Z.map((v)=>({url:v.url,title:v.title,page_age:v.pageAge,encrypted_content:v.encryptedContent,type:v.type})),cache_control:E});break}J.push({type:"other",message:`provider executed tool result for tool ${k.toolName} is not supported`});break}}}}F.push({role:"assistant",content:_});break}default:throw Error(`content type: ${w}`)}}return{prompt:{system:V,messages:F},betas:z}}function j7(Q){let Y=[],J=void 0;for(let X of Q){let{role:B}=X;switch(B){case"system":{if((J==null?void 0:J.type)!=="system")J={type:"system",messages:[]},Y.push(J);J.messages.push(X);break}case"assistant":{if((J==null?void 0:J.type)!=="assistant")J={type:"assistant",messages:[]},Y.push(J);J.messages.push(X);break}case"user":{if((J==null?void 0:J.type)!=="user")J={type:"user",messages:[]},Y.push(J);J.messages.push(X);break}case"tool":{if((J==null?void 0:J.type)!=="user")J={type:"user",messages:[]},Y.push(J);J.messages.push(X);break}default:throw Error(`Unsupported role: ${B}`)}}return Y}function IY({finishReason:Q,isJsonResponseFromTool:Y}){switch(Q){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return Y?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}function CY(Q,Y,J){var X;if(Q.type!=="page_location"&&Q.type!=="char_location")return;let B=Y[Q.document_index];if(!B)return;return{type:"source",sourceType:"document",id:J(),mediaType:B.mediaType,title:(X=Q.document_title)!=null?X:B.title,filename:B.filename,providerMetadata:{anthropic:Q.type==="page_location"?{citedText:Q.cited_text,startPageNumber:Q.start_page_number,endPageNumber:Q.end_page_number}:{citedText:Q.cited_text,startCharIndex:Q.start_char_index,endCharIndex:Q.end_char_index}}}}var K7=class{constructor(Q,Y){this.specificationVersion="v2";var J;this.modelId=Q,this.config=Y,this.generateId=(J=Y.generateId)!=null?J:s0}supportsUrl(Q){return Q.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var Q,Y,J;return(J=(Y=(Q=this.config).supportedUrls)==null?void 0:Y.call(Q))!=null?J:{}}async getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,topK:B,frequencyPenalty:q,presencePenalty:G,stopSequences:H,responseFormat:U,seed:z,tools:j,toolChoice:A,providerOptions:V}){var F,D,L,N;let K=[];if(q!=null)K.push({type:"unsupported-setting",setting:"frequencyPenalty"});if(G!=null)K.push({type:"unsupported-setting",setting:"presencePenalty"});if(z!=null)K.push({type:"unsupported-setting",setting:"seed"});if((U==null?void 0:U.type)==="json"){if(U.schema==null)K.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});else if(j!=null)K.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."})}let M=(U==null?void 0:U.type)==="json"&&U.schema!=null?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:U.schema}:void 0,w=await k0({provider:"anthropic",providerOptions:V,schema:p2}),_=new KX,{prompt:g,betas:S}=await N7({prompt:Q,sendReasoning:(F=w==null?void 0:w.sendReasoning)!=null?F:!0,warnings:K,cacheControlValidator:_}),C=((D=w==null?void 0:w.thinking)==null?void 0:D.type)==="enabled",T=(L=w==null?void 0:w.thinking)==null?void 0:L.budgetTokens,{maxOutputTokens:b,knownModel:k}=M7(this.modelId),I=Y!=null?Y:b,E={model:this.modelId,max_tokens:I,temperature:J,top_k:B,top_p:X,stop_sequences:H,...C&&{thinking:{type:"enabled",budget_tokens:T}},...(w==null?void 0:w.container)&&{container:{id:w.container.id,skills:(N=w.container.skills)==null?void 0:N.map((i)=>({type:i.type,skill_id:i.skillId,version:i.version}))}},system:g.system,messages:g.messages};if(C){if(T==null)throw new I0({functionality:"thinking requires a budget"});if(E.temperature!=null)E.temperature=void 0,K.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"});if(B!=null)E.top_k=void 0,K.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"});if(X!=null)E.top_p=void 0,K.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"});E.max_tokens=I+T}if(k&&E.max_tokens>b){if(Y!=null)K.push({type:"unsupported-setting",setting:"maxOutputTokens",details:`${E.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${b} max output tokens. The max output tokens have been limited to ${b}.`});E.max_tokens=b}if((w==null?void 0:w.container)&&w.container.skills&&w.container.skills.length>0){if(S.add("code-execution-2025-08-25"),S.add("skills-2025-10-02"),S.add("files-api-2025-04-14"),!(j==null?void 0:j.some((i)=>i.type==="provider-defined"&&i.id==="anthropic.code_execution_20250825")))K.push({type:"other",message:"code execution tool is required when using skills"})}let{tools:R,toolChoice:Z,toolWarnings:v,betas:y}=await G7(M!=null?{tools:[M],toolChoice:{type:"tool",toolName:M.name},disableParallelToolUse:!0,cacheControlValidator:_}:{tools:j!=null?j:[],toolChoice:A,disableParallelToolUse:w==null?void 0:w.disableParallelToolUse,cacheControlValidator:_}),m=_.getWarnings();return{args:{...E,tools:R,tool_choice:Z},warnings:[...K,...v,...m],betas:new Set([...S,...y]),usesJsonResponseTool:M!=null}}async getHeaders({betas:Q,headers:Y}){return b0(await H9(this.config.headers),Q.size>0?{"anthropic-beta":Array.from(Q).join(",")}:{},Y)}buildRequestUrl(Q){var Y,J,X;return(X=(J=(Y=this.config).buildRequestUrl)==null?void 0:J.call(Y,this.config.baseURL,Q))!=null?X:`${this.config.baseURL}/messages`}transformRequestBody(Q){var Y,J,X;return(X=(J=(Y=this.config).transformRequestBody)==null?void 0:J.call(Y,Q))!=null?X:Q}extractCitationDocuments(Q){let Y=(J)=>{var X,B;if(J.type!=="file")return!1;if(J.mediaType!=="application/pdf"&&J.mediaType!=="text/plain")return!1;let q=(X=J.providerOptions)==null?void 0:X.anthropic,G=q==null?void 0:q.citations;return(B=G==null?void 0:G.enabled)!=null?B:!1};return Q.filter((J)=>J.role==="user").flatMap((J)=>J.content).filter(Y).map((J)=>{var X;let B=J;return{title:(X=B.filename)!=null?X:"Untitled Document",filename:B.filename,mediaType:B.mediaType}})}async doGenerate(Q){var Y,J,X,B,q,G,H,U;let{args:z,warnings:j,betas:A,usesJsonResponseTool:V}=await this.getArgs(Q),F=this.extractCitationDocuments(Q.prompt),{responseHeaders:D,value:L,rawValue:N}=await T0({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:A,headers:Q.headers}),body:this.transformRequestBody(z),failedResponseHandler:EY,successfulResponseHandler:m0(c2),abortSignal:Q.abortSignal,fetch:this.config.fetch}),K=[];for(let M of L.content)switch(M.type){case"text":{if(!V){if(K.push({type:"text",text:M.text}),M.citations)for(let w of M.citations){let _=CY(w,F,this.generateId);if(_)K.push(_)}}break}case"thinking":{K.push({type:"reasoning",text:M.thinking,providerMetadata:{anthropic:{signature:M.signature}}});break}case"redacted_thinking":{K.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:M.data}}});break}case"tool_use":{K.push(V?{type:"text",text:JSON.stringify(M.input)}:{type:"tool-call",toolCallId:M.id,toolName:M.name,input:JSON.stringify(M.input)});break}case"server_tool_use":{if(M.name==="text_editor_code_execution"||M.name==="bash_code_execution")K.push({type:"tool-call",toolCallId:M.id,toolName:"code_execution",input:JSON.stringify({type:M.name,...M.input}),providerExecuted:!0});else if(M.name==="web_search"||M.name==="code_execution"||M.name==="web_fetch")K.push({type:"tool-call",toolCallId:M.id,toolName:M.name,input:JSON.stringify(M.input),providerExecuted:!0});break}case"web_fetch_tool_result":{if(M.content.type==="web_fetch_result")K.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:M.content.url,retrievedAt:M.content.retrieved_at,content:{type:M.content.content.type,title:M.content.content.title,citations:M.content.content.citations,source:{type:M.content.content.source.type,mediaType:M.content.content.source.media_type,data:M.content.content.source.data}}},providerExecuted:!0});else if(M.content.type==="web_fetch_tool_result_error")K.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:M.content.error_code},providerExecuted:!0});break}case"web_search_tool_result":{if(Array.isArray(M.content)){K.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:"web_search",result:M.content.map((w)=>{var _;return{url:w.url,title:w.title,pageAge:(_=w.page_age)!=null?_:null,encryptedContent:w.encrypted_content,type:w.type}}),providerExecuted:!0});for(let w of M.content)K.push({type:"source",sourceType:"url",id:this.generateId(),url:w.url,title:w.title,providerMetadata:{anthropic:{pageAge:(Y=w.page_age)!=null?Y:null}}})}else K.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:M.content.error_code},providerExecuted:!0});break}case"code_execution_tool_result":{if(M.content.type==="code_execution_result")K.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:"code_execution",result:{type:M.content.type,stdout:M.content.stdout,stderr:M.content.stderr,return_code:M.content.return_code},providerExecuted:!0});else if(M.content.type==="code_execution_tool_result_error")K.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:M.content.error_code},providerExecuted:!0});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{K.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:"code_execution",result:M.content,providerExecuted:!0});break}}return{content:K,finishReason:IY({finishReason:L.stop_reason,isJsonResponseFromTool:V}),usage:{inputTokens:L.usage.input_tokens,outputTokens:L.usage.output_tokens,totalTokens:L.usage.input_tokens+L.usage.output_tokens,cachedInputTokens:(J=L.usage.cache_read_input_tokens)!=null?J:void 0},request:{body:z},response:{id:(X=L.id)!=null?X:void 0,modelId:(B=L.model)!=null?B:void 0,headers:D,body:N},warnings:j,providerMetadata:{anthropic:{usage:L.usage,cacheCreationInputTokens:(q=L.usage.cache_creation_input_tokens)!=null?q:null,stopSequence:(G=L.stop_sequence)!=null?G:null,container:L.container?{expiresAt:L.container.expires_at,id:L.container.id,skills:(U=(H=L.container.skills)==null?void 0:H.map((M)=>({type:M.type,skillId:M.skill_id,version:M.version})))!=null?U:null}:null}}}}async doStream(Q){let{args:Y,warnings:J,betas:X,usesJsonResponseTool:B}=await this.getArgs(Q),q=this.extractCitationDocuments(Q.prompt),G={...Y,stream:!0},{responseHeaders:H,value:U}=await T0({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:X,headers:Q.headers}),body:this.transformRequestBody(G),failedResponseHandler:EY,successfulResponseHandler:D1(d2),abortSignal:Q.abortSignal,fetch:this.config.fetch}),z="unknown",j={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},A={},V=void 0,F=null,D=null,L=null,N=void 0,K=this.generateId;return{stream:U.pipeThrough(new TransformStream({start(M){M.enqueue({type:"stream-start",warnings:J})},transform(M,w){var _,g,S,C,T,b,k,I,E,R;if(Q.includeRawChunks)w.enqueue({type:"raw",rawValue:M.rawValue});if(!M.success){w.enqueue({type:"error",error:M.error});return}let Z=M.value;switch(Z.type){case"ping":return;case"content_block_start":{let v=Z.content_block.type;switch(N=v,v){case"text":{A[Z.index]={type:"text"},w.enqueue({type:"text-start",id:String(Z.index)});return}case"thinking":{A[Z.index]={type:"reasoning"},w.enqueue({type:"reasoning-start",id:String(Z.index)});return}case"redacted_thinking":{A[Z.index]={type:"reasoning"},w.enqueue({type:"reasoning-start",id:String(Z.index),providerMetadata:{anthropic:{redactedData:Z.content_block.data}}});return}case"tool_use":{A[Z.index]=B?{type:"text"}:{type:"tool-call",toolCallId:Z.content_block.id,toolName:Z.content_block.name,input:"",firstDelta:!0},w.enqueue(B?{type:"text-start",id:String(Z.index)}:{type:"tool-input-start",id:Z.content_block.id,toolName:Z.content_block.name});return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(Z.content_block.name)){A[Z.index]={type:"tool-call",toolCallId:Z.content_block.id,toolName:Z.content_block.name,input:"",providerExecuted:!0,firstDelta:!0};let y=Z.content_block.name==="text_editor_code_execution"||Z.content_block.name==="bash_code_execution"?"code_execution":Z.content_block.name;w.enqueue({type:"tool-input-start",id:Z.content_block.id,toolName:y,providerExecuted:!0})}return}case"web_fetch_tool_result":{let y=Z.content_block;if(y.content.type==="web_fetch_result")w.enqueue({type:"tool-result",toolCallId:y.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:y.content.url,retrievedAt:y.content.retrieved_at,content:{type:y.content.content.type,title:y.content.content.title,citations:y.content.content.citations,source:{type:y.content.content.source.type,mediaType:y.content.content.source.media_type,data:y.content.content.source.data}}}});else if(y.content.type==="web_fetch_tool_result_error")w.enqueue({type:"tool-result",toolCallId:y.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:y.content.error_code},providerExecuted:!0});return}case"web_search_tool_result":{let y=Z.content_block;if(Array.isArray(y.content)){w.enqueue({type:"tool-result",toolCallId:y.tool_use_id,toolName:"web_search",result:y.content.map((m)=>{var i;return{url:m.url,title:m.title,pageAge:(i=m.page_age)!=null?i:null,encryptedContent:m.encrypted_content,type:m.type}}),providerExecuted:!0});for(let m of y.content)w.enqueue({type:"source",sourceType:"url",id:K(),url:m.url,title:m.title,providerMetadata:{anthropic:{pageAge:(_=m.page_age)!=null?_:null}}})}else w.enqueue({type:"tool-result",toolCallId:y.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:y.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{let y=Z.content_block;if(y.content.type==="code_execution_result")w.enqueue({type:"tool-result",toolCallId:y.tool_use_id,toolName:"code_execution",result:{type:y.content.type,stdout:y.content.stdout,stderr:y.content.stderr,return_code:y.content.return_code},providerExecuted:!0});else if(y.content.type==="code_execution_tool_result_error")w.enqueue({type:"tool-result",toolCallId:y.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:y.content.error_code},providerExecuted:!0});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{let y=Z.content_block;w.enqueue({type:"tool-result",toolCallId:y.tool_use_id,toolName:"code_execution",result:y.content,providerExecuted:!0});return}default:throw Error(`Unsupported content block type: ${v}`)}}case"content_block_stop":{if(A[Z.index]!=null){let v=A[Z.index];switch(v.type){case"text":{w.enqueue({type:"text-end",id:String(Z.index)});break}case"reasoning":{w.enqueue({type:"reasoning-end",id:String(Z.index)});break}case"tool-call":if(!B){w.enqueue({type:"tool-input-end",id:v.toolCallId});let y=v.toolName==="text_editor_code_execution"||v.toolName==="bash_code_execution"?"code_execution":v.toolName;w.enqueue({type:"tool-call",toolCallId:v.toolCallId,toolName:y,input:v.input,providerExecuted:v.providerExecuted})}break}delete A[Z.index]}N=void 0;return}case"content_block_delta":{let v=Z.delta.type;switch(v){case"text_delta":{if(B)return;w.enqueue({type:"text-delta",id:String(Z.index),delta:Z.delta.text});return}case"thinking_delta":{w.enqueue({type:"reasoning-delta",id:String(Z.index),delta:Z.delta.thinking});return}case"signature_delta":{if(N==="thinking")w.enqueue({type:"reasoning-delta",id:String(Z.index),delta:"",providerMetadata:{anthropic:{signature:Z.delta.signature}}});return}case"input_json_delta":{let y=A[Z.index],m=Z.delta.partial_json;if(m.length===0)return;if(B){if((y==null?void 0:y.type)!=="text")return;w.enqueue({type:"text-delta",id:String(Z.index),delta:m})}else{if((y==null?void 0:y.type)!=="tool-call")return;if(y.firstDelta&&(y.toolName==="bash_code_execution"||y.toolName==="text_editor_code_execution"))m=`{"type": "${y.toolName}",${m.substring(1)}`;w.enqueue({type:"tool-input-delta",id:y.toolCallId,delta:m}),y.input+=m,y.firstDelta=!1}return}case"citations_delta":{let y=Z.delta.citation,m=CY(y,q,K);if(m)w.enqueue(m);return}default:throw Error(`Unsupported delta type: ${v}`)}}case"message_start":{j.inputTokens=Z.message.usage.input_tokens,j.cachedInputTokens=(g=Z.message.usage.cache_read_input_tokens)!=null?g:void 0,V={...Z.message.usage},F=(S=Z.message.usage.cache_creation_input_tokens)!=null?S:null,w.enqueue({type:"response-metadata",id:(C=Z.message.id)!=null?C:void 0,modelId:(T=Z.message.model)!=null?T:void 0});return}case"message_delta":{j.outputTokens=Z.usage.output_tokens,j.totalTokens=((b=j.inputTokens)!=null?b:0)+((k=Z.usage.output_tokens)!=null?k:0),z=IY({finishReason:Z.delta.stop_reason,isJsonResponseFromTool:B}),D=(I=Z.delta.stop_sequence)!=null?I:null,L=Z.delta.container!=null?{expiresAt:Z.delta.container.expires_at,id:Z.delta.container.id,skills:(R=(E=Z.delta.container.skills)==null?void 0:E.map((v)=>({type:v.type,skillId:v.skill_id,version:v.version})))!=null?R:null}:null,V={...V,...Z.usage};return}case"message_stop":{w.enqueue({type:"finish",finishReason:z,usage:j,providerMetadata:{anthropic:{usage:V!=null?V:null,cacheCreationInputTokens:F,stopSequence:D,container:L}}});return}case"error":{w.enqueue({type:"error",error:Z.error});return}default:throw Error(`Unsupported chunk type: ${Z}`)}}})),request:{body:G},response:{headers:H}}}};function M7(Q){if(Q.includes("claude-sonnet-4-")||Q.includes("claude-3-7-sonnet")||Q.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,knownModel:!0};else if(Q.includes("claude-opus-4-"))return{maxOutputTokens:32000,knownModel:!0};else if(Q.includes("claude-3-5-haiku"))return{maxOutputTokens:8192,knownModel:!0};else if(Q.includes("claude-3-haiku"))return{maxOutputTokens:4096,knownModel:!0};else return{maxOutputTokens:4096,knownModel:!1}}var A7=J0(()=>p(W.object({command:W.string(),restart:W.boolean().optional()}))),V7=Y1({id:"anthropic.bash_20241022",name:"bash",inputSchema:A7}),D7=J0(()=>p(W.object({command:W.string(),restart:W.boolean().optional()}))),w7=Y1({id:"anthropic.bash_20250124",name:"bash",inputSchema:D7}),O7=J0(()=>p(W.object({action:W.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:W.array(W.number().int()).optional(),text:W.string().optional()}))),R7=Y1({id:"anthropic.computer_20241022",name:"computer",inputSchema:O7}),Z7=J0(()=>p(W.object({action:W.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:W.tuple([W.number().int(),W.number().int()]).optional(),duration:W.number().optional(),scroll_amount:W.number().optional(),scroll_direction:W.enum(["up","down","left","right"]).optional(),start_coordinate:W.tuple([W.number().int(),W.number().int()]).optional(),text:W.string().optional()}))),E7=Y1({id:"anthropic.computer_20250124",name:"computer",inputSchema:Z7}),P7=J0(()=>p(W.discriminatedUnion("command",[W.object({command:W.literal("view"),path:W.string(),view_range:W.tuple([W.number(),W.number()]).optional()}),W.object({command:W.literal("create"),path:W.string(),file_text:W.string()}),W.object({command:W.literal("str_replace"),path:W.string(),old_str:W.string(),new_str:W.string()}),W.object({command:W.literal("insert"),path:W.string(),insert_line:W.number(),insert_text:W.string()}),W.object({command:W.literal("delete"),path:W.string()}),W.object({command:W.literal("rename"),old_path:W.string(),new_path:W.string()})]))),S7=Y1({id:"anthropic.memory_20250818",name:"memory",inputSchema:P7}),I7=J0(()=>p(W.object({command:W.enum(["view","create","str_replace","insert","undo_edit"]),path:W.string(),file_text:W.string().optional(),insert_line:W.number().int().optional(),new_str:W.string().optional(),old_str:W.string().optional(),view_range:W.array(W.number().int()).optional()}))),C7=Y1({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:I7}),b7=J0(()=>p(W.object({command:W.enum(["view","create","str_replace","insert","undo_edit"]),path:W.string(),file_text:W.string().optional(),insert_line:W.number().int().optional(),new_str:W.string().optional(),old_str:W.string().optional(),view_range:W.array(W.number().int()).optional()}))),T7=Y1({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:b7}),_7=J0(()=>p(W.object({command:W.enum(["view","create","str_replace","insert"]),path:W.string(),file_text:W.string().optional(),insert_line:W.number().int().optional(),new_str:W.string().optional(),old_str:W.string().optional(),view_range:W.array(W.number().int()).optional()}))),k7=Y1({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:_7}),v7={bash_20241022:V7,bash_20250124:w7,codeExecution_20250522:H7,codeExecution_20250825:L7,computer_20241022:R7,computer_20250124:E7,memory_20250818:S7,textEditor_20241022:C7,textEditor_20250124:T7,textEditor_20250429:k7,textEditor_20250728:o2,webFetch_20250910:W7,webSearch_20250305:Q7};function x7(Q={}){var Y;let J=(Y=w9(PQ({settingValue:Q.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?Y:"https://api.anthropic.com/v1",X=()=>i1({"anthropic-version":"2023-06-01","x-api-key":J8({apiKey:Q.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...Q.headers},`ai-sdk/anthropic/${m2}`),B=(G)=>{var H;return new K7(G,{provider:"anthropic.messages",baseURL:J,headers:X,fetch:Q.fetch,generateId:(H=Q.generateId)!=null?H:s0,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},q=function(G){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return B(G)};return q.languageModel=B,q.chat=B,q.messages=B,q.textEmbeddingModel=(G)=>{throw new M9({modelId:G,modelType:"textEmbeddingModel"})},q.imageModel=(G)=>{throw new M9({modelId:G,modelType:"imageModel"})},q.tools=v7,q}var vY=x7();var MX=null;async function g7(){if(MX)return MX;try{let Q=await fetch("https://models.dev/api.json",{headers:{"User-Agent":"sylphx-flow/1.0"}});if(!Q.ok)throw Error(`Failed to fetch models.dev: ${Q.status}`);let Y=await Q.json(),J=new Map;for(let X of Y.models)J.set(X.id,{id:X.id,name:X.name,contextLength:X.context_length,maxOutput:X.max_output,inputPrice:X.pricing?.input,outputPrice:X.pricing?.output,provider:X.provider,description:X.description});return MX=J,J}catch(Q){return console.error("Failed to fetch models.dev:",Q),new Map}}async function O9(Q){return(await g7()).get(Q)||null}var y7=[{id:"claude-3-5-sonnet-20241022",name:"Claude 3.5 Sonnet (Latest)"},{id:"claude-3-5-haiku-20241022",name:"Claude 3.5 Haiku"},{id:"claude-3-opus-20240229",name:"Claude 3 Opus"},{id:"claude-3-sonnet-20240229",name:"Claude 3 Sonnet"},{id:"claude-3-haiku-20240307",name:"Claude 3 Haiku"}],xY={"claude-3-5-sonnet-20241022":{contextLength:200000,maxOutput:8192},"claude-3-5-haiku-20241022":{contextLength:200000,maxOutput:8192},"claude-3-opus-20240229":{contextLength:200000,maxOutput:4096},"claude-3-sonnet-20240229":{contextLength:200000,maxOutput:4096},"claude-3-haiku-20240307":{contextLength:200000,maxOutput:4096}};class AX{id="anthropic";name="Anthropic";getConfigSchema(){return[{key:"api-key",label:"API Key",type:"string",required:!0,secret:!0,description:"Get your API key from https://console.anthropic.com",placeholder:"sk-ant-..."}]}isConfigured(Q){return!!Q["api-key"]}async fetchModels(Q){return y7}async getModelDetails(Q,Y){if(xY[Q])return xY[Q];let J=await O9(Q);if(J)return{contextLength:J.contextLength,maxOutput:J.maxOutput,inputPrice:J.inputPrice,outputPrice:J.outputPrice};return null}createClient(Q,Y){return vY(Y,{apiKey:Q["api-key"]})}}var VX=W.object({error:W.object({message:W.string(),type:W.string().nullish(),param:W.any().nullish(),code:W.union([W.string(),W.number()]).nullish()})}),a1=V1({errorSchema:VX,errorToMessage:(Q)=>Q.error.message});function $7({prompt:Q,systemMessageMode:Y="system"}){let J=[],X=[];for(let{role:B,content:q}of Q)switch(B){case"system":{switch(Y){case"system":{J.push({role:"system",content:q});break}case"developer":{J.push({role:"developer",content:q});break}case"remove":{X.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${Y}`)}break}case"user":{if(q.length===1&&q[0].type==="text"){J.push({role:"user",content:q[0].text});break}J.push({role:"user",content:q.map((G,H)=>{var U,z,j;switch(G.type){case"text":return{type:"text",text:G.text};case"file":if(G.mediaType.startsWith("image/")){let A=G.mediaType==="image/*"?"image/jpeg":G.mediaType;return{type:"image_url",image_url:{url:G.data instanceof URL?G.data.toString():`data:${A};base64,${F1(G.data)}`,detail:(z=(U=G.providerOptions)==null?void 0:U.openai)==null?void 0:z.imageDetail}}}else if(G.mediaType.startsWith("audio/")){if(G.data instanceof URL)throw new I0({functionality:"audio file parts with URLs"});switch(G.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:F1(G.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:F1(G.data),format:"mp3"}};default:throw new I0({functionality:`audio content parts with media type ${G.mediaType}`})}}else if(G.mediaType==="application/pdf"){if(G.data instanceof URL)throw new I0({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof G.data==="string"&&G.data.startsWith("file-")?{file_id:G.data}:{filename:(j=G.filename)!=null?j:`part-${H}.pdf`,file_data:`data:application/pdf;base64,${F1(G.data)}`}}}else throw new I0({functionality:`file part media type ${G.mediaType}`})}})});break}case"assistant":{let G="",H=[];for(let U of q)switch(U.type){case"text":{G+=U.text;break}case"tool-call":{H.push({id:U.toolCallId,type:"function",function:{name:U.toolName,arguments:JSON.stringify(U.input)}});break}}J.push({role:"assistant",content:G,tool_calls:H.length>0?H:void 0});break}case"tool":{for(let G of q){let H=G.output,U;switch(H.type){case"text":case"error-text":U=H.value;break;case"content":case"json":case"error-json":U=JSON.stringify(H.value);break}J.push({role:"tool",tool_call_id:G.toolCallId,content:U})}break}default:throw Error(`Unsupported role: ${B}`)}return{messages:J,warnings:X}}function gY({id:Q,model:Y,created:J}){return{id:Q!=null?Q:void 0,modelId:Y!=null?Y:void 0,timestamp:J!=null?new Date(J*1000):void 0}}function yY(Q){switch(Q){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 f7=d0(()=>p(W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({message:W.object({role:W.literal("assistant").nullish(),content:W.string().nullish(),tool_calls:W.array(W.object({id:W.string().nullish(),type:W.literal("function"),function:W.object({name:W.string(),arguments:W.string()})})).nullish(),annotations:W.array(W.object({type:W.literal("url_citation"),start_index:W.number(),end_index:W.number(),url:W.string(),title:W.string()})).nullish()}),index:W.number(),logprobs:W.object({content:W.array(W.object({token:W.string(),logprob:W.number(),top_logprobs:W.array(W.object({token:W.string(),logprob:W.number()}))})).nullish()}).nullish(),finish_reason:W.string().nullish()})),usage:W.object({prompt_tokens:W.number().nullish(),completion_tokens:W.number().nullish(),total_tokens:W.number().nullish(),prompt_tokens_details:W.object({cached_tokens:W.number().nullish()}).nullish(),completion_tokens_details:W.object({reasoning_tokens:W.number().nullish(),accepted_prediction_tokens:W.number().nullish(),rejected_prediction_tokens:W.number().nullish()}).nullish()}).nullish()}))),h7=d0(()=>p(W.union([W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({delta:W.object({role:W.enum(["assistant"]).nullish(),content:W.string().nullish(),tool_calls:W.array(W.object({index:W.number(),id:W.string().nullish(),type:W.literal("function").nullish(),function:W.object({name:W.string().nullish(),arguments:W.string().nullish()})})).nullish(),annotations:W.array(W.object({type:W.literal("url_citation"),start_index:W.number(),end_index:W.number(),url:W.string(),title:W.string()})).nullish()}).nullish(),logprobs:W.object({content:W.array(W.object({token:W.string(),logprob:W.number(),top_logprobs:W.array(W.object({token:W.string(),logprob:W.number()}))})).nullish()}).nullish(),finish_reason:W.string().nullish(),index:W.number()})),usage:W.object({prompt_tokens:W.number().nullish(),completion_tokens:W.number().nullish(),total_tokens:W.number().nullish(),prompt_tokens_details:W.object({cached_tokens:W.number().nullish()}).nullish(),completion_tokens_details:W.object({reasoning_tokens:W.number().nullish(),accepted_prediction_tokens:W.number().nullish(),rejected_prediction_tokens:W.number().nullish()}).nullish()}).nullish()}),VX]))),m7=d0(()=>p(W.object({logitBias:W.record(W.coerce.number(),W.number()).optional(),logprobs:W.union([W.boolean(),W.number()]).optional(),parallelToolCalls:W.boolean().optional(),user:W.string().optional(),reasoningEffort:W.enum(["minimal","low","medium","high"]).optional(),maxCompletionTokens:W.number().optional(),store:W.boolean().optional(),metadata:W.record(W.string().max(64),W.string().max(512)).optional(),prediction:W.record(W.string(),W.any()).optional(),structuredOutputs:W.boolean().optional(),serviceTier:W.enum(["auto","flex","priority","default"]).optional(),strictJsonSchema:W.boolean().optional(),textVerbosity:W.enum(["low","medium","high"]).optional(),promptCacheKey:W.string().optional(),safetyIdentifier:W.string().optional()})));function u7({tools:Q,toolChoice:Y,structuredOutputs:J,strictJsonSchema:X}){Q=(Q==null?void 0:Q.length)?Q:void 0;let B=[];if(Q==null)return{tools:void 0,toolChoice:void 0,toolWarnings:B};let q=[];for(let H of Q)switch(H.type){case"function":q.push({type:"function",function:{name:H.name,description:H.description,parameters:H.inputSchema,strict:J?X:void 0}});break;default:B.push({type:"unsupported-tool",tool:H});break}if(Y==null)return{tools:q,toolChoice:void 0,toolWarnings:B};let G=Y.type;switch(G){case"auto":case"none":case"required":return{tools:q,toolChoice:G,toolWarnings:B};case"tool":return{tools:q,toolChoice:{type:"function",function:{name:Y.toolName}},toolWarnings:B};default:throw new I0({functionality:`tool choice type: ${G}`})}}var c7=class{constructor(Q,Y){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Q,this.config=Y}get provider(){return this.config.provider}async getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,topK:B,frequencyPenalty:q,presencePenalty:G,stopSequences:H,responseFormat:U,seed:z,tools:j,toolChoice:A,providerOptions:V}){var F,D,L,N;let K=[],M=(F=await k0({provider:"openai",providerOptions:V,schema:m7}))!=null?F:{},w=(D=M.structuredOutputs)!=null?D:!0;if(B!=null)K.push({type:"unsupported-setting",setting:"topK"});if((U==null?void 0:U.type)==="json"&&U.schema!=null&&!w)K.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let{messages:_,warnings:g}=$7({prompt:Q,systemMessageMode:p7(this.modelId)});K.push(...g);let S=(L=M.strictJsonSchema)!=null?L:!1,C={model:this.modelId,logit_bias:M.logitBias,logprobs:M.logprobs===!0||typeof M.logprobs==="number"?!0:void 0,top_logprobs:typeof M.logprobs==="number"?M.logprobs:typeof M.logprobs==="boolean"?M.logprobs?0:void 0:void 0,user:M.user,parallel_tool_calls:M.parallelToolCalls,max_tokens:Y,temperature:J,top_p:X,frequency_penalty:q,presence_penalty:G,response_format:(U==null?void 0:U.type)==="json"?w&&U.schema!=null?{type:"json_schema",json_schema:{schema:U.schema,strict:S,name:(N=U.name)!=null?N:"response",description:U.description}}:{type:"json_object"}:void 0,stop:H,seed:z,verbosity:M.textVerbosity,max_completion_tokens:M.maxCompletionTokens,store:M.store,metadata:M.metadata,prediction:M.prediction,reasoning_effort:M.reasoningEffort,service_tier:M.serviceTier,prompt_cache_key:M.promptCacheKey,safety_identifier:M.safetyIdentifier,messages:_};if(pY(this.modelId)){if(C.temperature!=null)C.temperature=void 0,K.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"});if(C.top_p!=null)C.top_p=void 0,K.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"});if(C.frequency_penalty!=null)C.frequency_penalty=void 0,K.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"});if(C.presence_penalty!=null)C.presence_penalty=void 0,K.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"});if(C.logit_bias!=null)C.logit_bias=void 0,K.push({type:"other",message:"logitBias is not supported for reasoning models"});if(C.logprobs!=null)C.logprobs=void 0,K.push({type:"other",message:"logprobs is not supported for reasoning models"});if(C.top_logprobs!=null)C.top_logprobs=void 0,K.push({type:"other",message:"topLogprobs is not supported for reasoning models"});if(C.max_tokens!=null){if(C.max_completion_tokens==null)C.max_completion_tokens=C.max_tokens;C.max_tokens=void 0}}else if(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview")){if(C.temperature!=null)C.temperature=void 0,K.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})}if(M.serviceTier==="flex"&&!d7(this.modelId))K.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),C.service_tier=void 0;if(M.serviceTier==="priority"&&!l7(this.modelId))K.push({type:"unsupported-setting",setting:"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"}),C.service_tier=void 0;let{tools:T,toolChoice:b,toolWarnings:k}=u7({tools:j,toolChoice:A,structuredOutputs:w,strictJsonSchema:S});return{args:{...C,tools:T,tool_choice:b},warnings:[...K,...k]}}async doGenerate(Q){var Y,J,X,B,q,G,H,U,z,j,A,V,F,D;let{args:L,warnings:N}=await this.getArgs(Q),{responseHeaders:K,value:M,rawValue:w}=await T0({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:L,failedResponseHandler:a1,successfulResponseHandler:m0(f7),abortSignal:Q.abortSignal,fetch:this.config.fetch}),_=M.choices[0],g=[],S=_.message.content;if(S!=null&&S.length>0)g.push({type:"text",text:S});for(let k of(Y=_.message.tool_calls)!=null?Y:[])g.push({type:"tool-call",toolCallId:(J=k.id)!=null?J:s0(),toolName:k.function.name,input:k.function.arguments});for(let k of(X=_.message.annotations)!=null?X:[])g.push({type:"source",sourceType:"url",id:s0(),url:k.url,title:k.title});let C=(B=M.usage)==null?void 0:B.completion_tokens_details,T=(q=M.usage)==null?void 0:q.prompt_tokens_details,b={openai:{}};if((C==null?void 0:C.accepted_prediction_tokens)!=null)b.openai.acceptedPredictionTokens=C==null?void 0:C.accepted_prediction_tokens;if((C==null?void 0:C.rejected_prediction_tokens)!=null)b.openai.rejectedPredictionTokens=C==null?void 0:C.rejected_prediction_tokens;if(((G=_.logprobs)==null?void 0:G.content)!=null)b.openai.logprobs=_.logprobs.content;return{content:g,finishReason:yY(_.finish_reason),usage:{inputTokens:(U=(H=M.usage)==null?void 0:H.prompt_tokens)!=null?U:void 0,outputTokens:(j=(z=M.usage)==null?void 0:z.completion_tokens)!=null?j:void 0,totalTokens:(V=(A=M.usage)==null?void 0:A.total_tokens)!=null?V:void 0,reasoningTokens:(F=C==null?void 0:C.reasoning_tokens)!=null?F:void 0,cachedInputTokens:(D=T==null?void 0:T.cached_tokens)!=null?D:void 0},request:{body:L},response:{...gY(M),headers:K,body:w},warnings:N,providerMetadata:b}}async doStream(Q){let{args:Y,warnings:J}=await this.getArgs(Q),X={...Y,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:B,value:q}=await T0({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:X,failedResponseHandler:a1,successfulResponseHandler:D1(h7),abortSignal:Q.abortSignal,fetch:this.config.fetch}),G=[],H="unknown",U={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},z=!0,j=!1,A={openai:{}};return{stream:q.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:J})},transform(V,F){var D,L,N,K,M,w,_,g,S,C,T,b,k,I,E,R,Z,v,y,m,i,l,r,d;if(Q.includeRawChunks)F.enqueue({type:"raw",rawValue:V.rawValue});if(!V.success){H="error",F.enqueue({type:"error",error:V.error});return}let t=V.value;if("error"in t){H="error",F.enqueue({type:"error",error:t.error});return}if(z)z=!1,F.enqueue({type:"response-metadata",...gY(t)});if(t.usage!=null){if(U.inputTokens=(D=t.usage.prompt_tokens)!=null?D:void 0,U.outputTokens=(L=t.usage.completion_tokens)!=null?L:void 0,U.totalTokens=(N=t.usage.total_tokens)!=null?N:void 0,U.reasoningTokens=(M=(K=t.usage.completion_tokens_details)==null?void 0:K.reasoning_tokens)!=null?M:void 0,U.cachedInputTokens=(_=(w=t.usage.prompt_tokens_details)==null?void 0:w.cached_tokens)!=null?_:void 0,((g=t.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null)A.openai.acceptedPredictionTokens=(S=t.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens;if(((C=t.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens)!=null)A.openai.rejectedPredictionTokens=(T=t.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens}let Q0=t.choices[0];if((Q0==null?void 0:Q0.finish_reason)!=null)H=yY(Q0.finish_reason);if(((b=Q0==null?void 0:Q0.logprobs)==null?void 0:b.content)!=null)A.openai.logprobs=Q0.logprobs.content;if((Q0==null?void 0:Q0.delta)==null)return;let $=Q0.delta;if($.content!=null){if(!j)F.enqueue({type:"text-start",id:"0"}),j=!0;F.enqueue({type:"text-delta",id:"0",delta:$.content})}if($.tool_calls!=null)for(let H0 of $.tool_calls){let E0=H0.index;if(G[E0]==null){if(H0.type!=="function")throw new _9({data:H0,message:"Expected 'function' type."});if(H0.id==null)throw new _9({data:H0,message:"Expected 'id' to be a string."});if(((k=H0.function)==null?void 0:k.name)==null)throw new _9({data:H0,message:"Expected 'function.name' to be a string."});F.enqueue({type:"tool-input-start",id:H0.id,toolName:H0.function.name}),G[E0]={id:H0.id,type:"function",function:{name:H0.function.name,arguments:(I=H0.function.arguments)!=null?I:""},hasFinished:!1};let h=G[E0];if(((E=h.function)==null?void 0:E.name)!=null&&((R=h.function)==null?void 0:R.arguments)!=null){if(h.function.arguments.length>0)F.enqueue({type:"tool-input-delta",id:h.id,delta:h.function.arguments});if(W8(h.function.arguments))F.enqueue({type:"tool-input-end",id:h.id}),F.enqueue({type:"tool-call",toolCallId:(Z=h.id)!=null?Z:s0(),toolName:h.function.name,input:h.function.arguments}),h.hasFinished=!0}continue}let M0=G[E0];if(M0.hasFinished)continue;if(((v=H0.function)==null?void 0:v.arguments)!=null)M0.function.arguments+=(m=(y=H0.function)==null?void 0:y.arguments)!=null?m:"";if(F.enqueue({type:"tool-input-delta",id:M0.id,delta:(i=H0.function.arguments)!=null?i:""}),((l=M0.function)==null?void 0:l.name)!=null&&((r=M0.function)==null?void 0:r.arguments)!=null&&W8(M0.function.arguments))F.enqueue({type:"tool-input-end",id:M0.id}),F.enqueue({type:"tool-call",toolCallId:(d=M0.id)!=null?d:s0(),toolName:M0.function.name,input:M0.function.arguments}),M0.hasFinished=!0}if($.annotations!=null)for(let H0 of $.annotations)F.enqueue({type:"source",sourceType:"url",id:s0(),url:H0.url,title:H0.title})},flush(V){if(j)V.enqueue({type:"text-end",id:"0"});V.enqueue({type:"finish",finishReason:H,usage:U,...A!=null?{providerMetadata:A}:{}})}})),request:{body:X},response:{headers:B}}}};function pY(Q){return(Q.startsWith("o")||Q.startsWith("gpt-5"))&&!Q.startsWith("gpt-5-chat")}function d7(Q){return Q.startsWith("o3")||Q.startsWith("o4-mini")||Q.startsWith("gpt-5")&&!Q.startsWith("gpt-5-chat")}function l7(Q){return Q.startsWith("gpt-4")||Q.startsWith("gpt-5-mini")||Q.startsWith("gpt-5")&&!Q.startsWith("gpt-5-nano")&&!Q.startsWith("gpt-5-chat")||Q.startsWith("o3")||Q.startsWith("o4-mini")}function p7(Q){var Y,J;if(!pY(Q))return"system";return(J=(Y=n7[Q])==null?void 0:Y.systemMessageMode)!=null?J:"developer"}var n7={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function i7({prompt:Q,user:Y="user",assistant:J="assistant"}){let X="";if(Q[0].role==="system")X+=`${Q[0].content}
12
-
13
- `,Q=Q.slice(1);for(let{role:B,content:q}of Q)switch(B){case"system":throw new jQ({message:"Unexpected system message in prompt: ${content}",prompt:Q});case"user":{let G=q.map((H)=>{switch(H.type){case"text":return H.text}}).filter(Boolean).join("");X+=`${Y}:
14
- ${G}
15
-
16
- `;break}case"assistant":{let G=q.map((H)=>{switch(H.type){case"text":return H.text;case"tool-call":throw new I0({functionality:"tool-call messages"})}}).join("");X+=`${J}:
17
- ${G}
18
-
19
- `;break}case"tool":throw new I0({functionality:"tool messages"});default:throw Error(`Unsupported role: ${B}`)}return X+=`${J}:
20
- `,{prompt:X,stopSequences:[`
21
- ${Y}:`]}}function $Y({id:Q,model:Y,created:J}){return{id:Q!=null?Q:void 0,modelId:Y!=null?Y:void 0,timestamp:J!=null?new Date(J*1000):void 0}}function fY(Q){switch(Q){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 a7=d0(()=>p(W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({text:W.string(),finish_reason:W.string(),logprobs:W.object({tokens:W.array(W.string()),token_logprobs:W.array(W.number()),top_logprobs:W.array(W.record(W.string(),W.number())).nullish()}).nullish()})),usage:W.object({prompt_tokens:W.number(),completion_tokens:W.number(),total_tokens:W.number()}).nullish()}))),s7=d0(()=>p(W.union([W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({text:W.string(),finish_reason:W.string().nullish(),index:W.number(),logprobs:W.object({tokens:W.array(W.string()),token_logprobs:W.array(W.number()),top_logprobs:W.array(W.record(W.string(),W.number())).nullish()}).nullish()})),usage:W.object({prompt_tokens:W.number(),completion_tokens:W.number(),total_tokens:W.number()}).nullish()}),VX]))),hY=d0(()=>p(W.object({echo:W.boolean().optional(),logitBias:W.record(W.string(),W.number()).optional(),suffix:W.string().optional(),user:W.string().optional(),logprobs:W.union([W.boolean(),W.number()]).optional()}))),o7=class{constructor(Q,Y){this.specificationVersion="v2",this.supportedUrls={},this.modelId=Q,this.config=Y}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,topK:B,frequencyPenalty:q,presencePenalty:G,stopSequences:H,responseFormat:U,tools:z,toolChoice:j,seed:A,providerOptions:V}){let F=[],D={...await k0({provider:"openai",providerOptions:V,schema:hY}),...await k0({provider:this.providerOptionsName,providerOptions:V,schema:hY})};if(B!=null)F.push({type:"unsupported-setting",setting:"topK"});if(z==null?void 0:z.length)F.push({type:"unsupported-setting",setting:"tools"});if(j!=null)F.push({type:"unsupported-setting",setting:"toolChoice"});if(U!=null&&U.type!=="text")F.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:L,stopSequences:N}=i7({prompt:Q}),K=[...N!=null?N:[],...H!=null?H:[]];return{args:{model:this.modelId,echo:D.echo,logit_bias:D.logitBias,logprobs:(D==null?void 0:D.logprobs)===!0?0:(D==null?void 0:D.logprobs)===!1?void 0:D==null?void 0:D.logprobs,suffix:D.suffix,user:D.user,max_tokens:Y,temperature:J,top_p:X,frequency_penalty:q,presence_penalty:G,seed:A,prompt:L,stop:K.length>0?K:void 0},warnings:F}}async doGenerate(Q){var Y,J,X;let{args:B,warnings:q}=await this.getArgs(Q),{responseHeaders:G,value:H,rawValue:U}=await T0({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:B,failedResponseHandler:a1,successfulResponseHandler:m0(a7),abortSignal:Q.abortSignal,fetch:this.config.fetch}),z=H.choices[0],j={openai:{}};if(z.logprobs!=null)j.openai.logprobs=z.logprobs;return{content:[{type:"text",text:z.text}],usage:{inputTokens:(Y=H.usage)==null?void 0:Y.prompt_tokens,outputTokens:(J=H.usage)==null?void 0:J.completion_tokens,totalTokens:(X=H.usage)==null?void 0:X.total_tokens},finishReason:fY(z.finish_reason),request:{body:B},response:{...$Y(H),headers:G,body:U},providerMetadata:j,warnings:q}}async doStream(Q){let{args:Y,warnings:J}=await this.getArgs(Q),X={...Y,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:B,value:q}=await T0({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:X,failedResponseHandler:a1,successfulResponseHandler:D1(s7),abortSignal:Q.abortSignal,fetch:this.config.fetch}),G="unknown",H={openai:{}},U={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},z=!0;return{stream:q.pipeThrough(new TransformStream({start(j){j.enqueue({type:"stream-start",warnings:J})},transform(j,A){if(Q.includeRawChunks)A.enqueue({type:"raw",rawValue:j.rawValue});if(!j.success){G="error",A.enqueue({type:"error",error:j.error});return}let V=j.value;if("error"in V){G="error",A.enqueue({type:"error",error:V.error});return}if(z)z=!1,A.enqueue({type:"response-metadata",...$Y(V)}),A.enqueue({type:"text-start",id:"0"});if(V.usage!=null)U.inputTokens=V.usage.prompt_tokens,U.outputTokens=V.usage.completion_tokens,U.totalTokens=V.usage.total_tokens;let F=V.choices[0];if((F==null?void 0:F.finish_reason)!=null)G=fY(F.finish_reason);if((F==null?void 0:F.logprobs)!=null)H.openai.logprobs=F.logprobs;if((F==null?void 0:F.text)!=null&&F.text.length>0)A.enqueue({type:"text-delta",id:"0",delta:F.text})},flush(j){if(!z)j.enqueue({type:"text-end",id:"0"});j.enqueue({type:"finish",finishReason:G,providerMetadata:H,usage:U})}})),request:{body:X},response:{headers:B}}}},r7=d0(()=>p(W.object({dimensions:W.number().optional(),user:W.string().optional()}))),t7=d0(()=>p(W.object({data:W.array(W.object({embedding:W.array(W.number())})),usage:W.object({prompt_tokens:W.number()}).nullish()}))),e7=class{constructor(Q,Y){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=Q,this.config=Y}get provider(){return this.config.provider}async doEmbed({values:Q,headers:Y,abortSignal:J,providerOptions:X}){var B;if(Q.length>this.maxEmbeddingsPerCall)throw new s9({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Q});let q=(B=await k0({provider:"openai",providerOptions:X,schema:r7}))!=null?B:{},{responseHeaders:G,value:H,rawValue:U}=await T0({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:b0(this.config.headers(),Y),body:{model:this.modelId,input:Q,encoding_format:"float",dimensions:q.dimensions,user:q.user},failedResponseHandler:a1,successfulResponseHandler:m0(t7),abortSignal:J,fetch:this.config.fetch});return{embeddings:H.data.map((z)=>z.embedding),usage:H.usage?{tokens:H.usage.prompt_tokens}:void 0,response:{headers:G,body:U}}}},QG=d0(()=>p(W.object({data:W.array(W.object({b64_json:W.string(),revised_prompt:W.string().nullish()}))}))),XG={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},YG=new Set(["gpt-image-1","gpt-image-1-mini"]),JG=class{constructor(Q,Y){this.modelId=Q,this.config=Y,this.specificationVersion="v2"}get maxImagesPerCall(){var Q;return(Q=XG[this.modelId])!=null?Q:1}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:Y,size:J,aspectRatio:X,seed:B,providerOptions:q,headers:G,abortSignal:H}){var U,z,j,A;let V=[];if(X!=null)V.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."});if(B!=null)V.push({type:"unsupported-setting",setting:"seed"});let F=(j=(z=(U=this.config._internal)==null?void 0:U.currentDate)==null?void 0:z.call(U))!=null?j:new Date,{value:D,responseHeaders:L}=await T0({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:b0(this.config.headers(),G),body:{model:this.modelId,prompt:Q,n:Y,size:J,...(A=q.openai)!=null?A:{},...!YG.has(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:a1,successfulResponseHandler:m0(QG),abortSignal:H,fetch:this.config.fetch});return{images:D.data.map((N)=>N.b64_json),warnings:V,response:{timestamp:F,modelId:this.modelId,headers:L},providerMetadata:{openai:{images:D.data.map((N)=>N.revised_prompt?{revisedPrompt:N.revised_prompt}:null)}}}}},WG=J0(()=>p(W.object({code:W.string().nullish(),containerId:W.string()}))),GG=J0(()=>p(W.object({outputs:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("logs"),logs:W.string()}),W.object({type:W.literal("image"),url:W.string()})])).nullish()}))),BG=J0(()=>p(W.object({container:W.union([W.string(),W.object({fileIds:W.array(W.string()).optional()})]).optional()}))),qG=J1({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:WG,outputSchema:GG}),HG=(Q={})=>{return qG(Q)},nY=W.object({key:W.string(),type:W.enum(["eq","ne","gt","gte","lt","lte"]),value:W.union([W.string(),W.number(),W.boolean()])}),iY=W.object({type:W.enum(["and","or"]),filters:W.array(W.union([nY,W.lazy(()=>iY)]))}),zG=J0(()=>p(W.object({vectorStoreIds:W.array(W.string()),maxNumResults:W.number().optional(),ranking:W.object({ranker:W.string().optional(),scoreThreshold:W.number().optional()}).optional(),filters:W.union([nY,iY]).optional()}))),UG=J0(()=>p(W.object({queries:W.array(W.string()),results:W.array(W.object({attributes:W.record(W.string(),W.unknown()),fileId:W.string(),filename:W.string(),score:W.number(),text:W.string()})).nullable()}))),LG=J1({id:"openai.file_search",name:"file_search",inputSchema:W.object({}),outputSchema:UG}),FG=J0(()=>p(W.object({background:W.enum(["auto","opaque","transparent"]).optional(),inputFidelity:W.enum(["low","high"]).optional(),inputImageMask:W.object({fileId:W.string().optional(),imageUrl:W.string().optional()}).optional(),model:W.string().optional(),moderation:W.enum(["auto"]).optional(),outputCompression:W.number().int().min(0).max(100).optional(),outputFormat:W.enum(["png","jpeg","webp"]).optional(),partialImages:W.number().int().min(0).max(3).optional(),quality:W.enum(["auto","low","medium","high"]).optional(),size:W.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),NG=J0(()=>p(W.object({}))),jG=J0(()=>p(W.object({result:W.string()}))),KG=J1({id:"openai.image_generation",name:"image_generation",inputSchema:NG,outputSchema:jG}),MG=(Q={})=>{return KG(Q)},aY=J0(()=>p(W.object({action:W.object({type:W.literal("exec"),command:W.array(W.string()),timeoutMs:W.number().optional(),user:W.string().optional(),workingDirectory:W.string().optional(),env:W.record(W.string(),W.string()).optional()})}))),sY=J0(()=>p(W.object({output:W.string()}))),AG=J1({id:"openai.local_shell",name:"local_shell",inputSchema:aY,outputSchema:sY}),VG=J0(()=>p(W.object({filters:W.object({allowedDomains:W.array(W.string()).optional()}).optional(),searchContextSize:W.enum(["low","medium","high"]).optional(),userLocation:W.object({type:W.literal("approximate"),country:W.string().optional(),city:W.string().optional(),region:W.string().optional(),timezone:W.string().optional()}).optional()}))),DG=J0(()=>p(W.object({}))),wG=J0(()=>p(W.object({action:W.discriminatedUnion("type",[W.object({type:W.literal("search"),query:W.string().optional()}),W.object({type:W.literal("openPage"),url:W.string()}),W.object({type:W.literal("find"),url:W.string(),pattern:W.string()})]),sources:W.array(W.object({type:W.literal("url"),url:W.string()})).optional()}))),OG=J1({id:"openai.web_search",name:"web_search",inputSchema:DG,outputSchema:wG}),RG=(Q={})=>OG(Q),ZG=J0(()=>p(W.object({searchContextSize:W.enum(["low","medium","high"]).optional(),userLocation:W.object({type:W.literal("approximate"),country:W.string().optional(),city:W.string().optional(),region:W.string().optional(),timezone:W.string().optional()}).optional()}))),EG=J0(()=>p(W.object({}))),PG=J0(()=>p(W.object({action:W.discriminatedUnion("type",[W.object({type:W.literal("search"),query:W.string().optional()}),W.object({type:W.literal("openPage"),url:W.string()}),W.object({type:W.literal("find"),url:W.string(),pattern:W.string()})])}))),SG=J1({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:EG,outputSchema:PG}),IG={codeInterpreter:HG,fileSearch:LG,imageGeneration:MG,localShell:AG,webSearchPreview:SG,webSearch:RG};function mY(Q,Y){if(!Y)return!1;return Y.some((J)=>Q.startsWith(J))}async function CG({prompt:Q,systemMessageMode:Y,fileIdPrefixes:J,store:X,hasLocalShellTool:B=!1}){var q,G,H,U;let z=[],j=[];for(let{role:A,content:V}of Q)switch(A){case"system":{switch(Y){case"system":{z.push({role:"system",content:V});break}case"developer":{z.push({role:"developer",content:V});break}case"remove":{j.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${Y}`)}break}case"user":{z.push({role:"user",content:V.map((F,D)=>{var L,N,K;switch(F.type){case"text":return{type:"input_text",text:F.text};case"file":if(F.mediaType.startsWith("image/")){let M=F.mediaType==="image/*"?"image/jpeg":F.mediaType;return{type:"input_image",...F.data instanceof URL?{image_url:F.data.toString()}:typeof F.data==="string"&&mY(F.data,J)?{file_id:F.data}:{image_url:`data:${M};base64,${F1(F.data)}`},detail:(N=(L=F.providerOptions)==null?void 0:L.openai)==null?void 0:N.imageDetail}}else if(F.mediaType==="application/pdf"){if(F.data instanceof URL)return{type:"input_file",file_url:F.data.toString()};return{type:"input_file",...typeof F.data==="string"&&mY(F.data,J)?{file_id:F.data}:{filename:(K=F.filename)!=null?K:`part-${D}.pdf`,file_data:`data:application/pdf;base64,${F1(F.data)}`}}}else throw new I0({functionality:`file part media type ${F.mediaType}`})}})});break}case"assistant":{let F={},D={};for(let L of V)switch(L.type){case"text":{let N=(G=(q=L.providerOptions)==null?void 0:q.openai)==null?void 0:G.itemId;if(X&&N!=null){z.push({type:"item_reference",id:N});break}z.push({role:"assistant",content:[{type:"output_text",text:L.text}],id:N});break}case"tool-call":{if(D[L.toolCallId]=L,L.providerExecuted)break;let N=(U=(H=L.providerOptions)==null?void 0:H.openai)==null?void 0:U.itemId;if(X&&N!=null){z.push({type:"item_reference",id:N});break}if(B&&L.toolName==="local_shell"){let K=await q1({value:L.input,schema:aY});z.push({type:"local_shell_call",call_id:L.toolCallId,id:N,action:{type:"exec",command:K.action.command,timeout_ms:K.action.timeoutMs,user:K.action.user,working_directory:K.action.workingDirectory,env:K.action.env}});break}z.push({type:"function_call",call_id:L.toolCallId,name:L.toolName,arguments:JSON.stringify(L.input),id:N});break}case"tool-result":{if(X)z.push({type:"item_reference",id:L.toolCallId});else j.push({type:"other",message:`Results for OpenAI tool ${L.toolName} are not sent to the API when store is false`});break}case"reasoning":{let N=await k0({provider:"openai",providerOptions:L.providerOptions,schema:bG}),K=N==null?void 0:N.itemId;if(K!=null){let M=F[K];if(X){if(M===void 0)z.push({type:"item_reference",id:K}),F[K]={type:"reasoning",id:K,summary:[]}}else{let w=[];if(L.text.length>0)w.push({type:"summary_text",text:L.text});else if(M!==void 0)j.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(L)}.`});if(M===void 0)F[K]={type:"reasoning",id:K,encrypted_content:N==null?void 0:N.reasoningEncryptedContent,summary:w},z.push(F[K]);else if(M.summary.push(...w),(N==null?void 0:N.reasoningEncryptedContent)!=null)M.encrypted_content=N.reasoningEncryptedContent}}else j.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(L)}.`});break}}break}case"tool":{for(let F of V){let D=F.output;if(B&&F.toolName==="local_shell"&&D.type==="json"){let N=await q1({value:D.value,schema:sY});z.push({type:"local_shell_call_output",call_id:F.toolCallId,output:N.output});break}let L;switch(D.type){case"text":case"error-text":L=D.value;break;case"json":case"error-json":L=JSON.stringify(D.value);break;case"content":L=D.value.map((N)=>{switch(N.type){case"text":return{type:"input_text",text:N.text};case"media":return N.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${N.mediaType};base64,${N.data}`}:{type:"input_file",filename:"data",file_data:`data:${N.mediaType};base64,${N.data}`}}});break}z.push({type:"function_call_output",call_id:F.toolCallId,output:L})}break}default:throw Error(`Unsupported role: ${A}`)}return{input:z,warnings:j}}var bG=W.object({itemId:W.string().nullish(),reasoningEncryptedContent:W.string().nullish()});function uY({finishReason:Q,hasFunctionCall:Y}){switch(Q){case void 0:case null:return Y?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return Y?"tool-calls":"unknown"}}var TG=d0(()=>p(W.union([W.object({type:W.literal("response.output_text.delta"),item_id:W.string(),delta:W.string(),logprobs:W.array(W.object({token:W.string(),logprob:W.number(),top_logprobs:W.array(W.object({token:W.string(),logprob:W.number()}))})).nullish()}),W.object({type:W.enum(["response.completed","response.incomplete"]),response:W.object({incomplete_details:W.object({reason:W.string()}).nullish(),usage:W.object({input_tokens:W.number(),input_tokens_details:W.object({cached_tokens:W.number().nullish()}).nullish(),output_tokens:W.number(),output_tokens_details:W.object({reasoning_tokens:W.number().nullish()}).nullish()}),service_tier:W.string().nullish()})}),W.object({type:W.literal("response.created"),response:W.object({id:W.string(),created_at:W.number(),model:W.string(),service_tier:W.string().nullish()})}),W.object({type:W.literal("response.output_item.added"),output_index:W.number(),item:W.discriminatedUnion("type",[W.object({type:W.literal("message"),id:W.string()}),W.object({type:W.literal("reasoning"),id:W.string(),encrypted_content:W.string().nullish()}),W.object({type:W.literal("function_call"),id:W.string(),call_id:W.string(),name:W.string(),arguments:W.string()}),W.object({type:W.literal("web_search_call"),id:W.string(),status:W.string()}),W.object({type:W.literal("computer_call"),id:W.string(),status:W.string()}),W.object({type:W.literal("file_search_call"),id:W.string()}),W.object({type:W.literal("image_generation_call"),id:W.string()}),W.object({type:W.literal("code_interpreter_call"),id:W.string(),container_id:W.string(),code:W.string().nullable(),outputs:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("logs"),logs:W.string()}),W.object({type:W.literal("image"),url:W.string()})])).nullable(),status:W.string()})])}),W.object({type:W.literal("response.output_item.done"),output_index:W.number(),item:W.discriminatedUnion("type",[W.object({type:W.literal("message"),id:W.string()}),W.object({type:W.literal("reasoning"),id:W.string(),encrypted_content:W.string().nullish()}),W.object({type:W.literal("function_call"),id:W.string(),call_id:W.string(),name:W.string(),arguments:W.string(),status:W.literal("completed")}),W.object({type:W.literal("code_interpreter_call"),id:W.string(),code:W.string().nullable(),container_id:W.string(),outputs:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("logs"),logs:W.string()}),W.object({type:W.literal("image"),url:W.string()})])).nullable()}),W.object({type:W.literal("image_generation_call"),id:W.string(),result:W.string()}),W.object({type:W.literal("web_search_call"),id:W.string(),status:W.string(),action:W.discriminatedUnion("type",[W.object({type:W.literal("search"),query:W.string().nullish(),sources:W.array(W.object({type:W.literal("url"),url:W.string()})).nullish()}),W.object({type:W.literal("open_page"),url:W.string()}),W.object({type:W.literal("find"),url:W.string(),pattern:W.string()})])}),W.object({type:W.literal("file_search_call"),id:W.string(),queries:W.array(W.string()),results:W.array(W.object({attributes:W.record(W.string(),W.unknown()),file_id:W.string(),filename:W.string(),score:W.number(),text:W.string()})).nullish()}),W.object({type:W.literal("local_shell_call"),id:W.string(),call_id:W.string(),action:W.object({type:W.literal("exec"),command:W.array(W.string()),timeout_ms:W.number().optional(),user:W.string().optional(),working_directory:W.string().optional(),env:W.record(W.string(),W.string()).optional()})}),W.object({type:W.literal("computer_call"),id:W.string(),status:W.literal("completed")})])}),W.object({type:W.literal("response.function_call_arguments.delta"),item_id:W.string(),output_index:W.number(),delta:W.string()}),W.object({type:W.literal("response.image_generation_call.partial_image"),item_id:W.string(),output_index:W.number(),partial_image_b64:W.string()}),W.object({type:W.literal("response.code_interpreter_call_code.delta"),item_id:W.string(),output_index:W.number(),delta:W.string()}),W.object({type:W.literal("response.code_interpreter_call_code.done"),item_id:W.string(),output_index:W.number(),code:W.string()}),W.object({type:W.literal("response.output_text.annotation.added"),annotation:W.discriminatedUnion("type",[W.object({type:W.literal("url_citation"),url:W.string(),title:W.string()}),W.object({type:W.literal("file_citation"),file_id:W.string(),filename:W.string().nullish(),index:W.number().nullish(),start_index:W.number().nullish(),end_index:W.number().nullish(),quote:W.string().nullish()})])}),W.object({type:W.literal("response.reasoning_summary_part.added"),item_id:W.string(),summary_index:W.number()}),W.object({type:W.literal("response.reasoning_summary_text.delta"),item_id:W.string(),summary_index:W.number(),delta:W.string()}),W.object({type:W.literal("response.reasoning_summary_part.done"),item_id:W.string(),summary_index:W.number()}),W.object({type:W.literal("error"),code:W.string(),message:W.string(),param:W.string().nullish(),sequence_number:W.number()}),W.object({type:W.string()}).loose().transform((Q)=>({type:"unknown_chunk",message:Q.type}))]))),_G=d0(()=>p(W.object({id:W.string(),created_at:W.number(),error:W.object({code:W.string(),message:W.string()}).nullish(),model:W.string(),output:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("message"),role:W.literal("assistant"),id:W.string(),content:W.array(W.object({type:W.literal("output_text"),text:W.string(),logprobs:W.array(W.object({token:W.string(),logprob:W.number(),top_logprobs:W.array(W.object({token:W.string(),logprob:W.number()}))})).nullish(),annotations:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("url_citation"),start_index:W.number(),end_index:W.number(),url:W.string(),title:W.string()}),W.object({type:W.literal("file_citation"),file_id:W.string(),filename:W.string().nullish(),index:W.number().nullish(),start_index:W.number().nullish(),end_index:W.number().nullish(),quote:W.string().nullish()}),W.object({type:W.literal("container_file_citation")})]))}))}),W.object({type:W.literal("web_search_call"),id:W.string(),status:W.string(),action:W.discriminatedUnion("type",[W.object({type:W.literal("search"),query:W.string().nullish(),sources:W.array(W.object({type:W.literal("url"),url:W.string()})).nullish()}),W.object({type:W.literal("open_page"),url:W.string()}),W.object({type:W.literal("find"),url:W.string(),pattern:W.string()})])}),W.object({type:W.literal("file_search_call"),id:W.string(),queries:W.array(W.string()),results:W.array(W.object({attributes:W.record(W.string(),W.unknown()),file_id:W.string(),filename:W.string(),score:W.number(),text:W.string()})).nullish()}),W.object({type:W.literal("code_interpreter_call"),id:W.string(),code:W.string().nullable(),container_id:W.string(),outputs:W.array(W.discriminatedUnion("type",[W.object({type:W.literal("logs"),logs:W.string()}),W.object({type:W.literal("image"),url:W.string()})])).nullable()}),W.object({type:W.literal("image_generation_call"),id:W.string(),result:W.string()}),W.object({type:W.literal("local_shell_call"),id:W.string(),call_id:W.string(),action:W.object({type:W.literal("exec"),command:W.array(W.string()),timeout_ms:W.number().optional(),user:W.string().optional(),working_directory:W.string().optional(),env:W.record(W.string(),W.string()).optional()})}),W.object({type:W.literal("function_call"),call_id:W.string(),name:W.string(),arguments:W.string(),id:W.string()}),W.object({type:W.literal("computer_call"),id:W.string(),status:W.string().optional()}),W.object({type:W.literal("reasoning"),id:W.string(),encrypted_content:W.string().nullish(),summary:W.array(W.object({type:W.literal("summary_text"),text:W.string()}))})])),service_tier:W.string().nullish(),incomplete_details:W.object({reason:W.string()}).nullish(),usage:W.object({input_tokens:W.number(),input_tokens_details:W.object({cached_tokens:W.number().nullish()}).nullish(),output_tokens:W.number(),output_tokens_details:W.object({reasoning_tokens:W.number().nullish()}).nullish()})}))),oY=20,kG=["o1","o1-2024-12-17","o3-mini","o3-mini-2025-01-31","o3","o3-2025-04-16","o4-mini","o4-mini-2025-04-16","codex-mini-latest","computer-use-preview","gpt-5","gpt-5-2025-08-07","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06"],kA=["gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","gpt-4-0125-preview","gpt-4-1106-preview","gpt-4","gpt-4-0613","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","chatgpt-4o-latest","gpt-5-chat-latest",...kG],vG=d0(()=>p(W.object({include:W.array(W.enum(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:W.string().nullish(),logprobs:W.union([W.boolean(),W.number().min(1).max(oY)]).optional(),maxToolCalls:W.number().nullish(),metadata:W.any().nullish(),parallelToolCalls:W.boolean().nullish(),previousResponseId:W.string().nullish(),promptCacheKey:W.string().nullish(),reasoningEffort:W.string().nullish(),reasoningSummary:W.string().nullish(),safetyIdentifier:W.string().nullish(),serviceTier:W.enum(["auto","flex","priority","default"]).nullish(),store:W.boolean().nullish(),strictJsonSchema:W.boolean().nullish(),textVerbosity:W.enum(["low","medium","high"]).nullish(),truncation:W.enum(["auto","disabled"]).nullish(),user:W.string().nullish()})));async function xG({tools:Q,toolChoice:Y,strictJsonSchema:J}){Q=(Q==null?void 0:Q.length)?Q:void 0;let X=[];if(Q==null)return{tools:void 0,toolChoice:void 0,toolWarnings:X};let B=[];for(let G of Q)switch(G.type){case"function":B.push({type:"function",name:G.name,description:G.description,parameters:G.inputSchema,strict:J});break;case"provider-defined":{switch(G.id){case"openai.file_search":{let H=await q1({value:G.args,schema:zG});B.push({type:"file_search",vector_store_ids:H.vectorStoreIds,max_num_results:H.maxNumResults,ranking_options:H.ranking?{ranker:H.ranking.ranker,score_threshold:H.ranking.scoreThreshold}:void 0,filters:H.filters});break}case"openai.local_shell":{B.push({type:"local_shell"});break}case"openai.web_search_preview":{let H=await q1({value:G.args,schema:ZG});B.push({type:"web_search_preview",search_context_size:H.searchContextSize,user_location:H.userLocation});break}case"openai.web_search":{let H=await q1({value:G.args,schema:VG});B.push({type:"web_search",filters:H.filters!=null?{allowed_domains:H.filters.allowedDomains}:void 0,search_context_size:H.searchContextSize,user_location:H.userLocation});break}case"openai.code_interpreter":{let H=await q1({value:G.args,schema:BG});B.push({type:"code_interpreter",container:H.container==null?{type:"auto",file_ids:void 0}:typeof H.container==="string"?H.container:{type:"auto",file_ids:H.container.fileIds}});break}case"openai.image_generation":{let H=await q1({value:G.args,schema:FG});B.push({type:"image_generation",background:H.background,input_fidelity:H.inputFidelity,input_image_mask:H.inputImageMask?{file_id:H.inputImageMask.fileId,image_url:H.inputImageMask.imageUrl}:void 0,model:H.model,size:H.size,quality:H.quality,moderation:H.moderation,output_format:H.outputFormat,output_compression:H.outputCompression});break}}break}default:X.push({type:"unsupported-tool",tool:G});break}if(Y==null)return{tools:B,toolChoice:void 0,toolWarnings:X};let q=Y.type;switch(q){case"auto":case"none":case"required":return{tools:B,toolChoice:q,toolWarnings:X};case"tool":return{tools:B,toolChoice:Y.toolName==="code_interpreter"||Y.toolName==="file_search"||Y.toolName==="image_generation"||Y.toolName==="web_search_preview"||Y.toolName==="web_search"?{type:Y.toolName}:{type:"function",name:Y.toolName},toolWarnings:X};default:throw new I0({functionality:`tool choice type: ${q}`})}}var gG=class{constructor(Q,Y){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=Q,this.config=Y}get provider(){return this.config.provider}async getArgs({maxOutputTokens:Q,temperature:Y,stopSequences:J,topP:X,topK:B,presencePenalty:q,frequencyPenalty:G,seed:H,prompt:U,providerOptions:z,tools:j,toolChoice:A,responseFormat:V}){var F,D,L,N;let K=[],M=pG(this.modelId);if(B!=null)K.push({type:"unsupported-setting",setting:"topK"});if(H!=null)K.push({type:"unsupported-setting",setting:"seed"});if(q!=null)K.push({type:"unsupported-setting",setting:"presencePenalty"});if(G!=null)K.push({type:"unsupported-setting",setting:"frequencyPenalty"});if(J!=null)K.push({type:"unsupported-setting",setting:"stopSequences"});let w=await k0({provider:"openai",providerOptions:z,schema:vG}),{input:_,warnings:g}=await CG({prompt:U,systemMessageMode:M.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(F=w==null?void 0:w.store)!=null?F:!0,hasLocalShellTool:b("openai.local_shell")});K.push(...g);let S=(D=w==null?void 0:w.strictJsonSchema)!=null?D:!1,C=w==null?void 0:w.include;function T(m){if(C==null)C=[m];else if(!C.includes(m))C=[...C,m]}function b(m){return(j==null?void 0:j.find((i)=>i.type==="provider-defined"&&i.id===m))!=null}let k=typeof(w==null?void 0:w.logprobs)==="number"?w==null?void 0:w.logprobs:(w==null?void 0:w.logprobs)===!0?oY:void 0;if(k)T("message.output_text.logprobs");let I=(L=j==null?void 0:j.find((m)=>m.type==="provider-defined"&&(m.id==="openai.web_search"||m.id==="openai.web_search_preview")))==null?void 0:L.name;if(I)T("web_search_call.action.sources");if(b("openai.code_interpreter"))T("code_interpreter_call.outputs");let E=w==null?void 0:w.store;if(E===!1&&M.isReasoningModel)T("reasoning.encrypted_content");let R={model:this.modelId,input:_,temperature:Y,top_p:X,max_output_tokens:Q,...((V==null?void 0:V.type)==="json"||(w==null?void 0:w.textVerbosity))&&{text:{...(V==null?void 0:V.type)==="json"&&{format:V.schema!=null?{type:"json_schema",strict:S,name:(N=V.name)!=null?N:"response",description:V.description,schema:V.schema}:{type:"json_object"}},...(w==null?void 0:w.textVerbosity)&&{verbosity:w.textVerbosity}}},max_tool_calls:w==null?void 0:w.maxToolCalls,metadata:w==null?void 0:w.metadata,parallel_tool_calls:w==null?void 0:w.parallelToolCalls,previous_response_id:w==null?void 0:w.previousResponseId,store:E,user:w==null?void 0:w.user,instructions:w==null?void 0:w.instructions,service_tier:w==null?void 0:w.serviceTier,include:C,prompt_cache_key:w==null?void 0:w.promptCacheKey,safety_identifier:w==null?void 0:w.safetyIdentifier,top_logprobs:k,truncation:w==null?void 0:w.truncation,...M.isReasoningModel&&((w==null?void 0:w.reasoningEffort)!=null||(w==null?void 0:w.reasoningSummary)!=null)&&{reasoning:{...(w==null?void 0:w.reasoningEffort)!=null&&{effort:w.reasoningEffort},...(w==null?void 0:w.reasoningSummary)!=null&&{summary:w.reasoningSummary}}}};if(M.isReasoningModel){if(R.temperature!=null)R.temperature=void 0,K.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"});if(R.top_p!=null)R.top_p=void 0,K.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})}else{if((w==null?void 0:w.reasoningEffort)!=null)K.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"});if((w==null?void 0:w.reasoningSummary)!=null)K.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})}if((w==null?void 0:w.serviceTier)==="flex"&&!M.supportsFlexProcessing)K.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete R.service_tier;if((w==null?void 0:w.serviceTier)==="priority"&&!M.supportsPriorityProcessing)K.push({type:"unsupported-setting",setting:"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 R.service_tier;let{tools:Z,toolChoice:v,toolWarnings:y}=await xG({tools:j,toolChoice:A,strictJsonSchema:S});return{webSearchToolName:I,args:{...R,tools:Z,tool_choice:v},warnings:[...K,...y],store:E}}async doGenerate(Q){var Y,J,X,B,q,G,H,U,z,j,A,V,F,D,L,N,K,M,w;let{args:_,warnings:g,webSearchToolName:S}=await this.getArgs(Q),C=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:T,value:b,rawValue:k}=await T0({url:C,headers:b0(this.config.headers(),Q.headers),body:_,failedResponseHandler:a1,successfulResponseHandler:m0(_G),abortSignal:Q.abortSignal,fetch:this.config.fetch});if(b.error)throw new a0({message:b.error.message,url:C,requestBodyValues:_,statusCode:400,responseHeaders:T,responseBody:k,isRetryable:!1});let I=[],E=[],R=!1;for(let v of b.output)switch(v.type){case"reasoning":{if(v.summary.length===0)v.summary.push({type:"summary_text",text:""});for(let y of v.summary)I.push({type:"reasoning",text:y.text,providerMetadata:{openai:{itemId:v.id,reasoningEncryptedContent:(Y=v.encrypted_content)!=null?Y:null}}});break}case"image_generation_call":{I.push({type:"tool-call",toolCallId:v.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:v.id,toolName:"image_generation",result:{result:v.result},providerExecuted:!0});break}case"local_shell_call":{I.push({type:"tool-call",toolCallId:v.call_id,toolName:"local_shell",input:JSON.stringify({action:v.action}),providerMetadata:{openai:{itemId:v.id}}});break}case"message":{for(let y of v.content){if(((X=(J=Q.providerOptions)==null?void 0:J.openai)==null?void 0:X.logprobs)&&y.logprobs)E.push(y.logprobs);I.push({type:"text",text:y.text,providerMetadata:{openai:{itemId:v.id}}});for(let m of y.annotations)if(m.type==="url_citation")I.push({type:"source",sourceType:"url",id:(G=(q=(B=this.config).generateId)==null?void 0:q.call(B))!=null?G:s0(),url:m.url,title:m.title});else if(m.type==="file_citation")I.push({type:"source",sourceType:"document",id:(z=(U=(H=this.config).generateId)==null?void 0:U.call(H))!=null?z:s0(),mediaType:"text/plain",title:(A=(j=m.quote)!=null?j:m.filename)!=null?A:"Document",filename:(V=m.filename)!=null?V:m.file_id,...m.file_id?{providerMetadata:{openai:{fileId:m.file_id}}}:{}})}break}case"function_call":{R=!0,I.push({type:"tool-call",toolCallId:v.call_id,toolName:v.name,input:v.arguments,providerMetadata:{openai:{itemId:v.id}}});break}case"web_search_call":{I.push({type:"tool-call",toolCallId:v.id,toolName:S!=null?S:"web_search",input:JSON.stringify({}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:v.id,toolName:S!=null?S:"web_search",result:dY(v.action),providerExecuted:!0});break}case"computer_call":{I.push({type:"tool-call",toolCallId:v.id,toolName:"computer_use",input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:v.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:v.status||"completed"},providerExecuted:!0});break}case"file_search_call":{I.push({type:"tool-call",toolCallId:v.id,toolName:"file_search",input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:v.id,toolName:"file_search",result:{queries:v.queries,results:(D=(F=v.results)==null?void 0:F.map((y)=>({attributes:y.attributes,fileId:y.file_id,filename:y.filename,score:y.score,text:y.text})))!=null?D:null},providerExecuted:!0});break}case"code_interpreter_call":{I.push({type:"tool-call",toolCallId:v.id,toolName:"code_interpreter",input:JSON.stringify({code:v.code,containerId:v.container_id}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:v.id,toolName:"code_interpreter",result:{outputs:v.outputs},providerExecuted:!0});break}}let Z={openai:{responseId:b.id}};if(E.length>0)Z.openai.logprobs=E;if(typeof b.service_tier==="string")Z.openai.serviceTier=b.service_tier;return{content:I,finishReason:uY({finishReason:(L=b.incomplete_details)==null?void 0:L.reason,hasFunctionCall:R}),usage:{inputTokens:b.usage.input_tokens,outputTokens:b.usage.output_tokens,totalTokens:b.usage.input_tokens+b.usage.output_tokens,reasoningTokens:(K=(N=b.usage.output_tokens_details)==null?void 0:N.reasoning_tokens)!=null?K:void 0,cachedInputTokens:(w=(M=b.usage.input_tokens_details)==null?void 0:M.cached_tokens)!=null?w:void 0},request:{body:_},response:{id:b.id,timestamp:new Date(b.created_at*1000),modelId:b.model,headers:T,body:k},providerMetadata:Z,warnings:g}}async doStream(Q){let{args:Y,warnings:J,webSearchToolName:X,store:B}=await this.getArgs(Q),{responseHeaders:q,value:G}=await T0({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:{...Y,stream:!0},failedResponseHandler:a1,successfulResponseHandler:D1(TG),abortSignal:Q.abortSignal,fetch:this.config.fetch}),H=this,U="unknown",z={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},j=[],A=null,V={},F=!1,D={},L;return{stream:G.pipeThrough(new TransformStream({start(N){N.enqueue({type:"stream-start",warnings:J})},transform(N,K){var M,w,_,g,S,C,T,b,k,I,E,R,Z,v,y,m,i,l,r,d,t,Q0;if(Q.includeRawChunks)K.enqueue({type:"raw",rawValue:N.rawValue});if(!N.success){U="error",K.enqueue({type:"error",error:N.error});return}let $=N.value;if(cY($)){if($.item.type==="function_call")V[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},K.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="web_search_call")V[$.output_index]={toolName:X!=null?X:"web_search",toolCallId:$.item.id},K.enqueue({type:"tool-input-start",id:$.item.id,toolName:X!=null?X:"web_search",providerExecuted:!0}),K.enqueue({type:"tool-input-end",id:$.item.id}),K.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"web_search",input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")V[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},K.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0});else if($.item.type==="code_interpreter_call")V[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},K.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),K.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")K.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")K.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0});else if($.item.type==="message")K.enqueue({type:"text-start",id:$.item.id,providerMetadata:{openai:{itemId:$.item.id}}});else if(cY($)&&$.item.type==="reasoning")D[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},K.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{openai:{itemId:$.item.id,reasoningEncryptedContent:(M=$.item.encrypted_content)!=null?M:null}}})}else if($G($)){if($.item.type==="function_call")V[$.output_index]=void 0,F=!0,K.enqueue({type:"tool-input-end",id:$.item.call_id}),K.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{openai:{itemId:$.item.id}}});else if($.item.type==="web_search_call")V[$.output_index]=void 0,K.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"web_search",result:dY($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")V[$.output_index]=void 0,K.enqueue({type:"tool-input-end",id:$.item.id}),K.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),K.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")V[$.output_index]=void 0,K.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(_=(w=$.item.results)==null?void 0:w.map((H0)=>({attributes:H0.attributes,fileId:H0.file_id,filename:H0.filename,score:H0.score,text:H0.text})))!=null?_:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")V[$.output_index]=void 0,K.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")K.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")V[$.output_index]=void 0,K.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{openai:{itemId:$.item.id}}});else if($.item.type==="message")K.enqueue({type:"text-end",id:$.item.id});else if($.item.type==="reasoning"){let H0=D[$.item.id],E0=Object.entries(H0.summaryParts).filter(([M0,h])=>h==="active"||h==="can-conclude").map(([M0])=>M0);for(let M0 of E0)K.enqueue({type:"reasoning-end",id:`${$.item.id}:${M0}`,providerMetadata:{openai:{itemId:$.item.id,reasoningEncryptedContent:(g=$.item.encrypted_content)!=null?g:null}}});delete D[$.item.id]}}else if(mG($)){let H0=V[$.output_index];if(H0!=null)K.enqueue({type:"tool-input-delta",id:H0.toolCallId,delta:$.delta})}else if(uG($)){let H0=V[$.output_index];if(H0!=null)K.enqueue({type:"tool-input-delta",id:H0.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(cG($)){let H0=V[$.output_index];if(H0!=null)K.enqueue({type:"tool-input-delta",id:H0.toolCallId,delta:'"}'}),K.enqueue({type:"tool-input-end",id:H0.toolCallId}),K.enqueue({type:"tool-call",toolCallId:H0.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:H0.codeInterpreter.containerId}),providerExecuted:!0})}else if(hG($))A=$.response.id,K.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1000),modelId:$.response.model});else if(yG($)){if(K.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),((C=(S=Q.providerOptions)==null?void 0:S.openai)==null?void 0:C.logprobs)&&$.logprobs)j.push($.logprobs)}else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){let H0=D[$.item_id];H0.summaryParts[$.summary_index]="active";for(let E0 of Object.keys(H0.summaryParts))if(H0.summaryParts[E0]==="can-conclude")K.enqueue({type:"reasoning-end",id:`${$.item_id}:${E0}`,providerMetadata:{openai:{itemId:$.item_id}}}),H0.summaryParts[E0]="concluded";K.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{openai:{itemId:$.item_id,reasoningEncryptedContent:(b=(T=D[$.item_id])==null?void 0:T.encryptedContent)!=null?b:null}}})}}else if($.type==="response.reasoning_summary_text.delta")K.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{openai:{itemId:$.item_id}}});else if($.type==="response.reasoning_summary_part.done")if(B)K.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{openai:{itemId:$.item_id}}}),D[$.item_id].summaryParts[$.summary_index]="concluded";else D[$.item_id].summaryParts[$.summary_index]="can-conclude";else if(fG($)){if(U=uY({finishReason:(k=$.response.incomplete_details)==null?void 0:k.reason,hasFunctionCall:F}),z.inputTokens=$.response.usage.input_tokens,z.outputTokens=$.response.usage.output_tokens,z.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,z.reasoningTokens=(E=(I=$.response.usage.output_tokens_details)==null?void 0:I.reasoning_tokens)!=null?E:void 0,z.cachedInputTokens=(Z=(R=$.response.usage.input_tokens_details)==null?void 0:R.cached_tokens)!=null?Z:void 0,typeof $.response.service_tier==="string")L=$.response.service_tier}else if(dG($)){if($.annotation.type==="url_citation")K.enqueue({type:"source",sourceType:"url",id:(m=(y=(v=H.config).generateId)==null?void 0:y.call(v))!=null?m:s0(),url:$.annotation.url,title:$.annotation.title});else if($.annotation.type==="file_citation")K.enqueue({type:"source",sourceType:"document",id:(r=(l=(i=H.config).generateId)==null?void 0:l.call(i))!=null?r:s0(),mediaType:"text/plain",title:(t=(d=$.annotation.quote)!=null?d:$.annotation.filename)!=null?t:"Document",filename:(Q0=$.annotation.filename)!=null?Q0:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{openai:{fileId:$.annotation.file_id}}}:{}})}else if(lG($))K.enqueue({type:"error",error:$})},flush(N){let K={openai:{responseId:A}};if(j.length>0)K.openai.logprobs=j;if(L!==void 0)K.openai.serviceTier=L;N.enqueue({type:"finish",finishReason:U,usage:z,providerMetadata:K})}})),request:{body:Y},response:{headers:q}}}};function yG(Q){return Q.type==="response.output_text.delta"}function $G(Q){return Q.type==="response.output_item.done"}function fG(Q){return Q.type==="response.completed"||Q.type==="response.incomplete"}function hG(Q){return Q.type==="response.created"}function mG(Q){return Q.type==="response.function_call_arguments.delta"}function uG(Q){return Q.type==="response.code_interpreter_call_code.delta"}function cG(Q){return Q.type==="response.code_interpreter_call_code.done"}function cY(Q){return Q.type==="response.output_item.added"}function dG(Q){return Q.type==="response.output_text.annotation.added"}function lG(Q){return Q.type==="error"}function pG(Q){let Y=Q.startsWith("o3")||Q.startsWith("o4-mini")||Q.startsWith("gpt-5")&&!Q.startsWith("gpt-5-chat"),J=Q.startsWith("gpt-4")||Q.startsWith("gpt-5-mini")||Q.startsWith("gpt-5")&&!Q.startsWith("gpt-5-nano")&&!Q.startsWith("gpt-5-chat")||Q.startsWith("o3")||Q.startsWith("o4-mini"),X={systemMessageMode:"system",supportsFlexProcessing:Y,supportsPriorityProcessing:J};if(Q.startsWith("gpt-5-chat"))return{...X,isReasoningModel:!1};if(Q.startsWith("o")||Q.startsWith("gpt-5")||Q.startsWith("codex-")||Q.startsWith("computer-use")){if(Q.startsWith("o1-mini")||Q.startsWith("o1-preview"))return{...X,isReasoningModel:!0,systemMessageMode:"remove"};return{...X,isReasoningModel:!0,systemMessageMode:"developer"}}return{...X,isReasoningModel:!1}}function dY(Q){var Y;switch(Q.type){case"search":return{action:{type:"search",query:(Y=Q.query)!=null?Y:void 0},...Q.sources!=null&&{sources:Q.sources}};case"open_page":return{action:{type:"openPage",url:Q.url}};case"find":return{action:{type:"find",url:Q.url,pattern:Q.pattern}}}}var nG=d0(()=>p(W.object({instructions:W.string().nullish(),speed:W.number().min(0.25).max(4).default(1).nullish()}))),iG=class{constructor(Q,Y){this.modelId=Q,this.config=Y,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:Q,voice:Y="alloy",outputFormat:J="mp3",speed:X,instructions:B,language:q,providerOptions:G}){let H=[],U=await k0({provider:"openai",providerOptions:G,schema:nG}),z={model:this.modelId,input:Q,voice:Y,response_format:"mp3",speed:X,instructions:B};if(J)if(["mp3","opus","aac","flac","wav","pcm"].includes(J))z.response_format=J;else H.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${J}. Using mp3 instead.`});if(U){let j={};for(let A in j){let V=j[A];if(V!==void 0)z[A]=V}}if(q)H.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${q}" was ignored.`});return{requestBody:z,warnings:H}}async doGenerate(Q){var Y,J,X;let B=(X=(J=(Y=this.config._internal)==null?void 0:Y.currentDate)==null?void 0:J.call(Y))!=null?X:new Date,{requestBody:q,warnings:G}=await this.getArgs(Q),{value:H,responseHeaders:U,rawValue:z}=await T0({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:q,failedResponseHandler:a1,successfulResponseHandler:VY(),abortSignal:Q.abortSignal,fetch:this.config.fetch});return{audio:H,warnings:G,request:{body:JSON.stringify(q)},response:{timestamp:B,modelId:this.modelId,headers:U,body:z}}}},aG=d0(()=>p(W.object({text:W.string(),language:W.string().nullish(),duration:W.number().nullish(),words:W.array(W.object({word:W.string(),start:W.number(),end:W.number()})).nullish(),segments:W.array(W.object({id:W.number(),seek:W.number(),start:W.number(),end:W.number(),text:W.string(),tokens:W.array(W.number()),temperature:W.number(),avg_logprob:W.number(),compression_ratio:W.number(),no_speech_prob:W.number()})).nullish()}))),sG=d0(()=>p(W.object({include:W.array(W.string()).optional(),language:W.string().optional(),prompt:W.string().optional(),temperature:W.number().min(0).max(1).default(0).optional(),timestampGranularities:W.array(W.enum(["word","segment"])).default(["segment"]).optional()}))),lY={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"},oG=class{constructor(Q,Y){this.modelId=Q,this.config=Y,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:Q,mediaType:Y,providerOptions:J}){let X=[],B=await k0({provider:"openai",providerOptions:J,schema:sG}),q=new FormData,G=Q instanceof Uint8Array?new Blob([Q]):new Blob([ZY(Q)]);q.append("model",this.modelId);let H=NY(Y);if(q.append("file",new File([G],"audio",{type:Y}),`audio.${H}`),B){let U={include:B.include,language:B.language,prompt:B.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:B.temperature,timestamp_granularities:B.timestampGranularities};for(let[z,j]of Object.entries(U))if(j!=null)if(Array.isArray(j))for(let A of j)q.append(`${z}[]`,String(A));else q.append(z,String(j))}return{formData:q,warnings:X}}async doGenerate(Q){var Y,J,X,B,q,G,H,U;let z=(X=(J=(Y=this.config._internal)==null?void 0:Y.currentDate)==null?void 0:J.call(Y))!=null?X:new Date,{formData:j,warnings:A}=await this.getArgs(Q),{value:V,responseHeaders:F,rawValue:D}=await KY({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),formData:j,failedResponseHandler:a1,successfulResponseHandler:m0(aG),abortSignal:Q.abortSignal,fetch:this.config.fetch}),L=V.language!=null&&V.language in lY?lY[V.language]:void 0;return{text:V.text,segments:(H=(G=(B=V.segments)==null?void 0:B.map((N)=>({text:N.text,startSecond:N.start,endSecond:N.end})))!=null?G:(q=V.words)==null?void 0:q.map((N)=>({text:N.word,startSecond:N.start,endSecond:N.end})))!=null?H:[],language:L,durationInSeconds:(U=V.duration)!=null?U:void 0,warnings:A,response:{timestamp:z,modelId:this.modelId,headers:F,body:D}}}},rG="2.0.59";function tG(Q={}){var Y,J;let X=(Y=w9(PQ({settingValue:Q.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?Y:"https://api.openai.com/v1",B=(J=Q.name)!=null?J:"openai",q=()=>i1({Authorization:`Bearer ${J8({apiKey:Q.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":Q.organization,"OpenAI-Project":Q.project,...Q.headers},`ai-sdk/openai/${rG}`),G=(L)=>new c7(L,{provider:`${B}.chat`,url:({path:N})=>`${X}${N}`,headers:q,fetch:Q.fetch}),H=(L)=>new o7(L,{provider:`${B}.completion`,url:({path:N})=>`${X}${N}`,headers:q,fetch:Q.fetch}),U=(L)=>new e7(L,{provider:`${B}.embedding`,url:({path:N})=>`${X}${N}`,headers:q,fetch:Q.fetch}),z=(L)=>new JG(L,{provider:`${B}.image`,url:({path:N})=>`${X}${N}`,headers:q,fetch:Q.fetch}),j=(L)=>new oG(L,{provider:`${B}.transcription`,url:({path:N})=>`${X}${N}`,headers:q,fetch:Q.fetch}),A=(L)=>new iG(L,{provider:`${B}.speech`,url:({path:N})=>`${X}${N}`,headers:q,fetch:Q.fetch}),V=(L)=>{if(new.target)throw Error("The OpenAI model function cannot be called with the new keyword.");return F(L)},F=(L)=>{return new gG(L,{provider:`${B}.responses`,url:({path:N})=>`${X}${N}`,headers:q,fetch:Q.fetch,fileIdPrefixes:["file-"]})},D=function(L){return V(L)};return D.languageModel=V,D.chat=G,D.completion=H,D.responses=F,D.embedding=U,D.textEmbedding=U,D.textEmbeddingModel=U,D.image=z,D.imageModel=z,D.transcription=j,D.transcriptionModel=j,D.speech=A,D.speechModel=A,D.tools=IG,D}var rY=tG();var eG=[{id:"gpt-4o",name:"GPT-4o"},{id:"gpt-4o-mini",name:"GPT-4o Mini"},{id:"gpt-4-turbo",name:"GPT-4 Turbo"},{id:"gpt-4",name:"GPT-4"},{id:"gpt-3.5-turbo",name:"GPT-3.5 Turbo"}],tY={"gpt-4o":{contextLength:128000,maxOutput:16384},"gpt-4o-mini":{contextLength:128000,maxOutput:16384},"gpt-4-turbo":{contextLength:128000,maxOutput:4096},"gpt-4":{contextLength:8192,maxOutput:8192},"gpt-3.5-turbo":{contextLength:16384,maxOutput:4096}};class DX{id="openai";name="OpenAI";getConfigSchema(){return[{key:"api-key",label:"API Key",type:"string",required:!0,secret:!0,description:"Get your API key from https://platform.openai.com",placeholder:"sk-..."},{key:"base-url",label:"Base URL",type:"string",required:!1,description:"Custom API endpoint (for Azure OpenAI, etc.)",placeholder:"https://api.openai.com/v1"}]}isConfigured(Q){return!!Q["api-key"]}async fetchModels(Q){let Y=Q["api-key"];if(!Y)return eG;let J=Q["base-url"]||"https://api.openai.com/v1",X=await fetch(`${J}/models`,{headers:{Authorization:`Bearer ${Y}`},signal:AbortSignal.timeout(1e4)});if(!X.ok)throw Error(`OpenAI API returned ${X.status}: ${X.statusText}`);let q=(await X.json()).data.filter((G)=>G.id.startsWith("gpt-")).map((G)=>({id:G.id,name:G.id}));if(q.length===0)throw Error("No GPT models found in OpenAI API response");return q}async getModelDetails(Q,Y){if(tY[Q])return tY[Q];let J=await O9(Q);if(J)return{contextLength:J.contextLength,maxOutput:J.maxOutput,inputPrice:J.inputPrice,outputPrice:J.outputPrice};return null}createClient(Q,Y){let J=Q["api-key"],X=Q["base-url"];return rY(Y,{apiKey:J,baseURL:X})}}var QB="2.0.26",XB=J0(()=>p(W.object({error:W.object({code:W.number().nullable(),message:W.string(),status:W.string()})}))),s8=V1({errorSchema:XB,errorToMessage:(Q)=>Q.error.message}),YB=J0(()=>p(W.object({outputDimensionality:W.number().optional(),taskType:W.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}))),JB=class{constructor(Q,Y){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=Q,this.config=Y}get provider(){return this.config.provider}async doEmbed({values:Q,headers:Y,abortSignal:J,providerOptions:X}){let B=await k0({provider:"google",providerOptions:X,schema:YB});if(Q.length>this.maxEmbeddingsPerCall)throw new s9({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Q});let q=b0(await H9(this.config.headers),Y);if(Q.length===1){let{responseHeaders:z,value:j,rawValue:A}=await T0({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:q,body:{model:`models/${this.modelId}`,content:{parts:[{text:Q[0]}]},outputDimensionality:B==null?void 0:B.outputDimensionality,taskType:B==null?void 0:B.taskType},failedResponseHandler:s8,successfulResponseHandler:m0(GB),abortSignal:J,fetch:this.config.fetch});return{embeddings:[j.embedding.values],usage:void 0,response:{headers:z,body:A}}}let{responseHeaders:G,value:H,rawValue:U}=await T0({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:q,body:{requests:Q.map((z)=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:z}]},outputDimensionality:B==null?void 0:B.outputDimensionality,taskType:B==null?void 0:B.taskType}))},failedResponseHandler:s8,successfulResponseHandler:m0(WB),abortSignal:J,fetch:this.config.fetch});return{embeddings:H.embeddings.map((z)=>z.values),usage:void 0,response:{headers:G,body:U}}}},WB=J0(()=>p(W.object({embeddings:W.array(W.object({values:W.array(W.number())}))}))),GB=J0(()=>p(W.object({embedding:W.object({values:W.array(W.number())})})));function s1(Q){if(Q==null||BB(Q))return;if(typeof Q==="boolean")return{type:"boolean",properties:{}};let{type:Y,description:J,required:X,properties:B,items:q,allOf:G,anyOf:H,oneOf:U,format:z,const:j,minLength:A,enum:V}=Q,F={};if(J)F.description=J;if(X)F.required=X;if(z)F.format=z;if(j!==void 0)F.enum=[j];if(Y)if(Array.isArray(Y))if(Y.includes("null"))F.type=Y.filter((D)=>D!=="null")[0],F.nullable=!0;else F.type=Y;else if(Y==="null")F.type="null";else F.type=Y;if(V!==void 0)F.enum=V;if(B!=null)F.properties=Object.entries(B).reduce((D,[L,N])=>{return D[L]=s1(N),D},{});if(q)F.items=Array.isArray(q)?q.map(s1):s1(q);if(G)F.allOf=G.map(s1);if(H)if(H.some((D)=>typeof D==="object"&&(D==null?void 0:D.type)==="null")){let D=H.filter((L)=>!(typeof L==="object"&&(L==null?void 0:L.type)==="null"));if(D.length===1){let L=s1(D[0]);if(typeof L==="object")F.nullable=!0,Object.assign(F,L)}else F.anyOf=D.map(s1),F.nullable=!0}else F.anyOf=H.map(s1);if(U)F.oneOf=U.map(s1);if(A!==void 0)F.minLength=A;return F}function BB(Q){return Q!=null&&typeof Q==="object"&&Q.type==="object"&&(Q.properties==null||Object.keys(Q.properties).length===0)&&!Q.additionalProperties}function qB(Q,Y){var J;let X=[],B=[],q=!0,G=(J=Y==null?void 0:Y.isGemmaModel)!=null?J:!1;for(let{role:H,content:U}of Q)switch(H){case"system":{if(!q)throw new I0({functionality:"system messages are only supported at the beginning of the conversation"});X.push({text:U});break}case"user":{q=!1;let z=[];for(let j of U)switch(j.type){case"text":{z.push({text:j.text});break}case"file":{let A=j.mediaType==="image/*"?"image/jpeg":j.mediaType;z.push(j.data instanceof URL?{fileData:{mimeType:A,fileUri:j.data.toString()}}:{inlineData:{mimeType:A,data:F1(j.data)}});break}}B.push({role:"user",parts:z});break}case"assistant":{q=!1,B.push({role:"model",parts:U.map((z)=>{var j,A,V,F,D,L;switch(z.type){case"text":return z.text.length===0?void 0:{text:z.text,thoughtSignature:(A=(j=z.providerOptions)==null?void 0:j.google)==null?void 0:A.thoughtSignature};case"reasoning":return z.text.length===0?void 0:{text:z.text,thought:!0,thoughtSignature:(F=(V=z.providerOptions)==null?void 0:V.google)==null?void 0:F.thoughtSignature};case"file":{if(z.mediaType!=="image/png")throw new I0({functionality:"Only PNG images are supported in assistant messages"});if(z.data instanceof URL)throw new I0({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:z.mediaType,data:F1(z.data)}}}case"tool-call":return{functionCall:{name:z.toolName,args:z.input},thoughtSignature:(L=(D=z.providerOptions)==null?void 0:D.google)==null?void 0:L.thoughtSignature}}}).filter((z)=>z!==void 0)});break}case"tool":{q=!1;let z=[];for(let j of U){let A=j.output;if(A.type==="content")for(let V of A.value)switch(V.type){case"text":z.push({functionResponse:{name:j.toolName,response:{name:j.toolName,content:V.text}}});break;case"media":z.push({inlineData:{mimeType:V.mediaType,data:V.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:z.push({text:JSON.stringify(V)});break}else z.push({functionResponse:{name:j.toolName,response:{name:j.toolName,content:A.value}}})}B.push({role:"user",parts:z});break}}if(G&&X.length>0&&B.length>0&&B[0].role==="user"){let H=X.map((U)=>U.text).join(`
22
-
23
- `);B[0].parts.unshift({text:H+`
24
-
25
- `})}return{systemInstruction:X.length>0&&!G?{parts:X}:void 0,contents:B}}function eY(Q){return Q.includes("/")?Q:`models/${Q}`}var HB=J0(()=>p(W.object({responseModalities:W.array(W.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:W.object({thinkingBudget:W.number().optional(),includeThoughts:W.boolean().optional()}).optional(),cachedContent:W.string().optional(),structuredOutputs:W.boolean().optional(),safetySettings:W.array(W.object({category:W.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:W.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:W.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:W.boolean().optional(),labels:W.record(W.string(),W.string()).optional(),mediaResolution:W.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:W.object({aspectRatio:W.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional()}).optional()})));function zB({tools:Q,toolChoice:Y,modelId:J}){var X;Q=(Q==null?void 0:Q.length)?Q:void 0;let B=[],q=J.includes("gemini-2"),G=J.includes("gemini-1.5-flash")&&!J.includes("-8b");if(Q==null)return{tools:void 0,toolConfig:void 0,toolWarnings:B};let H=Q.some((A)=>A.type==="function"),U=Q.some((A)=>A.type==="provider-defined");if(H&&U)B.push({type:"unsupported-tool",tool:Q.find((A)=>A.type==="function"),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."});if(U){let A=[];return Q.filter((F)=>F.type==="provider-defined").forEach((F)=>{switch(F.id){case"google.google_search":if(q)A.push({googleSearch:{}});else if(G)A.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:F.args.mode,dynamicThreshold:F.args.dynamicThreshold}}});else A.push({googleSearchRetrieval:{}});break;case"google.url_context":if(q)A.push({urlContext:{}});else B.push({type:"unsupported-tool",tool:F,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(q)A.push({codeExecution:{}});else B.push({type:"unsupported-tool",tool:F,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:B.push({type:"unsupported-tool",tool:F});break}}),{tools:A.length>0?A:void 0,toolConfig:void 0,toolWarnings:B}}let z=[];for(let A of Q)switch(A.type){case"function":z.push({name:A.name,description:(X=A.description)!=null?X:"",parameters:s1(A.inputSchema)});break;default:B.push({type:"unsupported-tool",tool:A});break}if(Y==null)return{tools:{functionDeclarations:z},toolConfig:void 0,toolWarnings:B};let j=Y.type;switch(j){case"auto":return{tools:{functionDeclarations:z},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:B};case"none":return{tools:{functionDeclarations:z},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:B};case"required":return{tools:{functionDeclarations:z},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:B};case"tool":return{tools:{functionDeclarations:z},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[Y.toolName]}},toolWarnings:B};default:throw new I0({functionality:`tool choice type: ${j}`})}}function QJ({finishReason:Q,hasToolCalls:Y}){switch(Q){case"STOP":return Y?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var UB=class{constructor(Q,Y){this.specificationVersion="v2";var J;this.modelId=Q,this.config=Y,this.generateId=(J=Y.generateId)!=null?J:s0}get provider(){return this.config.provider}get supportedUrls(){var Q,Y,J;return(J=(Y=(Q=this.config).supportedUrls)==null?void 0:Y.call(Q))!=null?J:{}}async getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,topK:B,frequencyPenalty:q,presencePenalty:G,stopSequences:H,responseFormat:U,seed:z,tools:j,toolChoice:A,providerOptions:V}){var F,D;let L=[],N=await k0({provider:"google",providerOptions:V,schema:HB});if(((F=N==null?void 0:N.thinkingConfig)==null?void 0:F.includeThoughts)===!0&&!this.config.provider.startsWith("google.vertex."))L.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let K=this.modelId.toLowerCase().startsWith("gemma-"),{contents:M,systemInstruction:w}=qB(Q,{isGemmaModel:K}),{tools:_,toolConfig:g,toolWarnings:S}=zB({tools:j,toolChoice:A,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:Y,temperature:J,topK:B,topP:X,frequencyPenalty:q,presencePenalty:G,stopSequences:H,seed:z,responseMimeType:(U==null?void 0:U.type)==="json"?"application/json":void 0,responseSchema:(U==null?void 0:U.type)==="json"&&U.schema!=null&&((D=N==null?void 0:N.structuredOutputs)!=null?D:!0)?s1(U.schema):void 0,...(N==null?void 0:N.audioTimestamp)&&{audioTimestamp:N.audioTimestamp},responseModalities:N==null?void 0:N.responseModalities,thinkingConfig:N==null?void 0:N.thinkingConfig,...(N==null?void 0:N.imageConfig)&&{imageConfig:N.imageConfig},...(N==null?void 0:N.mediaResolution)&&{mediaResolution:N.mediaResolution}},contents:M,systemInstruction:K?void 0:w,safetySettings:N==null?void 0:N.safetySettings,tools:_,toolConfig:g,cachedContent:N==null?void 0:N.cachedContent,labels:N==null?void 0:N.labels},warnings:[...L,...S]}}async doGenerate(Q){var Y,J,X,B,q,G,H,U,z,j,A,V,F;let{args:D,warnings:L}=await this.getArgs(Q),N=JSON.stringify(D),K=b0(await H9(this.config.headers),Q.headers),{responseHeaders:M,value:w,rawValue:_}=await T0({url:`${this.config.baseURL}/${eY(this.modelId)}:generateContent`,headers:K,body:D,failedResponseHandler:s8,successfulResponseHandler:m0(NB),abortSignal:Q.abortSignal,fetch:this.config.fetch}),g=w.candidates[0],S=[],C=(J=(Y=g.content)==null?void 0:Y.parts)!=null?J:[],T=w.usageMetadata,b;for(let I of C)if("executableCode"in I&&((X=I.executableCode)==null?void 0:X.code)){let E=this.config.generateId();b=E,S.push({type:"tool-call",toolCallId:E,toolName:"code_execution",input:JSON.stringify(I.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in I&&I.codeExecutionResult)S.push({type:"tool-result",toolCallId:b,toolName:"code_execution",result:{outcome:I.codeExecutionResult.outcome,output:I.codeExecutionResult.output},providerExecuted:!0}),b=void 0;else if("text"in I&&I.text!=null&&I.text.length>0)S.push({type:I.thought===!0?"reasoning":"text",text:I.text,providerMetadata:I.thoughtSignature?{google:{thoughtSignature:I.thoughtSignature}}:void 0});else if("functionCall"in I)S.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:I.functionCall.name,input:JSON.stringify(I.functionCall.args),providerMetadata:I.thoughtSignature?{google:{thoughtSignature:I.thoughtSignature}}:void 0});else if("inlineData"in I)S.push({type:"file",data:I.inlineData.data,mediaType:I.inlineData.mimeType});let k=(B=XJ({groundingMetadata:g.groundingMetadata,generateId:this.config.generateId}))!=null?B:[];for(let I of k)S.push(I);return{content:S,finishReason:QJ({finishReason:g.finishReason,hasToolCalls:S.some((I)=>I.type==="tool-call")}),usage:{inputTokens:(q=T==null?void 0:T.promptTokenCount)!=null?q:void 0,outputTokens:(G=T==null?void 0:T.candidatesTokenCount)!=null?G:void 0,totalTokens:(H=T==null?void 0:T.totalTokenCount)!=null?H:void 0,reasoningTokens:(U=T==null?void 0:T.thoughtsTokenCount)!=null?U:void 0,cachedInputTokens:(z=T==null?void 0:T.cachedContentTokenCount)!=null?z:void 0},warnings:L,providerMetadata:{google:{promptFeedback:(j=w.promptFeedback)!=null?j:null,groundingMetadata:(A=g.groundingMetadata)!=null?A:null,urlContextMetadata:(V=g.urlContextMetadata)!=null?V:null,safetyRatings:(F=g.safetyRatings)!=null?F:null,usageMetadata:T!=null?T:null}},request:{body:N},response:{headers:M,body:_}}}async doStream(Q){let{args:Y,warnings:J}=await this.getArgs(Q),X=JSON.stringify(Y),B=b0(await H9(this.config.headers),Q.headers),{responseHeaders:q,value:G}=await T0({url:`${this.config.baseURL}/${eY(this.modelId)}:streamGenerateContent?alt=sse`,headers:B,body:Y,failedResponseHandler:s8,successfulResponseHandler:D1(jB),abortSignal:Q.abortSignal,fetch:this.config.fetch}),H="unknown",U={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},z=void 0,j=this.config.generateId,A=!1,V=null,F=null,D=0,L=new Set,N;return{stream:G.pipeThrough(new TransformStream({start(K){K.enqueue({type:"stream-start",warnings:J})},transform(K,M){var w,_,g,S,C,T,b,k,I,E,R,Z;if(Q.includeRawChunks)M.enqueue({type:"raw",rawValue:K.rawValue});if(!K.success){M.enqueue({type:"error",error:K.error});return}let v=K.value,y=v.usageMetadata;if(y!=null)U.inputTokens=(w=y.promptTokenCount)!=null?w:void 0,U.outputTokens=(_=y.candidatesTokenCount)!=null?_:void 0,U.totalTokens=(g=y.totalTokenCount)!=null?g:void 0,U.reasoningTokens=(S=y.thoughtsTokenCount)!=null?S:void 0,U.cachedInputTokens=(C=y.cachedContentTokenCount)!=null?C:void 0;let m=(T=v.candidates)==null?void 0:T[0];if(m==null)return;let i=m.content,l=XJ({groundingMetadata:m.groundingMetadata,generateId:j});if(l!=null){for(let r of l)if(r.sourceType==="url"&&!L.has(r.url))L.add(r.url),M.enqueue(r)}if(i!=null){let r=(b=i.parts)!=null?b:[];for(let Q0 of r)if("executableCode"in Q0&&((k=Q0.executableCode)==null?void 0:k.code)){let $=j();N=$,M.enqueue({type:"tool-call",toolCallId:$,toolName:"code_execution",input:JSON.stringify(Q0.executableCode),providerExecuted:!0}),A=!0}else if("codeExecutionResult"in Q0&&Q0.codeExecutionResult){let $=N;if($)M.enqueue({type:"tool-result",toolCallId:$,toolName:"code_execution",result:{outcome:Q0.codeExecutionResult.outcome,output:Q0.codeExecutionResult.output},providerExecuted:!0}),N=void 0}else if("text"in Q0&&Q0.text!=null&&Q0.text.length>0)if(Q0.thought===!0){if(V!==null)M.enqueue({type:"text-end",id:V}),V=null;if(F===null)F=String(D++),M.enqueue({type:"reasoning-start",id:F,providerMetadata:Q0.thoughtSignature?{google:{thoughtSignature:Q0.thoughtSignature}}:void 0});M.enqueue({type:"reasoning-delta",id:F,delta:Q0.text,providerMetadata:Q0.thoughtSignature?{google:{thoughtSignature:Q0.thoughtSignature}}:void 0})}else{if(F!==null)M.enqueue({type:"reasoning-end",id:F}),F=null;if(V===null)V=String(D++),M.enqueue({type:"text-start",id:V,providerMetadata:Q0.thoughtSignature?{google:{thoughtSignature:Q0.thoughtSignature}}:void 0});M.enqueue({type:"text-delta",id:V,delta:Q0.text,providerMetadata:Q0.thoughtSignature?{google:{thoughtSignature:Q0.thoughtSignature}}:void 0})}let d=FB(i.parts);if(d!=null)for(let Q0 of d)M.enqueue({type:"file",mediaType:Q0.inlineData.mimeType,data:Q0.inlineData.data});let t=LB({parts:i.parts,generateId:j});if(t!=null)for(let Q0 of t)M.enqueue({type:"tool-input-start",id:Q0.toolCallId,toolName:Q0.toolName,providerMetadata:Q0.providerMetadata}),M.enqueue({type:"tool-input-delta",id:Q0.toolCallId,delta:Q0.args,providerMetadata:Q0.providerMetadata}),M.enqueue({type:"tool-input-end",id:Q0.toolCallId,providerMetadata:Q0.providerMetadata}),M.enqueue({type:"tool-call",toolCallId:Q0.toolCallId,toolName:Q0.toolName,input:Q0.args,providerMetadata:Q0.providerMetadata}),A=!0}if(m.finishReason!=null){if(H=QJ({finishReason:m.finishReason,hasToolCalls:A}),z={google:{promptFeedback:(I=v.promptFeedback)!=null?I:null,groundingMetadata:(E=m.groundingMetadata)!=null?E:null,urlContextMetadata:(R=m.urlContextMetadata)!=null?R:null,safetyRatings:(Z=m.safetyRatings)!=null?Z:null}},y!=null)z.google.usageMetadata=y}},flush(K){if(V!==null)K.enqueue({type:"text-end",id:V});if(F!==null)K.enqueue({type:"reasoning-end",id:F});K.enqueue({type:"finish",finishReason:H,usage:U,providerMetadata:z})}})),response:{headers:q},request:{body:X}}}};function LB({parts:Q,generateId:Y}){let J=Q==null?void 0:Q.filter((X)=>("functionCall"in X));return J==null||J.length===0?void 0:J.map((X)=>({type:"tool-call",toolCallId:Y(),toolName:X.functionCall.name,args:JSON.stringify(X.functionCall.args),providerMetadata:X.thoughtSignature?{google:{thoughtSignature:X.thoughtSignature}}:void 0}))}function FB(Q){return Q==null?void 0:Q.filter((Y)=>("inlineData"in Y))}function XJ({groundingMetadata:Q,generateId:Y}){var J;return(J=Q==null?void 0:Q.groundingChunks)==null?void 0:J.filter((X)=>X.web!=null).map((X)=>({type:"source",sourceType:"url",id:Y(),url:X.web.uri,title:X.web.title}))}var YJ=()=>W.object({webSearchQueries:W.array(W.string()).nullish(),retrievalQueries:W.array(W.string()).nullish(),searchEntryPoint:W.object({renderedContent:W.string()}).nullish(),groundingChunks:W.array(W.object({web:W.object({uri:W.string(),title:W.string()}).nullish(),retrievedContext:W.object({uri:W.string(),title:W.string()}).nullish()})).nullish(),groundingSupports:W.array(W.object({segment:W.object({startIndex:W.number().nullish(),endIndex:W.number().nullish(),text:W.string().nullish()}),segment_text:W.string().nullish(),groundingChunkIndices:W.array(W.number()).nullish(),supportChunkIndices:W.array(W.number()).nullish(),confidenceScores:W.array(W.number()).nullish(),confidenceScore:W.array(W.number()).nullish()})).nullish(),retrievalMetadata:W.union([W.object({webDynamicRetrievalScore:W.number()}),W.object({})]).nullish()}),JJ=()=>W.object({parts:W.array(W.union([W.object({functionCall:W.object({name:W.string(),args:W.unknown()}),thoughtSignature:W.string().nullish()}),W.object({inlineData:W.object({mimeType:W.string(),data:W.string()})}),W.object({executableCode:W.object({language:W.string(),code:W.string()}).nullish(),codeExecutionResult:W.object({outcome:W.string(),output:W.string()}).nullish(),text:W.string().nullish(),thought:W.boolean().nullish(),thoughtSignature:W.string().nullish()})])).nullish()}),SQ=()=>W.object({category:W.string().nullish(),probability:W.string().nullish(),probabilityScore:W.number().nullish(),severity:W.string().nullish(),severityScore:W.number().nullish(),blocked:W.boolean().nullish()}),WJ=W.object({cachedContentTokenCount:W.number().nullish(),thoughtsTokenCount:W.number().nullish(),promptTokenCount:W.number().nullish(),candidatesTokenCount:W.number().nullish(),totalTokenCount:W.number().nullish()}),GJ=()=>W.object({urlMetadata:W.array(W.object({retrievedUrl:W.string(),urlRetrievalStatus:W.string()}))}),NB=J0(()=>p(W.object({candidates:W.array(W.object({content:JJ().nullish().or(W.object({}).strict()),finishReason:W.string().nullish(),safetyRatings:W.array(SQ()).nullish(),groundingMetadata:YJ().nullish(),urlContextMetadata:GJ().nullish()})),usageMetadata:WJ.nullish(),promptFeedback:W.object({blockReason:W.string().nullish(),safetyRatings:W.array(SQ()).nullish()}).nullish()}))),jB=J0(()=>p(W.object({candidates:W.array(W.object({content:JJ().nullish(),finishReason:W.string().nullish(),safetyRatings:W.array(SQ()).nullish(),groundingMetadata:YJ().nullish(),urlContextMetadata:GJ().nullish()})).nullish(),usageMetadata:WJ.nullish(),promptFeedback:W.object({blockReason:W.string().nullish(),safetyRatings:W.array(SQ()).nullish()}).nullish()}))),KB=J1({id:"google.code_execution",name:"code_execution",inputSchema:W.object({language:W.string().describe("The programming language of the code."),code:W.string().describe("The code to be executed.")}),outputSchema:W.object({outcome:W.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:W.string().describe("The output from the code execution.")})}),MB=Y1({id:"google.google_search",name:"google_search",inputSchema:J0(()=>p(W.object({mode:W.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:W.number().default(1)})))}),AB=Y1({id:"google.url_context",name:"url_context",inputSchema:J0(()=>p(W.object({})))}),VB={googleSearch:MB,urlContext:AB,codeExecution:KB},DB=class{constructor(Q,Y,J){this.modelId=Q,this.settings=Y,this.config=J,this.specificationVersion="v2"}get maxImagesPerCall(){var Q;return(Q=this.settings.maxImagesPerCall)!=null?Q:4}get provider(){return this.config.provider}async doGenerate(Q){var Y,J,X;let{prompt:B,n:q=1,size:G="1024x1024",aspectRatio:H="1:1",seed:U,providerOptions:z,headers:j,abortSignal:A}=Q,V=[];if(G!=null)V.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});if(U!=null)V.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});let F=await k0({provider:"google",providerOptions:z,schema:OB}),D=(X=(J=(Y=this.config._internal)==null?void 0:Y.currentDate)==null?void 0:J.call(Y))!=null?X:new Date,L={sampleCount:q};if(H!=null)L.aspectRatio=H;if(F)Object.assign(L,F);let N={instances:[{prompt:B}],parameters:L},{responseHeaders:K,value:M}=await T0({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:b0(await H9(this.config.headers),j),body:N,failedResponseHandler:s8,successfulResponseHandler:m0(wB),abortSignal:A,fetch:this.config.fetch});return{images:M.predictions.map((w)=>w.bytesBase64Encoded),warnings:V!=null?V:[],providerMetadata:{google:{images:M.predictions.map((w)=>({}))}},response:{timestamp:D,modelId:this.modelId,headers:K}}}},wB=J0(()=>p(W.object({predictions:W.array(W.object({bytesBase64Encoded:W.string()})).default([])}))),OB=J0(()=>p(W.object({personGeneration:W.enum(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:W.enum(["1:1","3:4","4:3","9:16","16:9"]).nullish()})));function RB(Q={}){var Y;let J=(Y=w9(Q.baseURL))!=null?Y:"https://generativelanguage.googleapis.com/v1beta",X=()=>i1({"x-goog-api-key":J8({apiKey:Q.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...Q.headers},`ai-sdk/google/${QB}`),B=(U)=>{var z;return new UB(U,{provider:"google.generative-ai",baseURL:J,headers:X,generateId:(z=Q.generateId)!=null?z:s0,supportedUrls:()=>({"*":[new RegExp(`^${J}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:Q.fetch})},q=(U)=>new JB(U,{provider:"google.generative-ai",baseURL:J,headers:X,fetch:Q.fetch}),G=(U,z={})=>new DB(U,z,{provider:"google.generative-ai",baseURL:J,headers:X,fetch:Q.fetch}),H=function(U){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return B(U)};return H.languageModel=B,H.chat=B,H.generativeAI=B,H.embedding=q,H.textEmbedding=q,H.textEmbeddingModel=q,H.image=G,H.imageModel=G,H.tools=VB,H}var wX=RB();var ZB=[{id:"gemini-2.0-flash-exp",name:"Gemini 2.0 Flash (Experimental)"},{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro"},{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash"}],BJ={"gemini-2.0-flash-exp":{contextLength:1e6,maxOutput:8192},"gemini-1.5-pro":{contextLength:2000000,maxOutput:8192},"gemini-1.5-flash":{contextLength:1e6,maxOutput:8192}};class OX{id="google";name="Google";getConfigSchema(){return[{key:"api-key",label:"API Key (AI Studio)",type:"string",required:!1,secret:!0,description:"Get your API key from https://aistudio.google.com",placeholder:"AIza..."},{key:"project-id",label:"Project ID (Vertex AI)",type:"string",required:!1,description:"Google Cloud project ID for Vertex AI",placeholder:"my-project-123"},{key:"location",label:"Location (Vertex AI)",type:"string",required:!1,description:"Vertex AI location (default: us-central1)",placeholder:"us-central1"}]}isConfigured(Q){let Y=!!Q["api-key"],J=!!Q["project-id"]&&!!Q.location;return Y||J}async fetchModels(Q){return ZB}async getModelDetails(Q,Y){if(BJ[Q])return BJ[Q];let J=await O9(Q);if(J)return{contextLength:J.contextLength,maxOutput:J.maxOutput,inputPrice:J.inputPrice,outputPrice:J.outputPrice};return null}createClient(Q,Y){let J=Q["api-key"],X=Q["project-id"],B=Q.location||"us-central1";if(J)return wX(Y,{apiKey:J});else if(X)return wX(Y,{vertexai:{projectId:X,location:B}});else throw Error("Google provider requires either api-key or project-id")}}var{defineProperty:EB,defineProperties:PB,getOwnPropertyDescriptors:SB,getOwnPropertySymbols:qJ}=Object,IB=Object.prototype.hasOwnProperty,CB=Object.prototype.propertyIsEnumerable,HJ=(Q,Y,J)=>(Y in Q)?EB(Q,Y,{enumerable:!0,configurable:!0,writable:!0,value:J}):Q[Y]=J,W1=(Q,Y)=>{for(var J in Y||(Y={}))if(IB.call(Y,J))HJ(Q,J,Y[J]);if(qJ){for(var J of qJ(Y))if(CB.call(Y,J))HJ(Q,J,Y[J])}return Q},CQ=(Q,Y)=>PB(Q,SB(Y)),jJ="vercel.ai.error",bB=Symbol.for(jJ),KJ,TB=class Q extends Error{constructor({name:Y,message:J,cause:X}){super(J);this[KJ]=!0,this.name=Y,this.cause=X}static isInstance(Y){return Q.hasMarker(Y,jJ)}static hasMarker(Y,J){let X=Symbol.for(J);return Y!=null&&typeof Y==="object"&&X in Y&&typeof Y[X]==="boolean"&&Y[X]===!0}};KJ=bB;var z1=TB,MJ="AI_APICallError",AJ=`vercel.ai.error.${MJ}`,_B=Symbol.for(AJ),VJ,z9=class extends z1{constructor({message:Q,url:Y,requestBodyValues:J,statusCode:X,responseHeaders:B,responseBody:q,cause:G,isRetryable:H=X!=null&&(X===408||X===409||X===429||X>=500),data:U}){super({name:MJ,message:Q,cause:G});this[VJ]=!0,this.url=Y,this.requestBodyValues=J,this.statusCode=X,this.responseHeaders=B,this.responseBody=q,this.isRetryable=H,this.data=U}static isInstance(Q){return z1.hasMarker(Q,AJ)}};VJ=_B;var DJ="AI_EmptyResponseBodyError",wJ=`vercel.ai.error.${DJ}`,kB=Symbol.for(wJ),OJ,vB=class extends z1{constructor({message:Q="Empty response body"}={}){super({name:DJ,message:Q});this[OJ]=!0}static isInstance(Q){return z1.hasMarker(Q,wJ)}};OJ=kB;function RJ(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}var ZJ="AI_InvalidArgumentError",EJ=`vercel.ai.error.${ZJ}`,xB=Symbol.for(EJ),PJ,gB=class extends z1{constructor({message:Q,cause:Y,argument:J}){super({name:ZJ,message:Q,cause:Y});this[PJ]=!0,this.argument=J}static isInstance(Q){return z1.hasMarker(Q,EJ)}};PJ=xB;var SJ="AI_InvalidPromptError",IJ=`vercel.ai.error.${SJ}`,yB=Symbol.for(IJ),CJ,$B=class extends z1{constructor({prompt:Q,message:Y,cause:J}){super({name:SJ,message:`Invalid prompt: ${Y}`,cause:J});this[CJ]=!0,this.prompt=Q}static isInstance(Q){return z1.hasMarker(Q,IJ)}};CJ=yB;var bJ="AI_InvalidResponseDataError",TJ=`vercel.ai.error.${bJ}`,fB=Symbol.for(TJ),_J,RX=class extends z1{constructor({data:Q,message:Y=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:bJ,message:Y});this[_J]=!0,this.data=Q}static isInstance(Q){return z1.hasMarker(Q,TJ)}};_J=fB;var kJ="AI_JSONParseError",vJ=`vercel.ai.error.${kJ}`,hB=Symbol.for(vJ),xJ,bQ=class extends z1{constructor({text:Q,cause:Y}){super({name:kJ,message:`JSON parsing failed: Text: ${Q}.
26
- Error message: ${RJ(Y)}`,cause:Y});this[xJ]=!0,this.text=Q}static isInstance(Q){return z1.hasMarker(Q,vJ)}};xJ=hB;var gJ="AI_LoadAPIKeyError",yJ=`vercel.ai.error.${gJ}`,mB=Symbol.for(yJ),$J,IQ=class extends z1{constructor({message:Q}){super({name:gJ,message:Q});this[$J]=!0}static isInstance(Q){return z1.hasMarker(Q,yJ)}};$J=mB;var uB="AI_LoadSettingError",cB=`vercel.ai.error.${uB}`,dB=Symbol.for(cB),lB;lB=dB;var pB="AI_NoContentGeneratedError",nB=`vercel.ai.error.${pB}`,iB=Symbol.for(nB),aB;aB=iB;var sB="AI_NoSuchModelError",oB=`vercel.ai.error.${sB}`,rB=Symbol.for(oB),tB;tB=rB;var eB="AI_TooManyEmbeddingValuesForCallError",Qq=`vercel.ai.error.${eB}`,Xq=Symbol.for(Qq),Yq;Yq=Xq;var fJ="AI_TypeValidationError",hJ=`vercel.ai.error.${fJ}`,Jq=Symbol.for(hJ),mJ,Wq=class Q extends z1{constructor({value:Y,cause:J}){super({name:fJ,message:`Type validation failed: Value: ${JSON.stringify(Y)}.
27
- Error message: ${RJ(J)}`,cause:J});this[mJ]=!0,this.value=Y}static isInstance(Y){return z1.hasMarker(Y,hJ)}static wrap({value:Y,cause:J}){return Q.isInstance(J)&&J.value===Y?J:new Q({value:Y,cause:J})}};mJ=Jq;var o8=Wq,uJ="AI_UnsupportedFunctionalityError",cJ=`vercel.ai.error.${uJ}`,Gq=Symbol.for(cJ),dJ,Z9=class extends z1{constructor({functionality:Q,message:Y=`'${Q}' functionality not supported.`}){super({name:uJ,message:Y});this[dJ]=!0,this.functionality=Q}static isInstance(Q){return z1.hasMarker(Q,cJ)}};dJ=Gq;var zJ=class extends Error{constructor(Q,Y){super(Q),this.name="ParseError",this.type=Y.type,this.field=Y.field,this.value=Y.value,this.line=Y.line}};function ZX(Q){}function Bq(Q){if(typeof Q=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:Y=ZX,onError:J=ZX,onRetry:X=ZX,onComment:B}=Q,q="",G=!0,H,U="",z="";function j(L){let N=G?L.replace(/^\xEF\xBB\xBF/,""):L,[K,M]=qq(`${q}${N}`);for(let w of K)A(w);q=M,G=!1}function A(L){if(L===""){F();return}if(L.startsWith(":")){B&&B(L.slice(L.startsWith(": ")?2:1));return}let N=L.indexOf(":");if(N!==-1){let K=L.slice(0,N),M=L[N+1]===" "?2:1,w=L.slice(N+M);V(K,w,L);return}V(L,"",L)}function V(L,N,K){switch(L){case"event":z=N;break;case"data":U=`${U}${N}
28
- `;break;case"id":H=N.includes("\x00")?void 0:N;break;case"retry":/^\d+$/.test(N)?X(parseInt(N,10)):J(new zJ(`Invalid \`retry\` value: "${N}"`,{type:"invalid-retry",value:N,line:K}));break;default:J(new zJ(`Unknown field "${L.length>20?`${L.slice(0,20)}…`:L}"`,{type:"unknown-field",field:L,value:N,line:K}));break}}function F(){U.length>0&&Y({id:H,event:z||void 0,data:U.endsWith(`
29
- `)?U.slice(0,-1):U}),H=void 0,U="",z=""}function D(L={}){q&&L.consume&&A(q),G=!0,H=void 0,U="",z="",q=""}return{feed:j,reset:D}}function qq(Q){let Y=[],J="",X=0;for(;X<Q.length;){let B=Q.indexOf("\r",X),q=Q.indexOf(`
30
- `,X),G=-1;if(B!==-1&&q!==-1?G=Math.min(B,q):B!==-1?G=B:q!==-1&&(G=q),G===-1){J=Q.slice(X);break}else{let H=Q.slice(X,G);Y.push(H),X=G+1,Q[X-1]==="\r"&&Q[X]===`
31
- `&&X++}}return[Y,J]}var Hq=class extends TransformStream{constructor({onError:Q,onRetry:Y,onComment:J}={}){let X;super({start(B){X=Bq({onEvent:(q)=>{B.enqueue(q)},onError(q){Q==="terminate"?B.error(q):typeof Q=="function"&&Q(q)},onRetry:Y,onComment:J})},transform(B){X.feed(B)}})}},TV=Symbol("Let zodToJsonSchema decide on which parser to use"),_V=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function TQ(...Q){return Q.reduce((Y,J)=>W1(W1({},Y),J!=null?J:{}),{})}function xQ(Q){return Object.fromEntries([...Q.headers])}var zq=({prefix:Q,size:Y=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:X="-"}={})=>{let B=()=>{let q=J.length,G=Array(Y);for(let H=0;H<Y;H++)G[H]=J[Math.random()*q|0];return G.join("")};if(Q==null)return B;if(J.includes(X))throw new gB({argument:"separator",message:`The separator "${X}" must not be part of the alphabet "${J}".`});return()=>`${Q}${X}${B()}`},$1=zq();function PX(Q){return(Q instanceof Error||Q instanceof DOMException)&&(Q.name==="AbortError"||Q.name==="ResponseAborted"||Q.name==="TimeoutError")}var Uq=["fetch failed","failed to fetch"];function Lq({error:Q,url:Y,requestBodyValues:J}){if(PX(Q))return Q;if(Q instanceof TypeError&&Uq.includes(Q.message.toLowerCase())){let X=Q.cause;if(X!=null)return new z9({message:`Cannot connect to API: ${X.message}`,cause:X,url:Y,requestBodyValues:J,isRetryable:!0})}return Q}function Fq(Q){return Object.fromEntries(Object.entries(Q).filter(([Y,J])=>J!=null))}function Nq({apiKey:Q,environmentVariableName:Y,apiKeyParameterName:J="apiKey",description:X}){if(typeof Q==="string")return Q;if(Q!=null)throw new IQ({message:`${X} API key must be a string.`});if(typeof process>"u")throw new IQ({message:`${X} API key is missing. Pass it using the '${J}' parameter. Environment variables is not supported in this environment.`});if(Q=process.env[Y],Q==null)throw new IQ({message:`${X} API key is missing. Pass it using the '${J}' parameter or the ${Y} environment variable.`});if(typeof Q!=="string")throw new IQ({message:`${X} API key must be a string. The value of the ${Y} environment variable is not a string.`});return Q}var jq=/"__proto__"\s*:/,Kq=/"constructor"\s*:/;function Mq(Q){let Y=JSON.parse(Q);if(Y===null||typeof Y!=="object")return Y;if(jq.test(Q)===!1&&Kq.test(Q)===!1)return Y;return Aq(Y)}function Aq(Q){let Y=[Q];while(Y.length){let J=Y;Y=[];for(let X of J){if(Object.prototype.hasOwnProperty.call(X,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(X,"constructor")&&Object.prototype.hasOwnProperty.call(X.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let B in X){let q=X[B];if(q&&typeof q==="object")Y.push(q)}}}return Q}function IX(Q){let{stackTraceLimit:Y}=Error;Error.stackTraceLimit=0;try{return Mq(Q)}finally{Error.stackTraceLimit=Y}}var SX=Symbol.for("vercel.ai.validator");function Vq(Q){return{[SX]:!0,validate:Q}}function Dq(Q){return typeof Q==="object"&&Q!==null&&SX in Q&&Q[SX]===!0&&"validate"in Q}function wq(Q){return Dq(Q)?Q:Oq(Q)}function Oq(Q){return Vq(async(Y)=>{let J=await Q["~standard"].validate(Y);return J.issues==null?{success:!0,value:J.value}:{success:!1,error:new o8({value:Y,cause:J.issues})}})}async function Rq({value:Q,schema:Y}){let J=await lJ({value:Q,schema:Y});if(!J.success)throw o8.wrap({value:Q,cause:J.error});return J.value}async function lJ({value:Q,schema:Y}){let J=wq(Y);try{if(J.validate==null)return{success:!0,value:Q,rawValue:Q};let X=await J.validate(Q);if(X.success)return{success:!0,value:X.value,rawValue:Q};return{success:!1,error:o8.wrap({value:Q,cause:X.error}),rawValue:Q}}catch(X){return{success:!1,error:o8.wrap({value:Q,cause:X}),rawValue:Q}}}async function Zq({text:Q,schema:Y}){try{let J=IX(Q);if(Y==null)return J;return Rq({value:J,schema:Y})}catch(J){if(bQ.isInstance(J)||o8.isInstance(J))throw J;throw new bQ({text:Q,cause:J})}}async function pJ({text:Q,schema:Y}){try{let J=IX(Q);if(Y==null)return{success:!0,value:J,rawValue:J};return await lJ({value:J,schema:Y})}catch(J){return{success:!1,error:bQ.isInstance(J)?J:new bQ({text:Q,cause:J}),rawValue:void 0}}}function EX(Q){try{return IX(Q),!0}catch(Y){return!1}}function Eq({stream:Q,schema:Y}){return Q.pipeThrough(new TextDecoderStream).pipeThrough(new Hq).pipeThrough(new TransformStream({async transform({data:J},X){if(J==="[DONE]")return;X.enqueue(await pJ({text:J,schema:Y}))}}))}var Pq=()=>globalThis.fetch,_Q=async({url:Q,headers:Y,body:J,failedResponseHandler:X,successfulResponseHandler:B,abortSignal:q,fetch:G})=>Sq({url:Q,headers:W1({"Content-Type":"application/json"},Y),body:{content:JSON.stringify(J),values:J},failedResponseHandler:X,successfulResponseHandler:B,abortSignal:q,fetch:G}),Sq=async({url:Q,headers:Y={},body:J,successfulResponseHandler:X,failedResponseHandler:B,abortSignal:q,fetch:G=Pq()})=>{try{let H=await G(Q,{method:"POST",headers:Fq(Y),body:J.content,signal:q}),U=xQ(H);if(!H.ok){let z;try{z=await B({response:H,url:Q,requestBodyValues:J.values})}catch(j){if(PX(j)||z9.isInstance(j))throw j;throw new z9({message:"Failed to process error response",cause:j,statusCode:H.status,url:Q,responseHeaders:U,requestBodyValues:J.values})}throw z.value}try{return await X({response:H,url:Q,requestBodyValues:J.values})}catch(z){if(z instanceof Error){if(PX(z)||z9.isInstance(z))throw z}throw new z9({message:"Failed to process successful response",cause:z,statusCode:H.status,url:Q,responseHeaders:U,requestBodyValues:J.values})}}catch(H){throw Lq({error:H,url:Q,requestBodyValues:J.values})}},Iq=({errorSchema:Q,errorToMessage:Y,isRetryable:J})=>async({response:X,url:B,requestBodyValues:q})=>{let G=await X.text(),H=xQ(X);if(G.trim()==="")return{responseHeaders:H,value:new z9({message:X.statusText,url:B,requestBodyValues:q,statusCode:X.status,responseHeaders:H,responseBody:G,isRetryable:J==null?void 0:J(X)})};try{let U=await Zq({text:G,schema:Q});return{responseHeaders:H,value:new z9({message:Y(U),url:B,requestBodyValues:q,statusCode:X.status,responseHeaders:H,responseBody:G,data:U,isRetryable:J==null?void 0:J(X,U)})}}catch(U){return{responseHeaders:H,value:new z9({message:X.statusText,url:B,requestBodyValues:q,statusCode:X.status,responseHeaders:H,responseBody:G,isRetryable:J==null?void 0:J(X)})}}},nJ=(Q)=>async({response:Y})=>{let J=xQ(Y);if(Y.body==null)throw new vB({});return{responseHeaders:J,value:Eq({stream:Y.body,schema:Q})}},iJ=(Q)=>async({response:Y,url:J,requestBodyValues:X})=>{let B=await Y.text(),q=await pJ({text:B,schema:Q}),G=xQ(Y);if(!q.success)throw new z9({message:"Invalid JSON response",cause:q.error,statusCode:Y.status,responseHeaders:G,responseBody:B,url:J,requestBodyValues:X});return{responseHeaders:G,value:q.value,rawValue:q.rawValue}};var{btoa:Cq,atob:kV}=globalThis;function bq(Q){let Y="";for(let J=0;J<Q.length;J++)Y+=String.fromCodePoint(Q[J]);return Cq(Y)}function Tq(Q){return Q==null?void 0:Q.replace(/\/$/,"")}var _q=W.object({type:W.literal("reasoning.summary"),summary:W.string()}),kq=W.object({type:W.literal("reasoning.encrypted"),data:W.string()}),vq=W.object({type:W.literal("reasoning.text"),text:W.string().nullish(),signature:W.string().nullish()}),xq=W.union([_q,kq,vq]),gq=W.union([xq,W.unknown().transform(()=>null)]),CX=W.array(gq).transform((Q)=>Q.filter((Y)=>!!Y)),bX=W.object({error:W.object({code:W.union([W.string(),W.number()]).nullable().optional().default(null),message:W.string(),type:W.string().nullable().optional().default(null),param:W.any().nullable().optional().default(null)})}),kQ=Iq({errorSchema:bX,errorToMessage:(Q)=>Q.error.message});function vQ(Q){switch(Q){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"}}function aJ({url:Q,protocols:Y}){try{let J=new URL(Q);return Y.has(J.protocol)}catch(J){return!1}}function UJ({part:Q,defaultMediaType:Y}){var J,X;if(Q.data instanceof Uint8Array){let q=bq(Q.data);return`data:${(J=Q.mediaType)!=null?J:Y};base64,${q}`}let B=Q.data.toString();if(aJ({url:B,protocols:new Set(["http:","https:"])}))return B;return B.startsWith("data:")?B:`data:${(X=Q.mediaType)!=null?X:Y};base64,${B}`}function LJ(Q,Y){var J;let X=Q.match(/^data:([^;]+)/);return X?(J=X[1])!=null?J:Y:Y}function FJ(Q){let Y=Q.match(/^data:[^;]*;base64,(.+)$/);return Y?Y[1]:Q}function R9(Q){var Y,J,X;let B=Q==null?void 0:Q.anthropic,q=Q==null?void 0:Q.openrouter;return(X=(J=(Y=q==null?void 0:q.cacheControl)!=null?Y:q==null?void 0:q.cache_control)!=null?J:B==null?void 0:B.cacheControl)!=null?X:B==null?void 0:B.cache_control}function yq(Q){var Y,J,X;let B=[];for(let{role:q,content:G,providerOptions:H}of Q)switch(q){case"system":{B.push({role:"system",content:G,cache_control:R9(H)});break}case"user":{if(G.length===1&&((Y=G[0])==null?void 0:Y.type)==="text"){let j=(J=R9(H))!=null?J:R9(G[0].providerOptions),A=j?[{type:"text",text:G[0].text,cache_control:j}]:G[0].text;B.push({role:"user",content:A});break}let U=R9(H),z=G.map((j)=>{var A,V,F,D,L,N;let K=(A=R9(j.providerOptions))!=null?A:U;switch(j.type){case"text":return{type:"text",text:j.text,cache_control:K};case"file":{if((V=j.mediaType)==null?void 0:V.startsWith("image/"))return{type:"image_url",image_url:{url:UJ({part:j,defaultMediaType:"image/jpeg"})},cache_control:K};let M=String((N=(L=(D=(F=j.providerOptions)==null?void 0:F.openrouter)==null?void 0:D.filename)!=null?L:j.filename)!=null?N:""),w=UJ({part:j,defaultMediaType:"application/pdf"});if(aJ({url:w,protocols:new Set(["http:","https:"])}))return{type:"file",file:{filename:M,file_data:w}};return{type:"file",file:{filename:M,file_data:w},cache_control:K}}default:return{type:"text",text:"",cache_control:K}}});B.push({role:"user",content:z});break}case"assistant":{let U="",z="",j=[],A=[];for(let V of G)switch(V.type){case"text":{U+=V.text;break}case"tool-call":{A.push({id:V.toolCallId,type:"function",function:{name:V.toolName,arguments:JSON.stringify(V.input)}});break}case"reasoning":{z+=V.text,j.push({type:"reasoning.text",text:V.text});break}case"file":break;default:break}B.push({role:"assistant",content:U,tool_calls:A.length>0?A:void 0,reasoning:z||void 0,reasoning_details:j.length>0?j:void 0,cache_control:R9(H)});break}case"tool":{for(let U of G){let z=$q(U);B.push({role:"tool",tool_call_id:U.toolCallId,content:z,cache_control:(X=R9(H))!=null?X:R9(U.providerOptions)})}break}default:break}return B}function $q(Q){return Q.output.type==="text"?Q.output.value:JSON.stringify(Q.output.value)}var yV=W.union([W.literal("auto"),W.literal("none"),W.literal("required"),W.object({type:W.literal("function"),function:W.object({name:W.string()})})]);function fq(Q){switch(Q.type){case"auto":case"none":case"required":return Q.type;case"tool":return{type:"function",function:{name:Q.toolName}};default:throw Error(`Invalid tool choice type: ${Q}`)}}var hq=W.object({type:W.literal("image_url"),image_url:W.object({url:W.string()})}),mq=W.union([hq,W.unknown().transform(()=>null)]),sJ=W.array(mq).transform((Q)=>Q.filter((Y)=>!!Y)),oJ=W.object({id:W.string().optional(),model:W.string().optional(),provider:W.string().optional(),usage:W.object({prompt_tokens:W.number(),prompt_tokens_details:W.object({cached_tokens:W.number()}).nullish(),completion_tokens:W.number(),completion_tokens_details:W.object({reasoning_tokens:W.number()}).nullish(),total_tokens:W.number(),cost:W.number().optional(),cost_details:W.object({upstream_inference_cost:W.number().nullish()}).nullish()}).nullish()}),uq=oJ.extend({choices:W.array(W.object({message:W.object({role:W.literal("assistant"),content:W.string().nullable().optional(),reasoning:W.string().nullable().optional(),reasoning_details:CX.nullish(),images:sJ.nullish(),tool_calls:W.array(W.object({id:W.string().optional().nullable(),type:W.literal("function"),function:W.object({name:W.string(),arguments:W.string()})})).optional(),annotations:W.array(W.object({type:W.enum(["url_citation"]),url_citation:W.object({end_index:W.number(),start_index:W.number(),title:W.string(),url:W.string(),content:W.string().optional()})})).nullish()}),index:W.number().nullish(),logprobs:W.object({content:W.array(W.object({token:W.string(),logprob:W.number(),top_logprobs:W.array(W.object({token:W.string(),logprob:W.number()}))})).nullable()}).nullable().optional(),finish_reason:W.string().optional().nullable()}))}),cq=W.union([oJ.extend({choices:W.array(W.object({delta:W.object({role:W.enum(["assistant"]).optional(),content:W.string().nullish(),reasoning:W.string().nullish().optional(),reasoning_details:CX.nullish(),images:sJ.nullish(),tool_calls:W.array(W.object({index:W.number().nullish(),id:W.string().nullish(),type:W.literal("function").optional(),function:W.object({name:W.string().nullish(),arguments:W.string().nullish()})})).nullish(),annotations:W.array(W.object({type:W.enum(["url_citation"]),url_citation:W.object({end_index:W.number(),start_index:W.number(),title:W.string(),url:W.string(),content:W.string().optional()})})).nullish()}).nullish(),logprobs:W.object({content:W.array(W.object({token:W.string(),logprob:W.number(),top_logprobs:W.array(W.object({token:W.string(),logprob:W.number()}))})).nullable()}).nullish(),finish_reason:W.string().nullable().optional(),index:W.number().nullish()}))}),bX]),dq=class{constructor(Q,Y,J){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=Q,this.settings=Y,this.config=J}getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,frequencyPenalty:B,presencePenalty:q,seed:G,stopSequences:H,responseFormat:U,topK:z,tools:j,toolChoice:A}){var V;let F=W1(W1({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs==="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs==="number"?this.settings.logprobs:typeof this.settings.logprobs==="boolean"?this.settings.logprobs?0:void 0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:Y,temperature:J,top_p:X,frequency_penalty:B,presence_penalty:q,seed:G,stop:H,response_format:U,top_k:z,messages:yq(Q),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody);if((U==null?void 0:U.type)==="json"&&U.schema!=null)return CQ(W1({},F),{response_format:{type:"json_schema",json_schema:W1({schema:U.schema,strict:!0,name:(V=U.name)!=null?V:"response"},U.description&&{description:U.description})}});if(j&&j.length>0){let D=j.filter((L)=>L.type==="function").map((L)=>({type:"function",function:{name:L.name,description:L.description,parameters:L.inputSchema}}));return CQ(W1({},F),{tools:D,tool_choice:A?fq(A):void 0})}return F}async doGenerate(Q){var Y,J,X,B,q,G,H,U,z,j,A,V,F,D,L,N,K,M,w,_,g,S,C,T;let k=(Q.providerOptions||{}).openrouter||{},I=W1(W1({},this.getArgs(Q)),k),{value:E,responseHeaders:R}=await _Q({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:TQ(this.config.headers(),Q.headers),body:I,failedResponseHandler:kQ,successfulResponseHandler:iJ(uq),abortSignal:Q.abortSignal,fetch:this.config.fetch}),Z=E.choices[0];if(!Z)throw Error("No choice in response");let v=E.usage?{inputTokens:(Y=E.usage.prompt_tokens)!=null?Y:0,outputTokens:(J=E.usage.completion_tokens)!=null?J:0,totalTokens:((X=E.usage.prompt_tokens)!=null?X:0)+((B=E.usage.completion_tokens)!=null?B:0),reasoningTokens:(G=(q=E.usage.completion_tokens_details)==null?void 0:q.reasoning_tokens)!=null?G:0,cachedInputTokens:(U=(H=E.usage.prompt_tokens_details)==null?void 0:H.cached_tokens)!=null?U:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},y=(z=Z.message.reasoning_details)!=null?z:[],m=y.length>0?y.map((l)=>{switch(l.type){case"reasoning.text":{if(l.text)return{type:"reasoning",text:l.text};break}case"reasoning.summary":{if(l.summary)return{type:"reasoning",text:l.summary};break}case"reasoning.encrypted":{if(l.data)return{type:"reasoning",text:"[REDACTED]"};break}default:}return null}).filter((l)=>l!==null):Z.message.reasoning?[{type:"reasoning",text:Z.message.reasoning}]:[],i=[];if(i.push(...m),Z.message.content)i.push({type:"text",text:Z.message.content});if(Z.message.tool_calls)for(let l of Z.message.tool_calls)i.push({type:"tool-call",toolCallId:(j=l.id)!=null?j:$1(),toolName:l.function.name,input:l.function.arguments});if(Z.message.images)for(let l of Z.message.images)i.push({type:"file",mediaType:LJ(l.image_url.url,"image/jpeg"),data:FJ(l.image_url.url)});if(Z.message.annotations){for(let l of Z.message.annotations)if(l.type==="url_citation")i.push({type:"source",sourceType:"url",id:l.url_citation.url,url:l.url_citation.url,title:l.url_citation.title,providerMetadata:{openrouter:{content:l.url_citation.content||""}}})}return{content:i,finishReason:vQ(Z.finish_reason),usage:v,warnings:[],providerMetadata:{openrouter:{provider:(A=E.provider)!=null?A:"",usage:{promptTokens:(V=v.inputTokens)!=null?V:0,completionTokens:(F=v.outputTokens)!=null?F:0,totalTokens:(D=v.totalTokens)!=null?D:0,cost:(L=E.usage)==null?void 0:L.cost,promptTokensDetails:{cachedTokens:(M=(K=(N=E.usage)==null?void 0:N.prompt_tokens_details)==null?void 0:K.cached_tokens)!=null?M:0},completionTokensDetails:{reasoningTokens:(g=(_=(w=E.usage)==null?void 0:w.completion_tokens_details)==null?void 0:_.reasoning_tokens)!=null?g:0},costDetails:{upstreamInferenceCost:(T=(C=(S=E.usage)==null?void 0:S.cost_details)==null?void 0:C.upstream_inference_cost)!=null?T:0}}}},request:{body:I},response:{id:E.id,modelId:E.model,headers:R}}}async doStream(Q){var Y;let X=(Q.providerOptions||{}).openrouter||{},B=W1(W1({},this.getArgs(Q)),X),{value:q,responseHeaders:G}=await _Q({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:TQ(this.config.headers(),Q.headers),body:CQ(W1({},B),{stream:!0,stream_options:this.config.compatibility==="strict"?W1({include_usage:!0},((Y=this.settings.usage)==null?void 0:Y.include)?{include_usage:!0}:{}):void 0}),failedResponseHandler:kQ,successfulResponseHandler:nJ(cq),abortSignal:Q.abortSignal,fetch:this.config.fetch}),H=[],U="other",z={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},j={},A=!1,V=!1,F,D,L,N;return{stream:q.pipeThrough(new TransformStream({transform(K,M){var w,_,g,S,C,T,b,k,I,E,R,Z,v,y;if(!K.success){U="error",M.enqueue({type:"error",error:K.error});return}let m=K.value;if("error"in m){U="error",M.enqueue({type:"error",error:m.error});return}if(m.provider)N=m.provider;if(m.id)L=m.id,M.enqueue({type:"response-metadata",id:m.id});if(m.model)M.enqueue({type:"response-metadata",modelId:m.model});if(m.usage!=null){if(z.inputTokens=m.usage.prompt_tokens,z.outputTokens=m.usage.completion_tokens,z.totalTokens=m.usage.prompt_tokens+m.usage.completion_tokens,j.promptTokens=m.usage.prompt_tokens,m.usage.prompt_tokens_details){let d=(w=m.usage.prompt_tokens_details.cached_tokens)!=null?w:0;z.cachedInputTokens=d,j.promptTokensDetails={cachedTokens:d}}if(j.completionTokens=m.usage.completion_tokens,m.usage.completion_tokens_details){let d=(_=m.usage.completion_tokens_details.reasoning_tokens)!=null?_:0;z.reasoningTokens=d,j.completionTokensDetails={reasoningTokens:d}}j.cost=m.usage.cost,j.totalTokens=m.usage.total_tokens}let i=m.choices[0];if((i==null?void 0:i.finish_reason)!=null)U=vQ(i.finish_reason);if((i==null?void 0:i.delta)==null)return;let l=i.delta,r=(d)=>{if(!V)D=L||$1(),M.enqueue({type:"reasoning-start",id:D}),V=!0;M.enqueue({type:"reasoning-delta",delta:d,id:D||$1()})};if(l.reasoning_details&&l.reasoning_details.length>0)for(let d of l.reasoning_details)switch(d.type){case"reasoning.text":{if(d.text)r(d.text);break}case"reasoning.encrypted":{if(d.data)r("[REDACTED]");break}case"reasoning.summary":{if(d.summary)r(d.summary);break}default:break}else if(l.reasoning)r(l.reasoning);if(l.content){if(V&&!A)M.enqueue({type:"reasoning-end",id:D||$1()}),V=!1;if(!A)F=L||$1(),M.enqueue({type:"text-start",id:F}),A=!0;M.enqueue({type:"text-delta",delta:l.content,id:F||$1()})}if(l.annotations){for(let d of l.annotations)if(d.type==="url_citation")M.enqueue({type:"source",sourceType:"url",id:d.url_citation.url,url:d.url_citation.url,title:d.url_citation.title,providerMetadata:{openrouter:{content:d.url_citation.content||""}}})}if(l.tool_calls!=null)for(let d of l.tool_calls){let t=(g=d.index)!=null?g:H.length-1;if(H[t]==null){if(d.type!=="function")throw new RX({data:d,message:"Expected 'function' type."});if(d.id==null)throw new RX({data:d,message:"Expected 'id' to be a string."});if(((S=d.function)==null?void 0:S.name)==null)throw new RX({data:d,message:"Expected 'function.name' to be a string."});H[t]={id:d.id,type:"function",function:{name:d.function.name,arguments:(C=d.function.arguments)!=null?C:""},inputStarted:!1,sent:!1};let $=H[t];if($==null)throw Error("Tool call is missing");if(((T=$.function)==null?void 0:T.name)!=null&&((b=$.function)==null?void 0:b.arguments)!=null&&EX($.function.arguments))$.inputStarted=!0,M.enqueue({type:"tool-input-start",id:$.id,toolName:$.function.name}),M.enqueue({type:"tool-input-delta",id:$.id,delta:$.function.arguments}),M.enqueue({type:"tool-input-end",id:$.id}),M.enqueue({type:"tool-call",toolCallId:$.id,toolName:$.function.name,input:$.function.arguments}),$.sent=!0;continue}let Q0=H[t];if(Q0==null)throw Error("Tool call is missing");if(!Q0.inputStarted)Q0.inputStarted=!0,M.enqueue({type:"tool-input-start",id:Q0.id,toolName:Q0.function.name});if(((k=d.function)==null?void 0:k.arguments)!=null)Q0.function.arguments+=(E=(I=d.function)==null?void 0:I.arguments)!=null?E:"";if(M.enqueue({type:"tool-input-delta",id:Q0.id,delta:(R=d.function.arguments)!=null?R:""}),((Z=Q0.function)==null?void 0:Z.name)!=null&&((v=Q0.function)==null?void 0:v.arguments)!=null&&EX(Q0.function.arguments))M.enqueue({type:"tool-call",toolCallId:(y=Q0.id)!=null?y:$1(),toolName:Q0.function.name,input:Q0.function.arguments}),Q0.sent=!0}if(l.images!=null)for(let d of l.images)M.enqueue({type:"file",mediaType:LJ(d.image_url.url,"image/jpeg"),data:FJ(d.image_url.url)})},flush(K){var M;if(U==="tool-calls"){for(let _ of H)if(_&&!_.sent)K.enqueue({type:"tool-call",toolCallId:(M=_.id)!=null?M:$1(),toolName:_.function.name,input:EX(_.function.arguments)?_.function.arguments:"{}"}),_.sent=!0}if(V)K.enqueue({type:"reasoning-end",id:D||$1()});if(A)K.enqueue({type:"text-end",id:F||$1()});let w={usage:j};if(N!==void 0)w.provider=N;K.enqueue({type:"finish",finishReason:U,usage:z,providerMetadata:{openrouter:w}})}})),warnings:[],request:{body:B},response:{headers:G}}}};function lq({prompt:Q,inputFormat:Y,user:J="user",assistant:X="assistant"}){if(Y==="prompt"&&Q.length===1&&Q[0]&&Q[0].role==="user"&&Q[0].content.length===1&&Q[0].content[0]&&Q[0].content[0].type==="text")return{prompt:Q[0].content[0].text};let B="";if(Q[0]&&Q[0].role==="system")B+=`${Q[0].content}
32
-
33
- `,Q=Q.slice(1);for(let{role:q,content:G}of Q)switch(q){case"system":throw new $B({message:`Unexpected system message in prompt: ${G}`,prompt:Q});case"user":{let H=G.map((U)=>{switch(U.type){case"text":return U.text;case"file":throw new Z9({functionality:"file attachments"});default:return""}}).join("");B+=`${J}:
34
- ${H}
35
-
36
- `;break}case"assistant":{let H=G.map((U)=>{switch(U.type){case"text":return U.text;case"tool-call":throw new Z9({functionality:"tool-call messages"});case"tool-result":throw new Z9({functionality:"tool-result messages"});case"reasoning":throw new Z9({functionality:"reasoning messages"});case"file":throw new Z9({functionality:"file attachments"});default:return""}}).join("");B+=`${X}:
37
- ${H}
38
-
39
- `;break}case"tool":throw new Z9({functionality:"tool messages"});default:break}return B+=`${X}:
40
- `,{prompt:B}}var NJ=W.union([W.object({id:W.string().optional(),model:W.string().optional(),choices:W.array(W.object({text:W.string(),reasoning:W.string().nullish().optional(),reasoning_details:CX.nullish(),finish_reason:W.string().nullish(),index:W.number().nullish(),logprobs:W.object({tokens:W.array(W.string()),token_logprobs:W.array(W.number()),top_logprobs:W.array(W.record(W.string(),W.number())).nullable()}).nullable().optional()})),usage:W.object({prompt_tokens:W.number(),prompt_tokens_details:W.object({cached_tokens:W.number()}).nullish(),completion_tokens:W.number(),completion_tokens_details:W.object({reasoning_tokens:W.number()}).nullish(),total_tokens:W.number(),cost:W.number().optional()}).nullish()}),bX]),pq=class{constructor(Q,Y,J){this.specificationVersion="v2",this.provider="openrouter",this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=Q,this.settings=Y,this.config=J}getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,frequencyPenalty:B,presencePenalty:q,seed:G,responseFormat:H,topK:U,stopSequences:z,tools:j,toolChoice:A}){let{prompt:V}=lq({prompt:Q,inputFormat:"prompt"});if(j==null?void 0:j.length)throw new Z9({functionality:"tools"});if(A)throw new Z9({functionality:"toolChoice"});return W1(W1({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs==="number"?this.settings.logprobs:typeof this.settings.logprobs==="boolean"?this.settings.logprobs?0:void 0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:Y,temperature:J,top_p:X,frequency_penalty:B,presence_penalty:q,seed:G,stop:z,response_format:H,top_k:U,prompt:V,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate(Q){var Y,J,X,B,q,G,H,U,z,j,A,V,F,D,L;let K=(Q.providerOptions||{}).openrouter||{},M=W1(W1({},this.getArgs(Q)),K),{value:w,responseHeaders:_}=await _Q({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:TQ(this.config.headers(),Q.headers),body:M,failedResponseHandler:kQ,successfulResponseHandler:iJ(NJ),abortSignal:Q.abortSignal,fetch:this.config.fetch});if("error"in w)throw Error(`${w.error.message}`);let g=w.choices[0];if(!g)throw Error("No choice in OpenRouter completion response");return{content:[{type:"text",text:(Y=g.text)!=null?Y:""}],finishReason:vQ(g.finish_reason),usage:{inputTokens:(X=(J=w.usage)==null?void 0:J.prompt_tokens)!=null?X:0,outputTokens:(q=(B=w.usage)==null?void 0:B.completion_tokens)!=null?q:0,totalTokens:((H=(G=w.usage)==null?void 0:G.prompt_tokens)!=null?H:0)+((z=(U=w.usage)==null?void 0:U.completion_tokens)!=null?z:0),reasoningTokens:(V=(A=(j=w.usage)==null?void 0:j.completion_tokens_details)==null?void 0:A.reasoning_tokens)!=null?V:0,cachedInputTokens:(L=(D=(F=w.usage)==null?void 0:F.prompt_tokens_details)==null?void 0:D.cached_tokens)!=null?L:0},warnings:[],response:{headers:_}}}async doStream(Q){let J=(Q.providerOptions||{}).openrouter||{},X=W1(W1({},this.getArgs(Q)),J),{value:B,responseHeaders:q}=await _Q({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:TQ(this.config.headers(),Q.headers),body:CQ(W1({},X),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:kQ,successfulResponseHandler:nJ(NJ),abortSignal:Q.abortSignal,fetch:this.config.fetch}),G="other",H={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},U={};return{stream:B.pipeThrough(new TransformStream({transform(z,j){var A,V;if(!z.success){G="error",j.enqueue({type:"error",error:z.error});return}let F=z.value;if("error"in F){G="error",j.enqueue({type:"error",error:F.error});return}if(F.usage!=null){if(H.inputTokens=F.usage.prompt_tokens,H.outputTokens=F.usage.completion_tokens,H.totalTokens=F.usage.prompt_tokens+F.usage.completion_tokens,U.promptTokens=F.usage.prompt_tokens,F.usage.prompt_tokens_details){let L=(A=F.usage.prompt_tokens_details.cached_tokens)!=null?A:0;H.cachedInputTokens=L,U.promptTokensDetails={cachedTokens:L}}if(U.completionTokens=F.usage.completion_tokens,F.usage.completion_tokens_details){let L=(V=F.usage.completion_tokens_details.reasoning_tokens)!=null?V:0;H.reasoningTokens=L,U.completionTokensDetails={reasoningTokens:L}}U.cost=F.usage.cost,U.totalTokens=F.usage.total_tokens}let D=F.choices[0];if((D==null?void 0:D.finish_reason)!=null)G=vQ(D.finish_reason);if((D==null?void 0:D.text)!=null)j.enqueue({type:"text-delta",delta:D.text,id:$1()})},flush(z){z.enqueue({type:"finish",finishReason:G,usage:H,providerMetadata:{openrouter:{usage:U}}})}})),response:{headers:q}}}};function TX(Q={}){var Y,J,X;let B=(J=Tq((Y=Q.baseURL)!=null?Y:Q.baseUrl))!=null?J:"https://openrouter.ai/api/v1",q=(X=Q.compatibility)!=null?X:"compatible",G=()=>W1({Authorization:`Bearer ${Nq({apiKey:Q.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},Q.headers),H=(A,V={})=>new dq(A,V,{provider:"openrouter.chat",url:({path:F})=>`${B}${F}`,headers:G,compatibility:q,fetch:Q.fetch,extraBody:Q.extraBody}),U=(A,V={})=>new pq(A,V,{provider:"openrouter.completion",url:({path:F})=>`${B}${F}`,headers:G,compatibility:q,fetch:Q.fetch,extraBody:Q.extraBody}),z=(A,V)=>{if(new.target)throw Error("The OpenRouter model function cannot be called with the new keyword.");if(A==="openai/gpt-3.5-turbo-instruct")return U(A,V);return H(A,V)},j=(A,V)=>z(A,V);return j.languageModel=z,j.chat=H,j.completion=U,j}var mV=TX({compatibility:"strict"});class _X{id="openrouter";name="OpenRouter";getConfigSchema(){return[{key:"api-key",label:"API Key",type:"string",required:!0,secret:!0,description:"Get your API key from https://openrouter.ai",placeholder:"sk-or-..."}]}isConfigured(Q){return!!Q["api-key"]}async fetchModels(Q){let Y=Q["api-key"],J=2,X;for(let q=0;q<=2;q++)try{let G=await fetch("https://openrouter.ai/api/v1/models",{headers:Y?{Authorization:`Bearer ${Y}`}:{},signal:AbortSignal.timeout(1e4)});if(!G.ok)throw Error(`API returned ${G.status}: ${G.statusText}`);return(await G.json()).data.map((U)=>({id:U.id,name:U.name||U.id}))}catch(G){if(X=G,q<2)await new Promise((H)=>setTimeout(H,100*Math.pow(2,q)))}let B=X instanceof Error?X.message:String(X);throw Error(`Failed to fetch models after 3 attempts: ${B}`)}async getModelDetails(Q,Y){let J=Y?.apiKey;try{let B=await fetch("https://openrouter.ai/api/v1/models",{headers:J?{Authorization:`Bearer ${J}`}:{}});if(B.ok){let G=(await B.json()).data.find((H)=>H.id===Q);if(G)return{contextLength:G.context_length,maxOutput:G.top_provider?.max_completion_tokens,inputPrice:parseFloat(G.pricing?.prompt||"0"),outputPrice:parseFloat(G.pricing?.completion||"0")}}}catch{}let X=await O9(Q);if(X)return{contextLength:X.contextLength,maxOutput:X.maxOutput,inputPrice:X.inputPrice,outputPrice:X.outputPrice};return null}createClient(Q,Y){let J=Q["api-key"];return TX({apiKey:J})(Y)}}var nq=({prefix:Q,size:Y=16,alphabet:J="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:X="-"}={})=>{let B=()=>{let q=J.length,G=Array(Y);for(let H=0;H<Y;H++)G[H]=J[Math.random()*q|0];return G.join("")};if(Q==null)return B;if(J.includes(X))throw new a9({argument:"separator",message:`The separator "${X}" must not be part of the alphabet "${J}".`});return()=>`${Q}${X}${B()}`},U9=nq();var WD=Symbol("Let zodToJsonSchema decide on which parser to use");var GD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var qW=HN(eJ(),1);import{existsSync as ZN}from"fs";import{join as W5}from"path";import{fileURLToPath as xH}from"url";import{setMaxListeners as gH}from"events";import{spawn as $H}from"child_process";import{createInterface as fH}from"readline";import*as K0 from"fs";import{stat as hH,open as KD}from"fs/promises";import{join as _U}from"path";import{homedir as kU}from"os";import{dirname as gX,join as C5}from"path";import{cwd as xU}from"process";import{realpathSync as gU}from"fs";import{randomUUID as yU}from"crypto";var{create:aq,getPrototypeOf:sq,defineProperty:xX,getOwnPropertyNames:oq}=Object,rq=Object.prototype.hasOwnProperty,tq=(Q,Y,J)=>{J=Q!=null?aq(sq(Q)):{};let X=Y||!Q||!Q.__esModule?xX(J,"default",{value:Q,enumerable:!0}):J;for(let B of oq(Q))if(!rq.call(X,B))xX(X,B,{get:()=>Q[B],enumerable:!0});return X},V0=(Q,Y)=>()=>(Y||Q((Y={exports:{}}).exports,Y),Y.exports),eq=(Q,Y)=>{for(var J in Y)xX(Q,J,{get:Y[J],enumerable:!0,configurable:!0,set:(X)=>Y[J]=()=>X})},QH=V0((Q,Y)=>{(function(J,X){typeof Q==="object"&&typeof Y<"u"?X(Q):typeof define==="function"&&define.amd?define(["exports"],X):X(J.URI=J.URI||{})})(Q,function(J){function X(){for(var x=arguments.length,P=Array(x),f=0;f<x;f++)P[f]=arguments[f];if(P.length>1){P[0]=P[0].slice(0,-1);var u=P.length-1;for(var c=1;c<u;++c)P[c]=P[c].slice(1,-1);return P[u]=P[u].slice(1),P.join("")}else return P[0]}function B(x){return"(?:"+x+")"}function q(x){return x===void 0?"undefined":x===null?"null":Object.prototype.toString.call(x).split(" ").pop().split("]").shift().toLowerCase()}function G(x){return x.toUpperCase()}function H(x){return x!==void 0&&x!==null?x instanceof Array?x:typeof x.length!=="number"||x.split||x.setInterval||x.call?[x]:Array.prototype.slice.call(x):[]}function U(x,P){var f=x;if(P)for(var u in P)f[u]=P[u];return f}function z(x){var P="[A-Za-z]",f="[\\x0D]",u="[0-9]",c="[\\x22]",B0=X(u,"[A-Fa-f]"),Z0="[\\x0A]",g0="[\\x20]",f0=B(B("%[EFef]"+B0+"%"+B0+B0+"%"+B0+B0)+"|"+B("%[89A-Fa-f]"+B0+"%"+B0+B0)+"|"+B("%"+B0+B0)),G1="[\\:\\/\\?\\#\\[\\]\\@]",v0="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",o0=X(G1,v0),B1=x?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",i0=x?"[\\uE000-\\uF8FF]":"[]",$0=X(P,u,"[\\-\\.\\_\\~]",B1),r0=B(P+X(P,u,"[\\+\\-\\.]")+"*"),u0=B(B(f0+"|"+X($0,v0,"[\\:]"))+"*"),C9=B(B("25[0-5]")+"|"+B("2[0-4]"+u)+"|"+B("1"+u+u)+"|"+B("[1-9]"+u)+"|"+u),R1=B(B("25[0-5]")+"|"+B("2[0-4]"+u)+"|"+B("1"+u+u)+"|"+B("0?[1-9]"+u)+"|0?0?"+u),C1=B(R1+"\\."+R1+"\\."+R1+"\\."+R1),c0=B(B0+"{1,4}"),Z1=B(B(c0+"\\:"+c0)+"|"+C1),b1=B(B(c0+"\\:")+"{6}"+Z1),d1=B("\\:\\:"+B(c0+"\\:")+"{5}"+Z1),b9=B(B(c0)+"?\\:\\:"+B(c0+"\\:")+"{4}"+Z1),Q9=B(B(B(c0+"\\:")+"{0,1}"+c0)+"?\\:\\:"+B(c0+"\\:")+"{3}"+Z1),C8=B(B(B(c0+"\\:")+"{0,2}"+c0)+"?\\:\\:"+B(c0+"\\:")+"{2}"+Z1),LQ=B(B(B(c0+"\\:")+"{0,3}"+c0)+"?\\:\\:"+c0+"\\:"+Z1),FQ=B(B(B(c0+"\\:")+"{0,4}"+c0)+"?\\:\\:"+Z1),c9=B(B(B(c0+"\\:")+"{0,5}"+c0)+"?\\:\\:"+c0),d9=B(B(B(c0+"\\:")+"{0,6}"+c0)+"?\\:\\:"),X9=B([b1,d1,b9,Q9,C8,LQ,FQ,c9,d9].join("|")),l9=B(B($0+"|"+f0)+"+"),rQ=B(X9+"\\%25"+l9),T9=B(X9+B("\\%25|\\%(?!"+B0+"{2})")+l9),TW=B("[vV]"+B0+"+\\."+X($0,v0,"[\\:]")+"+"),_W=B("\\["+B(T9+"|"+X9+"|"+TW)+"\\]"),F6=B(B(f0+"|"+X($0,v0))+"*"),b8=B(_W+"|"+C1+"(?!"+F6+")|"+F6),T8=B(u+"*"),N6=B(B(u0+"@")+"?"+b8+B("\\:"+T8)+"?"),_8=B(f0+"|"+X($0,v0,"[\\:\\@]")),kW=B(_8+"*"),j6=B(_8+"+"),vW=B(B(f0+"|"+X($0,v0,"[\\@]"))+"+"),Y9=B(B("\\/"+kW)+"*"),p9=B("\\/"+B(j6+Y9)+"?"),tQ=B(vW+Y9),NQ=B(j6+Y9),n9="(?!"+_8+")",tN=B(Y9+"|"+p9+"|"+tQ+"|"+NQ+"|"+n9),i9=B(B(_8+"|"+X("[\\/\\?]",i0))+"*"),k8=B(B(_8+"|[\\/\\?]")+"*"),K6=B(B("\\/\\/"+N6+Y9)+"|"+p9+"|"+NQ+"|"+n9),xW=B(r0+"\\:"+K6+B("\\?"+i9)+"?"+B("\\#"+k8)+"?"),gW=B(B("\\/\\/"+N6+Y9)+"|"+p9+"|"+tQ+"|"+n9),yW=B(gW+B("\\?"+i9)+"?"+B("\\#"+k8)+"?"),eN=B(xW+"|"+yW),Qj=B(r0+"\\:"+K6+B("\\?"+i9)+"?"),Xj="^("+r0+")\\:"+B(B("\\/\\/("+B("("+u0+")@")+"?("+b8+")"+B("\\:("+T8+")")+"?)")+"?("+Y9+"|"+p9+"|"+NQ+"|"+n9+")")+B("\\?("+i9+")")+"?"+B("\\#("+k8+")")+"?$",Yj="^(){0}"+B(B("\\/\\/("+B("("+u0+")@")+"?("+b8+")"+B("\\:("+T8+")")+"?)")+"?("+Y9+"|"+p9+"|"+tQ+"|"+n9+")")+B("\\?("+i9+")")+"?"+B("\\#("+k8+")")+"?$",Jj="^("+r0+")\\:"+B(B("\\/\\/("+B("("+u0+")@")+"?("+b8+")"+B("\\:("+T8+")")+"?)")+"?("+Y9+"|"+p9+"|"+NQ+"|"+n9+")")+B("\\?("+i9+")")+"?$",Wj="^"+B("\\#("+k8+")")+"?$",Gj="^"+B("("+u0+")@")+"?("+b8+")"+B("\\:("+T8+")")+"?$";return{NOT_SCHEME:new RegExp(X("[^]",P,u,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(X("[^\\%\\:]",$0,v0),"g"),NOT_HOST:new RegExp(X("[^\\%\\[\\]\\:]",$0,v0),"g"),NOT_PATH:new RegExp(X("[^\\%\\/\\:\\@]",$0,v0),"g"),NOT_PATH_NOSCHEME:new RegExp(X("[^\\%\\/\\@]",$0,v0),"g"),NOT_QUERY:new RegExp(X("[^\\%]",$0,v0,"[\\:\\@\\/\\?]",i0),"g"),NOT_FRAGMENT:new RegExp(X("[^\\%]",$0,v0,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(X("[^]",$0,v0),"g"),UNRESERVED:new RegExp($0,"g"),OTHER_CHARS:new RegExp(X("[^\\%]",$0,o0),"g"),PCT_ENCODED:new RegExp(f0,"g"),IPV4ADDRESS:new RegExp("^("+C1+")$"),IPV6ADDRESS:new RegExp("^\\[?("+X9+")"+B(B("\\%25|\\%(?!"+B0+"{2})")+"("+l9+")")+"?\\]?$")}}var j=z(!1),A=z(!0),V=function(){function x(P,f){var u=[],c=!0,B0=!1,Z0=void 0;try{for(var g0=P[Symbol.iterator](),f0;!(c=(f0=g0.next()).done);c=!0)if(u.push(f0.value),f&&u.length===f)break}catch(G1){B0=!0,Z0=G1}finally{try{if(!c&&g0.return)g0.return()}finally{if(B0)throw Z0}}return u}return function(P,f){if(Array.isArray(P))return P;else if(Symbol.iterator in Object(P))return x(P,f);else throw TypeError("Invalid attempt to destructure non-iterable instance")}}(),F=function(x){if(Array.isArray(x)){for(var P=0,f=Array(x.length);P<x.length;P++)f[P]=x[P];return f}else return Array.from(x)},D=2147483647,L=36,N=1,K=26,M=38,w=700,_=72,g=128,S="-",C=/^xn--/,T=/[^\0-\x7E]/,b=/[\x2E\u3002\uFF0E\uFF61]/g,k={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=L-N,E=Math.floor,R=String.fromCharCode;function Z(x){throw RangeError(k[x])}function v(x,P){var f=[],u=x.length;while(u--)f[u]=P(x[u]);return f}function y(x,P){var f=x.split("@"),u="";if(f.length>1)u=f[0]+"@",x=f[1];x=x.replace(b,".");var c=x.split("."),B0=v(c,P).join(".");return u+B0}function m(x){var P=[],f=0,u=x.length;while(f<u){var c=x.charCodeAt(f++);if(c>=55296&&c<=56319&&f<u){var B0=x.charCodeAt(f++);if((B0&64512)==56320)P.push(((c&1023)<<10)+(B0&1023)+65536);else P.push(c),f--}else P.push(c)}return P}var i=function(P){return String.fromCodePoint.apply(String,F(P))},l=function(P){if(P-48<10)return P-22;if(P-65<26)return P-65;if(P-97<26)return P-97;return L},r=function(P,f){return P+22+75*(P<26)-((f!=0)<<5)},d=function(P,f,u){var c=0;P=u?E(P/w):P>>1,P+=E(P/f);for(;P>I*K>>1;c+=L)P=E(P/I);return E(c+(I+1)*P/(P+M))},t=function(P){var f=[],u=P.length,c=0,B0=g,Z0=_,g0=P.lastIndexOf(S);if(g0<0)g0=0;for(var f0=0;f0<g0;++f0){if(P.charCodeAt(f0)>=128)Z("not-basic");f.push(P.charCodeAt(f0))}for(var G1=g0>0?g0+1:0;G1<u;){var v0=c;for(var o0=1,B1=L;;B1+=L){if(G1>=u)Z("invalid-input");var i0=l(P.charCodeAt(G1++));if(i0>=L||i0>E((D-c)/o0))Z("overflow");c+=i0*o0;var $0=B1<=Z0?N:B1>=Z0+K?K:B1-Z0;if(i0<$0)break;var r0=L-$0;if(o0>E(D/r0))Z("overflow");o0*=r0}var u0=f.length+1;if(Z0=d(c-v0,u0,v0==0),E(c/u0)>D-B0)Z("overflow");B0+=E(c/u0),c%=u0,f.splice(c++,0,B0)}return String.fromCodePoint.apply(String,f)},Q0=function(P){var f=[];P=m(P);var u=P.length,c=g,B0=0,Z0=_,g0=!0,f0=!1,G1=void 0;try{for(var v0=P[Symbol.iterator](),o0;!(g0=(o0=v0.next()).done);g0=!0){var B1=o0.value;if(B1<128)f.push(R(B1))}}catch(T9){f0=!0,G1=T9}finally{try{if(!g0&&v0.return)v0.return()}finally{if(f0)throw G1}}var i0=f.length,$0=i0;if(i0)f.push(S);while($0<u){var r0=D,u0=!0,C9=!1,R1=void 0;try{for(var C1=P[Symbol.iterator](),c0;!(u0=(c0=C1.next()).done);u0=!0){var Z1=c0.value;if(Z1>=c&&Z1<r0)r0=Z1}}catch(T9){C9=!0,R1=T9}finally{try{if(!u0&&C1.return)C1.return()}finally{if(C9)throw R1}}var b1=$0+1;if(r0-c>E((D-B0)/b1))Z("overflow");B0+=(r0-c)*b1,c=r0;var d1=!0,b9=!1,Q9=void 0;try{for(var C8=P[Symbol.iterator](),LQ;!(d1=(LQ=C8.next()).done);d1=!0){var FQ=LQ.value;if(FQ<c&&++B0>D)Z("overflow");if(FQ==c){var c9=B0;for(var d9=L;;d9+=L){var X9=d9<=Z0?N:d9>=Z0+K?K:d9-Z0;if(c9<X9)break;var l9=c9-X9,rQ=L-X9;f.push(R(r(X9+l9%rQ,0))),c9=E(l9/rQ)}f.push(R(r(c9,0))),Z0=d(B0,b1,$0==i0),B0=0,++$0}}}catch(T9){b9=!0,Q9=T9}finally{try{if(!d1&&C8.return)C8.return()}finally{if(b9)throw Q9}}++B0,++c}return f.join("")},$=function(P){return y(P,function(f){return C.test(f)?t(f.slice(4).toLowerCase()):f})},H0=function(P){return y(P,function(f){return T.test(f)?"xn--"+Q0(f):f})},E0={version:"2.1.0",ucs2:{decode:m,encode:i},decode:t,encode:Q0,toASCII:H0,toUnicode:$},M0={};function h(x){var P=x.charCodeAt(0),f=void 0;if(P<16)f="%0"+P.toString(16).toUpperCase();else if(P<128)f="%"+P.toString(16).toUpperCase();else if(P<2048)f="%"+(P>>6|192).toString(16).toUpperCase()+"%"+(P&63|128).toString(16).toUpperCase();else f="%"+(P>>12|224).toString(16).toUpperCase()+"%"+(P>>6&63|128).toString(16).toUpperCase()+"%"+(P&63|128).toString(16).toUpperCase();return f}function n(x){var P="",f=0,u=x.length;while(f<u){var c=parseInt(x.substr(f+1,2),16);if(c<128)P+=String.fromCharCode(c),f+=3;else if(c>=194&&c<224){if(u-f>=6){var B0=parseInt(x.substr(f+4,2),16);P+=String.fromCharCode((c&31)<<6|B0&63)}else P+=x.substr(f,6);f+=6}else if(c>=224){if(u-f>=9){var Z0=parseInt(x.substr(f+4,2),16),g0=parseInt(x.substr(f+7,2),16);P+=String.fromCharCode((c&15)<<12|(Z0&63)<<6|g0&63)}else P+=x.substr(f,9);f+=9}else P+=x.substr(f,3),f+=3}return P}function z0(x,P){function f(u){var c=n(u);return!c.match(P.UNRESERVED)?u:c}if(x.scheme)x.scheme=String(x.scheme).replace(P.PCT_ENCODED,f).toLowerCase().replace(P.NOT_SCHEME,"");if(x.userinfo!==void 0)x.userinfo=String(x.userinfo).replace(P.PCT_ENCODED,f).replace(P.NOT_USERINFO,h).replace(P.PCT_ENCODED,G);if(x.host!==void 0)x.host=String(x.host).replace(P.PCT_ENCODED,f).toLowerCase().replace(P.NOT_HOST,h).replace(P.PCT_ENCODED,G);if(x.path!==void 0)x.path=String(x.path).replace(P.PCT_ENCODED,f).replace(x.scheme?P.NOT_PATH:P.NOT_PATH_NOSCHEME,h).replace(P.PCT_ENCODED,G);if(x.query!==void 0)x.query=String(x.query).replace(P.PCT_ENCODED,f).replace(P.NOT_QUERY,h).replace(P.PCT_ENCODED,G);if(x.fragment!==void 0)x.fragment=String(x.fragment).replace(P.PCT_ENCODED,f).replace(P.NOT_FRAGMENT,h).replace(P.PCT_ENCODED,G);return x}function D0(x){return x.replace(/^0*(.*)/,"$1")||"0"}function a(x,P){var f=x.match(P.IPV4ADDRESS)||[],u=V(f,2),c=u[1];if(c)return c.split(".").map(D0).join(".");else return x}function X0(x,P){var f=x.match(P.IPV6ADDRESS)||[],u=V(f,3),c=u[1],B0=u[2];if(c){var Z0=c.toLowerCase().split("::").reverse(),g0=V(Z0,2),f0=g0[0],G1=g0[1],v0=G1?G1.split(":").map(D0):[],o0=f0.split(":").map(D0),B1=P.IPV4ADDRESS.test(o0[o0.length-1]),i0=B1?7:8,$0=o0.length-i0,r0=Array(i0);for(var u0=0;u0<i0;++u0)r0[u0]=v0[u0]||o0[$0+u0]||"";if(B1)r0[i0-1]=a(r0[i0-1],P);var C9=r0.reduce(function(b1,d1,b9){if(!d1||d1==="0"){var Q9=b1[b1.length-1];if(Q9&&Q9.index+Q9.length===b9)Q9.length++;else b1.push({index:b9,length:1})}return b1},[]),R1=C9.sort(function(b1,d1){return d1.length-b1.length})[0],C1=void 0;if(R1&&R1.length>1){var c0=r0.slice(0,R1.index),Z1=r0.slice(R1.index+R1.length);C1=c0.join(":")+"::"+Z1.join(":")}else C1=r0.join(":");if(B0)C1+="%"+B0;return C1}else return x}var P0=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,_0="".match(/(){0}/)[1]===void 0;function A0(x){var P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},f={},u=P.iri!==!1?A:j;if(P.reference==="suffix")x=(P.scheme?P.scheme+":":"")+"//"+x;var c=x.match(P0);if(c){if(_0){if(f.scheme=c[1],f.userinfo=c[3],f.host=c[4],f.port=parseInt(c[5],10),f.path=c[6]||"",f.query=c[7],f.fragment=c[8],isNaN(f.port))f.port=c[5]}else if(f.scheme=c[1]||void 0,f.userinfo=x.indexOf("@")!==-1?c[3]:void 0,f.host=x.indexOf("//")!==-1?c[4]:void 0,f.port=parseInt(c[5],10),f.path=c[6]||"",f.query=x.indexOf("?")!==-1?c[7]:void 0,f.fragment=x.indexOf("#")!==-1?c[8]:void 0,isNaN(f.port))f.port=x.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?c[4]:void 0;if(f.host)f.host=X0(a(f.host,u),u);if(f.scheme===void 0&&f.userinfo===void 0&&f.host===void 0&&f.port===void 0&&!f.path&&f.query===void 0)f.reference="same-document";else if(f.scheme===void 0)f.reference="relative";else if(f.fragment===void 0)f.reference="absolute";else f.reference="uri";if(P.reference&&P.reference!=="suffix"&&P.reference!==f.reference)f.error=f.error||"URI is not a "+P.reference+" reference.";var B0=M0[(P.scheme||f.scheme||"").toLowerCase()];if(!P.unicodeSupport&&(!B0||!B0.unicodeSupport)){if(f.host&&(P.domainHost||B0&&B0.domainHost))try{f.host=E0.toASCII(f.host.replace(u.PCT_ENCODED,n).toLowerCase())}catch(Z0){f.error=f.error||"Host's domain name can not be converted to ASCII via punycode: "+Z0}z0(f,j)}else z0(f,u);if(B0&&B0.parse)B0.parse(f,P)}else f.error=f.error||"URI can not be parsed.";return f}function l0(x,P){var f=P.iri!==!1?A:j,u=[];if(x.userinfo!==void 0)u.push(x.userinfo),u.push("@");if(x.host!==void 0)u.push(X0(a(String(x.host),f),f).replace(f.IPV6ADDRESS,function(c,B0,Z0){return"["+B0+(Z0?"%25"+Z0:"")+"]"}));if(typeof x.port==="number"||typeof x.port==="string")u.push(":"),u.push(String(x.port));return u.length?u.join(""):void 0}var p0=/^\.\.?\//,y0=/^\/\.(\/|$)/,U1=/^\/\.\.(\/|$)/,e0=/^\/?(?:.|\n)*?(?=\/|$)/;function j1(x){var P=[];while(x.length)if(x.match(p0))x=x.replace(p0,"");else if(x.match(y0))x=x.replace(y0,"/");else if(x.match(U1))x=x.replace(U1,"/"),P.pop();else if(x==="."||x==="..")x="";else{var f=x.match(e0);if(f){var u=f[0];x=x.slice(u.length),P.push(u)}else throw Error("Unexpected dot segment condition")}return P.join("")}function n0(x){var P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},f=P.iri?A:j,u=[],c=M0[(P.scheme||x.scheme||"").toLowerCase()];if(c&&c.serialize)c.serialize(x,P);if(x.host){if(f.IPV6ADDRESS.test(x.host));else if(P.domainHost||c&&c.domainHost)try{x.host=!P.iri?E0.toASCII(x.host.replace(f.PCT_ENCODED,n).toLowerCase()):E0.toUnicode(x.host)}catch(g0){x.error=x.error||"Host's domain name can not be converted to "+(!P.iri?"ASCII":"Unicode")+" via punycode: "+g0}}if(z0(x,f),P.reference!=="suffix"&&x.scheme)u.push(x.scheme),u.push(":");var B0=l0(x,P);if(B0!==void 0){if(P.reference!=="suffix")u.push("//");if(u.push(B0),x.path&&x.path.charAt(0)!=="/")u.push("/")}if(x.path!==void 0){var Z0=x.path;if(!P.absolutePath&&(!c||!c.absolutePath))Z0=j1(Z0);if(B0===void 0)Z0=Z0.replace(/^\/\//,"/%2F");u.push(Z0)}if(x.query!==void 0)u.push("?"),u.push(x.query);if(x.fragment!==void 0)u.push("#"),u.push(x.fragment);return u.join("")}function H1(x,P){var f=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},u=arguments[3],c={};if(!u)x=A0(n0(x,f),f),P=A0(n0(P,f),f);if(f=f||{},!f.tolerant&&P.scheme)c.scheme=P.scheme,c.userinfo=P.userinfo,c.host=P.host,c.port=P.port,c.path=j1(P.path||""),c.query=P.query;else{if(P.userinfo!==void 0||P.host!==void 0||P.port!==void 0)c.userinfo=P.userinfo,c.host=P.host,c.port=P.port,c.path=j1(P.path||""),c.query=P.query;else{if(!P.path)if(c.path=x.path,P.query!==void 0)c.query=P.query;else c.query=x.query;else{if(P.path.charAt(0)==="/")c.path=j1(P.path);else{if((x.userinfo!==void 0||x.host!==void 0||x.port!==void 0)&&!x.path)c.path="/"+P.path;else if(!x.path)c.path=P.path;else c.path=x.path.slice(0,x.path.lastIndexOf("/")+1)+P.path;c.path=j1(c.path)}c.query=P.query}c.userinfo=x.userinfo,c.host=x.host,c.port=x.port}c.scheme=x.scheme}return c.fragment=P.fragment,c}function I1(x,P,f){var u=U({scheme:"null"},f);return n0(H1(A0(x,u),A0(P,u),u,!0),u)}function O1(x,P){if(typeof x==="string")x=n0(A0(x,P),P);else if(q(x)==="object")x=A0(n0(x,P),P);return x}function UQ(x,P,f){if(typeof x==="string")x=n0(A0(x,f),f);else if(q(x)==="object")x=n0(x,f);if(typeof P==="string")P=n0(A0(P,f),f);else if(q(P)==="object")P=n0(P,f);return x===P}function sQ(x,P){return x&&x.toString().replace(!P||!P.iri?j.ESCAPE:A.ESCAPE,h)}function v1(x,P){return x&&x.toString().replace(!P||!P.iri?j.PCT_ENCODED:A.PCT_ENCODED,n)}var S8={scheme:"http",domainHost:!0,parse:function(P,f){if(!P.host)P.error=P.error||"HTTP URIs must have a host.";return P},serialize:function(P,f){var u=String(P.scheme).toLowerCase()==="https";if(P.port===(u?443:80)||P.port==="")P.port=void 0;if(!P.path)P.path="/";return P}},W6={scheme:"https",domainHost:S8.domainHost,parse:S8.parse,serialize:S8.serialize};function G6(x){return typeof x.secure==="boolean"?x.secure:String(x.scheme).toLowerCase()==="wss"}var I8={scheme:"ws",domainHost:!0,parse:function(P,f){var u=P;return u.secure=G6(u),u.resourceName=(u.path||"/")+(u.query?"?"+u.query:""),u.path=void 0,u.query=void 0,u},serialize:function(P,f){if(P.port===(G6(P)?443:80)||P.port==="")P.port=void 0;if(typeof P.secure==="boolean")P.scheme=P.secure?"wss":"ws",P.secure=void 0;if(P.resourceName){var u=P.resourceName.split("?"),c=V(u,2),B0=c[0],Z0=c[1];P.path=B0&&B0!=="/"?B0:void 0,P.query=Z0,P.resourceName=void 0}return P.fragment=void 0,P}},B6={scheme:"wss",domainHost:I8.domainHost,parse:I8.parse,serialize:I8.serialize},VW={},DW=!0,q6="[A-Za-z0-9\\-\\.\\_\\~"+(DW?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",c1="[0-9A-Fa-f]",wW=B(B("%[EFef]"+c1+"%"+c1+c1+"%"+c1+c1)+"|"+B("%[89A-Fa-f]"+c1+"%"+c1+c1)+"|"+B("%"+c1+c1)),OW="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",RW="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",ZW=X(RW,"[\\\"\\\\]"),EW="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",PW=new RegExp(q6,"g"),u9=new RegExp(wW,"g"),SW=new RegExp(X("[^]",OW,"[\\.]","[\\\"]",ZW),"g"),H6=new RegExp(X("[^]",q6,EW),"g"),IW=H6;function oQ(x){var P=n(x);return!P.match(PW)?x:P}var z6={scheme:"mailto",parse:function(P,f){var u=P,c=u.to=u.path?u.path.split(","):[];if(u.path=void 0,u.query){var B0=!1,Z0={},g0=u.query.split("&");for(var f0=0,G1=g0.length;f0<G1;++f0){var v0=g0[f0].split("=");switch(v0[0]){case"to":var o0=v0[1].split(",");for(var B1=0,i0=o0.length;B1<i0;++B1)c.push(o0[B1]);break;case"subject":u.subject=v1(v0[1],f);break;case"body":u.body=v1(v0[1],f);break;default:B0=!0,Z0[v1(v0[0],f)]=v1(v0[1],f);break}}if(B0)u.headers=Z0}u.query=void 0;for(var $0=0,r0=c.length;$0<r0;++$0){var u0=c[$0].split("@");if(u0[0]=v1(u0[0]),!f.unicodeSupport)try{u0[1]=E0.toASCII(v1(u0[1],f).toLowerCase())}catch(C9){u.error=u.error||"Email address's domain name can not be converted to ASCII via punycode: "+C9}else u0[1]=v1(u0[1],f).toLowerCase();c[$0]=u0.join("@")}return u},serialize:function(P,f){var u=P,c=H(P.to);if(c){for(var B0=0,Z0=c.length;B0<Z0;++B0){var g0=String(c[B0]),f0=g0.lastIndexOf("@"),G1=g0.slice(0,f0).replace(u9,oQ).replace(u9,G).replace(SW,h),v0=g0.slice(f0+1);try{v0=!f.iri?E0.toASCII(v1(v0,f).toLowerCase()):E0.toUnicode(v0)}catch($0){u.error=u.error||"Email address's domain name can not be converted to "+(!f.iri?"ASCII":"Unicode")+" via punycode: "+$0}c[B0]=G1+"@"+v0}u.path=c.join(",")}var o0=P.headers=P.headers||{};if(P.subject)o0.subject=P.subject;if(P.body)o0.body=P.body;var B1=[];for(var i0 in o0)if(o0[i0]!==VW[i0])B1.push(i0.replace(u9,oQ).replace(u9,G).replace(H6,h)+"="+o0[i0].replace(u9,oQ).replace(u9,G).replace(IW,h));if(B1.length)u.query=B1.join("&");return u}},CW=/^([^\:]+)\:(.*)/,U6={scheme:"urn",parse:function(P,f){var u=P.path&&P.path.match(CW),c=P;if(u){var B0=f.scheme||c.scheme||"urn",Z0=u[1].toLowerCase(),g0=u[2],f0=B0+":"+(f.nid||Z0),G1=M0[f0];if(c.nid=Z0,c.nss=g0,c.path=void 0,G1)c=G1.parse(c,f)}else c.error=c.error||"URN can not be parsed.";return c},serialize:function(P,f){var u=f.scheme||P.scheme||"urn",c=P.nid,B0=u+":"+(f.nid||c),Z0=M0[B0];if(Z0)P=Z0.serialize(P,f);var g0=P,f0=P.nss;return g0.path=(c||f.nid)+":"+f0,g0}},bW=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,L6={scheme:"urn:uuid",parse:function(P,f){var u=P;if(u.uuid=u.nss,u.nss=void 0,!f.tolerant&&(!u.uuid||!u.uuid.match(bW)))u.error=u.error||"UUID is not valid.";return u},serialize:function(P,f){var u=P;return u.nss=(P.uuid||"").toLowerCase(),u}};M0[S8.scheme]=S8,M0[W6.scheme]=W6,M0[I8.scheme]=I8,M0[B6.scheme]=B6,M0[z6.scheme]=z6,M0[U6.scheme]=U6,M0[L6.scheme]=L6,J.SCHEMES=M0,J.pctEncChar=h,J.pctDecChars=n,J.parse=A0,J.removeDotSegments=j1,J.serialize=n0,J.resolveComponents=H1,J.resolve=I1,J.normalize=O1,J.equal=UQ,J.escapeComponent=sQ,J.unescapeComponent=v1,Object.defineProperty(J,"__esModule",{value:!0})})}),cX=V0((Q,Y)=>{Y.exports=function J(X,B){if(X===B)return!0;if(X&&B&&typeof X=="object"&&typeof B=="object"){if(X.constructor!==B.constructor)return!1;var q,G,H;if(Array.isArray(X)){if(q=X.length,q!=B.length)return!1;for(G=q;G--!==0;)if(!J(X[G],B[G]))return!1;return!0}if(X.constructor===RegExp)return X.source===B.source&&X.flags===B.flags;if(X.valueOf!==Object.prototype.valueOf)return X.valueOf()===B.valueOf();if(X.toString!==Object.prototype.toString)return X.toString()===B.toString();if(H=Object.keys(X),q=H.length,q!==Object.keys(B).length)return!1;for(G=q;G--!==0;)if(!Object.prototype.hasOwnProperty.call(B,H[G]))return!1;for(G=q;G--!==0;){var U=H[G];if(!J(X[U],B[U]))return!1}return!0}return X!==X&&B!==B}}),XH=V0((Q,Y)=>{Y.exports=function(X){var B=0,q=X.length,G=0,H;while(G<q)if(B++,H=X.charCodeAt(G++),H>=55296&&H<=56319&&G<q){if(H=X.charCodeAt(G),(H&64512)==56320)G++}return B}}),O8=V0((Q,Y)=>{Y.exports={copy:J,checkDataType:X,checkDataTypes:B,coerceToTypes:G,toHash:H,getProperty:j,escapeQuotes:A,equal:cX(),ucs2length:XH(),varOccurences:V,varReplace:F,schemaHasRules:D,schemaHasRulesExcept:L,schemaUnknownRules:N,toQuotedString:K,getPathExpr:M,getPath:w,getData:S,unescapeFragment:T,unescapeJsonPointer:I,escapeFragment:b,escapeJsonPointer:k};function J(E,R){R=R||{};for(var Z in E)R[Z]=E[Z];return R}function X(E,R,Z,v){var y=v?" !== ":" === ",m=v?" || ":" && ",i=v?"!":"",l=v?"":"!";switch(E){case"null":return R+y+"null";case"array":return i+"Array.isArray("+R+")";case"object":return"("+i+R+m+"typeof "+R+y+'"object"'+m+l+"Array.isArray("+R+"))";case"integer":return"(typeof "+R+y+'"number"'+m+l+"("+R+" % 1)"+m+R+y+R+(Z?m+i+"isFinite("+R+")":"")+")";case"number":return"(typeof "+R+y+'"'+E+'"'+(Z?m+i+"isFinite("+R+")":"")+")";default:return"typeof "+R+y+'"'+E+'"'}}function B(E,R,Z){switch(E.length){case 1:return X(E[0],R,Z,!0);default:var v="",y=H(E);if(y.array&&y.object)v=y.null?"(":"(!"+R+" || ",v+="typeof "+R+' !== "object")',delete y.null,delete y.array,delete y.object;if(y.number)delete y.integer;for(var m in y)v+=(v?" && ":"")+X(m,R,Z,!0);return v}}var q=H(["string","number","integer","boolean","null"]);function G(E,R){if(Array.isArray(R)){var Z=[];for(var v=0;v<R.length;v++){var y=R[v];if(q[y])Z[Z.length]=y;else if(E==="array"&&y==="array")Z[Z.length]=y}if(Z.length)return Z}else if(q[R])return[R];else if(E==="array"&&R==="array")return["array"]}function H(E){var R={};for(var Z=0;Z<E.length;Z++)R[E[Z]]=!0;return R}var U=/^[a-z$_][a-z$_0-9]*$/i,z=/'|\\/g;function j(E){return typeof E=="number"?"["+E+"]":U.test(E)?"."+E:"['"+A(E)+"']"}function A(E){return E.replace(z,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function V(E,R){R+="[^0-9]";var Z=E.match(new RegExp(R,"g"));return Z?Z.length:0}function F(E,R,Z){return R+="([^0-9])",Z=Z.replace(/\$/g,"$$$$"),E.replace(new RegExp(R,"g"),Z+"$1")}function D(E,R){if(typeof E=="boolean")return!E;for(var Z in E)if(R[Z])return!0}function L(E,R,Z){if(typeof E=="boolean")return!E&&Z!="not";for(var v in E)if(v!=Z&&R[v])return!0}function N(E,R){if(typeof E=="boolean")return;for(var Z in E)if(!R[Z])return Z}function K(E){return"'"+A(E)+"'"}function M(E,R,Z,v){var y=Z?"'/' + "+R+(v?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):v?"'[' + "+R+" + ']'":"'[\\'' + "+R+" + '\\']'";return C(E,y)}function w(E,R,Z){var v=Z?K("/"+k(R)):K(j(R));return C(E,v)}var _=/^\/(?:[^~]|~0|~1)*$/,g=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function S(E,R,Z){var v,y,m,i;if(E==="")return"rootData";if(E[0]=="/"){if(!_.test(E))throw Error("Invalid JSON-pointer: "+E);y=E,m="rootData"}else{if(i=E.match(g),!i)throw Error("Invalid JSON-pointer: "+E);if(v=+i[1],y=i[2],y=="#"){if(v>=R)throw Error("Cannot access property/index "+v+" levels up, current level is "+R);return Z[R-v]}if(v>R)throw Error("Cannot access data "+v+" levels up, current level is "+R);if(m="data"+(R-v||""),!y)return m}var l=m,r=y.split("/");for(var d=0;d<r.length;d++){var t=r[d];if(t)m+=j(I(t)),l+=" && "+m}return l}function C(E,R){if(E=='""')return R;return(E+" + "+R).replace(/([^\\])' \+ '/g,"$1")}function T(E){return I(decodeURIComponent(E))}function b(E){return encodeURIComponent(k(E))}function k(E){return E.replace(/~/g,"~0").replace(/\//g,"~1")}function I(E){return E.replace(/~1/g,"/").replace(/~0/g,"~")}}),K5=V0((Q,Y)=>{var J=O8();Y.exports=X;function X(B){J.copy(B,this)}}),YH=V0((Q,Y)=>{var J=Y.exports=function(q,G,H){if(typeof G=="function")H=G,G={};H=G.cb||H;var U=typeof H=="function"?H:H.pre||function(){},z=H.post||function(){};X(G,U,z,q,"",q)};J.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},J.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},J.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},J.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function X(q,G,H,U,z,j,A,V,F,D){if(U&&typeof U=="object"&&!Array.isArray(U)){G(U,z,j,A,V,F,D);for(var L in U){var N=U[L];if(Array.isArray(N)){if(L in J.arrayKeywords)for(var K=0;K<N.length;K++)X(q,G,H,N[K],z+"/"+L+"/"+K,j,z,L,U,K)}else if(L in J.propsKeywords){if(N&&typeof N=="object")for(var M in N)X(q,G,H,N[M],z+"/"+L+"/"+B(M),j,z,L,U,M)}else if(L in J.keywords||q.allKeys&&!(L in J.skipKeywords))X(q,G,H,N,z+"/"+L,j,z,L,U)}H(U,z,j,A,V,F,D)}}function B(q){return q.replace(/~/g,"~0").replace(/\//g,"~1")}}),dX=V0((Q,Y)=>{var J=QH(),X=cX(),B=O8(),q=K5(),G=YH();Y.exports=H,H.normalizeId=w,H.fullPath=N,H.url=_,H.ids=g,H.inlineRef=F,H.schema=U;function H(S,C,T){var b=this._refs[T];if(typeof b=="string")if(this._refs[b])b=this._refs[b];else return H.call(this,S,C,b);if(b=b||this._schemas[T],b instanceof q)return F(b.schema,this._opts.inlineRefs)?b.schema:b.validate||this._compile(b);var k=U.call(this,C,T),I,E,R;if(k)I=k.schema,C=k.root,R=k.baseId;if(I instanceof q)E=I.validate||S.call(this,I.schema,C,void 0,R);else if(I!==void 0)E=F(I,this._opts.inlineRefs)?I:S.call(this,I,C,void 0,R);return E}function U(S,C){var T=J.parse(C),b=K(T),k=N(this._getId(S.schema));if(Object.keys(S.schema).length===0||b!==k){var I=w(b),E=this._refs[I];if(typeof E=="string")return z.call(this,S,E,T);else if(E instanceof q){if(!E.validate)this._compile(E);S=E}else if(E=this._schemas[I],E instanceof q){if(!E.validate)this._compile(E);if(I==w(C))return{schema:E,root:S,baseId:k};S=E}else return;if(!S.schema)return;k=N(this._getId(S.schema))}return A.call(this,T,k,S.schema,S)}function z(S,C,T){var b=U.call(this,S,C);if(b){var{schema:k,baseId:I}=b;S=b.root;var E=this._getId(k);if(E)I=_(I,E);return A.call(this,T,I,k,S)}}var j=B.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function A(S,C,T,b){if(S.fragment=S.fragment||"",S.fragment.slice(0,1)!="/")return;var k=S.fragment.split("/");for(var I=1;I<k.length;I++){var E=k[I];if(E){if(E=B.unescapeFragment(E),T=T[E],T===void 0)break;var R;if(!j[E]){if(R=this._getId(T),R)C=_(C,R);if(T.$ref){var Z=_(C,T.$ref),v=U.call(this,b,Z);if(v)T=v.schema,b=v.root,C=v.baseId}}}}if(T!==void 0&&T!==b.schema)return{schema:T,root:b,baseId:C}}var V=B.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function F(S,C){if(C===!1)return!1;if(C===void 0||C===!0)return D(S);else if(C)return L(S)<=C}function D(S){var C;if(Array.isArray(S)){for(var T=0;T<S.length;T++)if(C=S[T],typeof C=="object"&&!D(C))return!1}else for(var b in S){if(b=="$ref")return!1;if(C=S[b],typeof C=="object"&&!D(C))return!1}return!0}function L(S){var C=0,T;if(Array.isArray(S))for(var b=0;b<S.length;b++){if(T=S[b],typeof T=="object")C+=L(T);if(C==1/0)return 1/0}else for(var k in S){if(k=="$ref")return 1/0;if(V[k])C++;else{if(T=S[k],typeof T=="object")C+=L(T)+1;if(C==1/0)return 1/0}}return C}function N(S,C){if(C!==!1)S=w(S);var T=J.parse(S);return K(T)}function K(S){return J.serialize(S).split("#")[0]+"#"}var M=/#\/?$/;function w(S){return S?S.replace(M,""):""}function _(S,C){return C=w(C),J.resolve(S,C)}function g(S){var C=w(this._getId(S)),T={"":C},b={"":N(C,!1)},k={},I=this;return G(S,{allKeys:!0},function(E,R,Z,v,y,m,i){if(R==="")return;var l=I._getId(E),r=T[v],d=b[v]+"/"+y;if(i!==void 0)d+="/"+(typeof i=="number"?i:B.escapeFragment(i));if(typeof l=="string"){l=r=w(r?J.resolve(r,l):l);var t=I._refs[l];if(typeof t=="string")t=I._refs[t];if(t&&t.schema){if(!X(E,t.schema))throw Error('id "'+l+'" resolves to more than one schema')}else if(l!=w(d))if(l[0]=="#"){if(k[l]&&!X(E,k[l]))throw Error('id "'+l+'" resolves to more than one schema');k[l]=E}else I._refs[l]=d}T[R]=r,b[R]=d}),k}}),lX=V0((Q,Y)=>{var J=dX();Y.exports={Validation:q(X),MissingRef:q(B)};function X(G){this.message="validation failed",this.errors=G,this.ajv=this.validation=!0}B.message=function(G,H){return"can't resolve reference "+H+" from id "+G};function B(G,H,U){this.message=U||B.message(G,H),this.missingRef=J.url(G,H),this.missingSchema=J.normalizeId(J.fullPath(this.missingRef))}function q(G){return G.prototype=Object.create(Error.prototype),G.prototype.constructor=G,G}}),M5=V0((Q,Y)=>{Y.exports=function(J,X){if(!X)X={};if(typeof X==="function")X={cmp:X};var B=typeof X.cycles==="boolean"?X.cycles:!1,q=X.cmp&&function(H){return function(U){return function(z,j){var A={key:z,value:U[z]},V={key:j,value:U[j]};return H(A,V)}}}(X.cmp),G=[];return function H(U){if(U&&U.toJSON&&typeof U.toJSON==="function")U=U.toJSON();if(U===void 0)return;if(typeof U=="number")return isFinite(U)?""+U:"null";if(typeof U!=="object")return JSON.stringify(U);var z,j;if(Array.isArray(U)){j="[";for(z=0;z<U.length;z++){if(z)j+=",";j+=H(U[z])||"null"}return j+"]"}if(U===null)return"null";if(G.indexOf(U)!==-1){if(B)return JSON.stringify("__cycle__");throw TypeError("Converting circular structure to JSON")}var A=G.push(U)-1,V=Object.keys(U).sort(q&&q(U));j="";for(z=0;z<V.length;z++){var F=V[z],D=H(U[F]);if(!D)continue;if(j)j+=",";j+=JSON.stringify(F)+":"+D}return G.splice(A,1),"{"+j+"}"}(J)}}),A5=V0((Q,Y)=>{Y.exports=function(X,B,q){var G="",H=X.schema.$async===!0,U=X.util.schemaHasRulesExcept(X.schema,X.RULES.all,"$ref"),z=X.self._getId(X.schema);if(X.opts.strictKeywords){var j=X.util.schemaUnknownRules(X.schema,X.RULES.keywords);if(j){var A="unknown keyword: "+j;if(X.opts.strictKeywords==="log")X.logger.warn(A);else throw Error(A)}}if(X.isTop){if(G+=" var validate = ",H)X.async=!0,G+="async ";if(G+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",z&&(X.opts.sourceCode||X.opts.processCode))G+=" "+("/*# sourceURL="+z+" */")+" "}if(typeof X.schema=="boolean"||!(U||X.schema.$ref)){var B="false schema",V=X.level,F=X.dataLevel,D=X.schema[B],L=X.schemaPath+X.util.getProperty(B),N=X.errSchemaPath+"/"+B,C=!X.opts.allErrors,k,K="data"+(F||""),S="valid"+V;if(X.schema===!1){if(X.isTop)C=!0;else G+=" var "+S+" = false; ";var M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(k||"false schema")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(N)+" , params: {} ",X.opts.messages!==!1)G+=" , message: 'boolean schema is false' ";if(X.opts.verbose)G+=" , schema: false , parentSchema: validate.schema"+X.schemaPath+" , data: "+K+" ";G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&C)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else if(X.isTop)if(H)G+=" return data; ";else G+=" validate.errors = null; return true; ";else G+=" var "+S+" = true; ";if(X.isTop)G+=" }; return validate; ";return G}if(X.isTop){var _=X.isTop,V=X.level=0,F=X.dataLevel=0,K="data";if(X.rootId=X.resolve.fullPath(X.self._getId(X.root.schema)),X.baseId=X.baseId||X.rootId,delete X.isTop,X.dataPathArr=[""],X.schema.default!==void 0&&X.opts.useDefaults&&X.opts.strictDefaults){var g="default is ignored in the schema root";if(X.opts.strictDefaults==="log")X.logger.warn(g);else throw Error(g)}G+=" var vErrors = null; ",G+=" var errors = 0; ",G+=" if (rootData === undefined) rootData = data; "}else{var{level:V,dataLevel:F}=X,K="data"+(F||"");if(z)X.baseId=X.resolve.url(X.baseId,z);if(H&&!X.async)throw Error("async schema in sync schema");G+=" var errs_"+V+" = errors;"}var S="valid"+V,C=!X.opts.allErrors,T="",b="",k,I=X.schema.type,E=Array.isArray(I);if(I&&X.opts.nullable&&X.schema.nullable===!0){if(E){if(I.indexOf("null")==-1)I=I.concat("null")}else if(I!="null")I=[I,"null"],E=!0}if(E&&I.length==1)I=I[0],E=!1;if(X.schema.$ref&&U){if(X.opts.extendRefs=="fail")throw Error('$ref: validation keywords used in schema at path "'+X.errSchemaPath+'" (see option extendRefs)');else if(X.opts.extendRefs!==!0)U=!1,X.logger.warn('$ref: keywords ignored in schema at path "'+X.errSchemaPath+'"')}if(X.schema.$comment&&X.opts.$comment)G+=" "+X.RULES.all.$comment.code(X,"$comment");if(I){if(X.opts.coerceTypes)var R=X.util.coerceToTypes(X.opts.coerceTypes,I);var Z=X.RULES.types[I];if(R||E||Z===!0||Z&&!e0(Z)){var L=X.schemaPath+".type",N=X.errSchemaPath+"/type",L=X.schemaPath+".type",N=X.errSchemaPath+"/type",v=E?"checkDataTypes":"checkDataType";if(G+=" if ("+X.util[v](I,K,X.opts.strictNumbers,!0)+") { ",R){var y="dataType"+V,m="coerced"+V;if(G+=" var "+y+" = typeof "+K+"; var "+m+" = undefined; ",X.opts.coerceTypes=="array")G+=" if ("+y+" == 'object' && Array.isArray("+K+") && "+K+".length == 1) { "+K+" = "+K+"[0]; "+y+" = typeof "+K+"; if ("+X.util.checkDataType(X.schema.type,K,X.opts.strictNumbers)+") "+m+" = "+K+"; } ";G+=" if ("+m+" !== undefined) ; ";var i=R;if(i){var l,r=-1,d=i.length-1;while(r<d)if(l=i[r+=1],l=="string")G+=" else if ("+y+" == 'number' || "+y+" == 'boolean') "+m+" = '' + "+K+"; else if ("+K+" === null) "+m+" = ''; ";else if(l=="number"||l=="integer"){if(G+=" else if ("+y+" == 'boolean' || "+K+" === null || ("+y+" == 'string' && "+K+" && "+K+" == +"+K+" ",l=="integer")G+=" && !("+K+" % 1)";G+=")) "+m+" = +"+K+"; "}else if(l=="boolean")G+=" else if ("+K+" === 'false' || "+K+" === 0 || "+K+" === null) "+m+" = false; else if ("+K+" === 'true' || "+K+" === 1) "+m+" = true; ";else if(l=="null")G+=" else if ("+K+" === '' || "+K+" === 0 || "+K+" === false) "+m+" = null; ";else if(X.opts.coerceTypes=="array"&&l=="array")G+=" else if ("+y+" == 'string' || "+y+" == 'number' || "+y+" == 'boolean' || "+K+" == null) "+m+" = ["+K+"]; "}G+=" else { ";var M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(k||"type")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(N)+" , params: { type: '",E)G+=""+I.join(",");else G+=""+I;if(G+="' } ",X.opts.messages!==!1){if(G+=" , message: 'should be ",E)G+=""+I.join(",");else G+=""+I;G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+L+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+K+" ";G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&C)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";G+=" } if ("+m+" !== undefined) { ";var t=F?"data"+(F-1||""):"parentData",Q0=F?X.dataPathArr[F]:"parentDataProperty";if(G+=" "+K+" = "+m+"; ",!F)G+="if ("+t+" !== undefined)";G+=" "+t+"["+Q0+"] = "+m+"; } "}else{var M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(k||"type")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(N)+" , params: { type: '",E)G+=""+I.join(",");else G+=""+I;if(G+="' } ",X.opts.messages!==!1){if(G+=" , message: 'should be ",E)G+=""+I.join(",");else G+=""+I;G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+L+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+K+" ";G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&C)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}G+=" } "}}if(X.schema.$ref&&!U){if(G+=" "+X.RULES.all.$ref.code(X,"$ref")+" ",C){if(G+=" } if (errors === ",_)G+="0";else G+="errs_"+V;G+=") { ",b+="}"}}else{var $=X.RULES;if($){var Z,H0=-1,E0=$.length-1;while(H0<E0)if(Z=$[H0+=1],e0(Z)){if(Z.type)G+=" if ("+X.util.checkDataType(Z.type,K,X.opts.strictNumbers)+") { ";if(X.opts.useDefaults){if(Z.type=="object"&&X.schema.properties){var D=X.schema.properties,M0=Object.keys(D),h=M0;if(h){var n,z0=-1,D0=h.length-1;while(z0<D0){n=h[z0+=1];var a=D[n];if(a.default!==void 0){var X0=K+X.util.getProperty(n);if(X.compositeRule){if(X.opts.strictDefaults){var g="default is ignored for: "+X0;if(X.opts.strictDefaults==="log")X.logger.warn(g);else throw Error(g)}}else{if(G+=" if ("+X0+" === undefined ",X.opts.useDefaults=="empty")G+=" || "+X0+" === null || "+X0+" === '' ";if(G+=" ) "+X0+" = ",X.opts.useDefaults=="shared")G+=" "+X.useDefault(a.default)+" ";else G+=" "+JSON.stringify(a.default)+" ";G+="; "}}}}}else if(Z.type=="array"&&Array.isArray(X.schema.items)){var P0=X.schema.items;if(P0){var a,r=-1,_0=P0.length-1;while(r<_0)if(a=P0[r+=1],a.default!==void 0){var X0=K+"["+r+"]";if(X.compositeRule){if(X.opts.strictDefaults){var g="default is ignored for: "+X0;if(X.opts.strictDefaults==="log")X.logger.warn(g);else throw Error(g)}}else{if(G+=" if ("+X0+" === undefined ",X.opts.useDefaults=="empty")G+=" || "+X0+" === null || "+X0+" === '' ";if(G+=" ) "+X0+" = ",X.opts.useDefaults=="shared")G+=" "+X.useDefault(a.default)+" ";else G+=" "+JSON.stringify(a.default)+" ";G+="; "}}}}}var A0=Z.rules;if(A0){var l0,p0=-1,y0=A0.length-1;while(p0<y0)if(l0=A0[p0+=1],j1(l0)){var U1=l0.code(X,l0.keyword,Z.type);if(U1){if(G+=" "+U1+" ",C)T+="}"}}}if(C)G+=" "+T+" ",T="";if(Z.type){if(G+=" } ",I&&I===Z.type&&!R){G+=" else { ";var L=X.schemaPath+".type",N=X.errSchemaPath+"/type",M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(k||"type")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(N)+" , params: { type: '",E)G+=""+I.join(",");else G+=""+I;if(G+="' } ",X.opts.messages!==!1){if(G+=" , message: 'should be ",E)G+=""+I.join(",");else G+=""+I;G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+L+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+K+" ";G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&C)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";G+=" } "}}if(C){if(G+=" if (errors === ",_)G+="0";else G+="errs_"+V;G+=") { ",b+="}"}}}}if(C)G+=" "+b+" ";if(_){if(H)G+=" if (errors === 0) return data; ",G+=" else throw new ValidationError(vErrors); ";else G+=" validate.errors = vErrors; ",G+=" return errors === 0; ";G+=" }; return validate;"}else G+=" var "+S+" = errors === errs_"+V+";";function e0(H1){var I1=H1.rules;for(var O1=0;O1<I1.length;O1++)if(j1(I1[O1]))return!0}function j1(H1){return X.schema[H1.keyword]!==void 0||H1.implements&&n0(H1)}function n0(H1){var I1=H1.implements;for(var O1=0;O1<I1.length;O1++)if(X.schema[I1[O1]]!==void 0)return!0}return G}}),JH=V0((Q,Y)=>{var J=dX(),X=O8(),B=lX(),q=M5(),G=A5(),H=X.ucs2length,U=cX(),z=B.Validation;Y.exports=j;function j(w,_,g,S){var C=this,T=this._opts,b=[void 0],k={},I=[],E={},R=[],Z={},v=[];_=_||{schema:w,refVal:b,refs:k};var y=A.call(this,w,_,S),m=this._compilations[y.index];if(y.compiling)return m.callValidate=t;var i=this._formats,l=this.RULES;try{var r=Q0(w,_,g,S);m.validate=r;var d=m.callValidate;if(d){if(d.schema=r.schema,d.errors=null,d.refs=r.refs,d.refVal=r.refVal,d.root=r.root,d.$async=r.$async,T.sourceCode)d.source=r.source}return r}finally{V.call(this,w,_,S)}function t(){var a=m.validate,X0=a.apply(this,arguments);return t.errors=a.errors,X0}function Q0(a,X0,P0,_0){var A0=!X0||X0&&X0.schema==a;if(X0.schema!=_.schema)return j.call(C,a,X0,P0,_0);var l0=a.$async===!0,p0=G({isTop:!0,schema:a,isRoot:A0,baseId:_0,root:X0,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:B.MissingRef,RULES:l,validate:G,util:X,resolve:J,resolveRef:$,usePattern:n,useDefault:z0,useCustomRule:D0,opts:T,formats:i,logger:C.logger,self:C});if(p0=M(b,N)+M(I,D)+M(R,L)+M(v,K)+p0,T.processCode)p0=T.processCode(p0,a);var y0;try{var U1=Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",p0);y0=U1(C,l,i,_,b,R,v,U,H,z),b[0]=y0}catch(e0){throw C.logger.error("Error compiling schema, function code:",p0),e0}if(y0.schema=a,y0.errors=null,y0.refs=k,y0.refVal=b,y0.root=A0?y0:X0,l0)y0.$async=!0;if(T.sourceCode===!0)y0.source={code:p0,patterns:I,defaults:R};return y0}function $(a,X0,P0){X0=J.url(a,X0);var _0=k[X0],A0,l0;if(_0!==void 0)return A0=b[_0],l0="refVal["+_0+"]",h(A0,l0);if(!P0&&_.refs){var p0=_.refs[X0];if(p0!==void 0)return A0=_.refVal[p0],l0=H0(X0,A0),h(A0,l0)}l0=H0(X0);var y0=J.call(C,Q0,_,X0);if(y0===void 0){var U1=g&&g[X0];if(U1)y0=J.inlineRef(U1,T.inlineRefs)?U1:j.call(C,U1,_,g,a)}if(y0===void 0)E0(X0);else return M0(X0,y0),h(y0,l0)}function H0(a,X0){var P0=b.length;return b[P0]=X0,k[a]=P0,"refVal"+P0}function E0(a){delete k[a]}function M0(a,X0){var P0=k[a];b[P0]=X0}function h(a,X0){return typeof a=="object"||typeof a=="boolean"?{code:X0,schema:a,inline:!0}:{code:X0,$async:a&&!!a.$async}}function n(a){var X0=E[a];if(X0===void 0)X0=E[a]=I.length,I[X0]=a;return"pattern"+X0}function z0(a){switch(typeof a){case"boolean":case"number":return""+a;case"string":return X.toQuotedString(a);case"object":if(a===null)return"null";var X0=q(a),P0=Z[X0];if(P0===void 0)P0=Z[X0]=R.length,R[P0]=a;return"default"+P0}}function D0(a,X0,P0,_0){if(C._opts.validateSchema!==!1){var A0=a.definition.dependencies;if(A0&&!A0.every(function(I1){return Object.prototype.hasOwnProperty.call(P0,I1)}))throw Error("parent schema must have all required keywords: "+A0.join(","));var l0=a.definition.validateSchema;if(l0){var p0=l0(X0);if(!p0){var y0="keyword schema is invalid: "+C.errorsText(l0.errors);if(C._opts.validateSchema=="log")C.logger.error(y0);else throw Error(y0)}}}var U1=a.definition.compile,e0=a.definition.inline,j1=a.definition.macro,n0;if(U1)n0=U1.call(C,X0,P0,_0);else if(j1){if(n0=j1.call(C,X0,P0,_0),T.validateSchema!==!1)C.validateSchema(n0,!0)}else if(e0)n0=e0.call(C,_0,a.keyword,X0,P0);else if(n0=a.definition.validate,!n0)return;if(n0===void 0)throw Error('custom keyword "'+a.keyword+'"failed to compile');var H1=v.length;return v[H1]=n0,{code:"customRule"+H1,validate:n0}}}function A(w,_,g){var S=F.call(this,w,_,g);if(S>=0)return{index:S,compiling:!0};return S=this._compilations.length,this._compilations[S]={schema:w,root:_,baseId:g},{index:S,compiling:!1}}function V(w,_,g){var S=F.call(this,w,_,g);if(S>=0)this._compilations.splice(S,1)}function F(w,_,g){for(var S=0;S<this._compilations.length;S++){var C=this._compilations[S];if(C.schema==w&&C.root==_&&C.baseId==g)return S}return-1}function D(w,_){return"var pattern"+w+" = new RegExp("+X.toQuotedString(_[w])+");"}function L(w){return"var default"+w+" = defaults["+w+"];"}function N(w,_){return _[w]===void 0?"":"var refVal"+w+" = refVal["+w+"];"}function K(w){return"var customRule"+w+" = customRules["+w+"];"}function M(w,_){if(!w.length)return"";var g="";for(var S=0;S<w.length;S++)g+=_(S,w);return g}}),WH=V0((Q,Y)=>{var J=Y.exports=function(){this._cache={}};J.prototype.put=function(B,q){this._cache[B]=q},J.prototype.get=function(B){return this._cache[B]},J.prototype.del=function(B){delete this._cache[B]},J.prototype.clear=function(){this._cache={}}}),GH=V0((Q,Y)=>{var J=O8(),X=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,B=[0,31,28,31,30,31,30,31,31,30,31,30,31],q=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,G=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,H=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,U=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,z=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,j=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,A=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,V=/^(?:\/(?:[^~/]|~0|~1)*)*$/,F=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,D=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;Y.exports=L;function L(b){return b=b=="full"?"full":"fast",J.copy(L[b])}L.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":z,url:j,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:G,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:T,uuid:A,"json-pointer":V,"json-pointer-uri-fragment":F,"relative-json-pointer":D},L.full={date:K,time:M,"date-time":_,uri:S,"uri-reference":U,"uri-template":z,url:j,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:G,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:T,uuid:A,"json-pointer":V,"json-pointer-uri-fragment":F,"relative-json-pointer":D};function N(b){return b%4===0&&(b%100!==0||b%400===0)}function K(b){var k=b.match(X);if(!k)return!1;var I=+k[1],E=+k[2],R=+k[3];return E>=1&&E<=12&&R>=1&&R<=(E==2&&N(I)?29:B[E])}function M(b,k){var I=b.match(q);if(!I)return!1;var E=I[1],R=I[2],Z=I[3],v=I[5];return(E<=23&&R<=59&&Z<=59||E==23&&R==59&&Z==60)&&(!k||v)}var w=/t|\s/i;function _(b){var k=b.split(w);return k.length==2&&K(k[0])&&M(k[1],!0)}var g=/\/|:/;function S(b){return g.test(b)&&H.test(b)}var C=/[^\\]\\Z/;function T(b){if(C.test(b))return!1;try{return new RegExp(b),!0}catch(k){return!1}}}),BH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.errSchemaPath+"/"+B,A=!X.opts.allErrors,V="data"+(U||""),F="valid"+H,D,L;if(z=="#"||z=="#/")if(X.isRoot)D=X.async,L="validate";else D=X.root.schema.$async===!0,L="root.refVal[0]";else{var N=X.resolveRef(X.baseId,z,X.isRoot);if(N===void 0){var K=X.MissingRefError.message(X.baseId,z);if(X.opts.missingRefs=="fail"){X.logger.error(K);var M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(j)+" , params: { ref: '"+X.util.escapeQuotes(z)+"' } ",X.opts.messages!==!1)G+=" , message: 'can\\'t resolve reference "+X.util.escapeQuotes(z)+"' ";if(X.opts.verbose)G+=" , schema: "+X.util.toQuotedString(z)+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+V+" ";G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&A)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(A)G+=" if (false) { "}else if(X.opts.missingRefs=="ignore"){if(X.logger.warn(K),A)G+=" if (true) { "}else throw new X.MissingRefError(X.baseId,z,K)}else if(N.inline){var _=X.util.copy(X);_.level++;var g="valid"+_.level;_.schema=N.schema,_.schemaPath="",_.errSchemaPath=z;var S=X.validate(_).replace(/validate\.schema/g,N.code);if(G+=" "+S+" ",A)G+=" if ("+g+") { "}else D=N.$async===!0||X.async&&N.$async!==!1,L=N.code}if(L){var M=M||[];if(M.push(G),G="",X.opts.passContext)G+=" "+L+".call(this, ";else G+=" "+L+"( ";if(G+=" "+V+", (dataPath || '')",X.errorPath!='""')G+=" + "+X.errorPath;var C=U?"data"+(U-1||""):"parentData",T=U?X.dataPathArr[U]:"parentDataProperty";G+=" , "+C+" , "+T+", rootData) ";var b=G;if(G=M.pop(),D){if(!X.async)throw Error("async schema referenced by sync schema");if(A)G+=" var "+F+"; ";if(G+=" try { await "+b+"; ",A)G+=" "+F+" = true; ";if(G+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",A)G+=" "+F+" = false; ";if(G+=" } ",A)G+=" if ("+F+") { "}else if(G+=" if (!"+b+") { if (vErrors === null) vErrors = "+L+".errors; else vErrors = vErrors.concat("+L+".errors); errors = vErrors.length; } ",A)G+=" else { "}return G}}),qH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.schema[B],U=X.schemaPath+X.util.getProperty(B),z=X.errSchemaPath+"/"+B,j=!X.opts.allErrors,A=X.util.copy(X),V="";A.level++;var F="valid"+A.level,D=A.baseId,L=!0,N=H;if(N){var K,M=-1,w=N.length-1;while(M<w)if(K=N[M+=1],X.opts.strictKeywords?typeof K=="object"&&Object.keys(K).length>0||K===!1:X.util.schemaHasRules(K,X.RULES.all)){if(L=!1,A.schema=K,A.schemaPath=U+"["+M+"]",A.errSchemaPath=z+"/"+M,G+=" "+X.validate(A)+" ",A.baseId=D,j)G+=" if ("+F+") { ",V+="}"}}if(j)if(L)G+=" if (true) { ";else G+=" "+V.slice(0,-1)+" ";return G}}),HH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L="errs__"+H,N=X.util.copy(X),K="";N.level++;var M="valid"+N.level,w=z.every(function(k){return X.opts.strictKeywords?typeof k=="object"&&Object.keys(k).length>0||k===!1:X.util.schemaHasRules(k,X.RULES.all)});if(w){var _=N.baseId;G+=" var "+L+" = errors; var "+D+" = false; ";var g=X.compositeRule;X.compositeRule=N.compositeRule=!0;var S=z;if(S){var C,T=-1,b=S.length-1;while(T<b)C=S[T+=1],N.schema=C,N.schemaPath=j+"["+T+"]",N.errSchemaPath=A+"/"+T,G+=" "+X.validate(N)+" ",N.baseId=_,G+=" "+D+" = "+D+" || "+M+"; if (!"+D+") { ",K+="}"}if(X.compositeRule=N.compositeRule=g,G+=" "+K+" if (!"+D+") { var err = ",X.createErrors!==!1){if(G+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: {} ",X.opts.messages!==!1)G+=" , message: 'should match some schema in anyOf' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";if(G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(vErrors); ";else G+=" validate.errors = vErrors; return false; ";if(G+=" } else { errors = "+L+"; if (vErrors !== null) { if ("+L+") vErrors.length = "+L+"; else vErrors = null; } ",X.opts.allErrors)G+=" } "}else if(V)G+=" if (true) { ";return G}}),zH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.schema[B],U=X.errSchemaPath+"/"+B,z=!X.opts.allErrors,j=X.util.toQuotedString(H);if(X.opts.$comment===!0)G+=" console.log("+j+");";else if(typeof X.opts.$comment=="function")G+=" self._opts.$comment("+j+", "+X.util.toQuotedString(U)+", validate.root.schema);";return G}}),UH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L=X.opts.$data&&z&&z.$data,N;if(L)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",N="schema"+H;else N=z;if(!L)G+=" var schema"+H+" = validate.schema"+j+";";G+="var "+D+" = equal("+F+", schema"+H+"); if (!"+D+") { ";var K=K||[];if(K.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'const' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { allowedValue: schema"+H+" } ",X.opts.messages!==!1)G+=" , message: 'should be equal to constant' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var M=G;if(G=K.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+M+"]); ";else G+=" validate.errors = ["+M+"]; return false; ";else G+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" }",V)G+=" else { ";return G}}),LH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L="errs__"+H,N=X.util.copy(X),K="";N.level++;var M="valid"+N.level,w="i"+H,_=N.dataLevel=X.dataLevel+1,g="data"+_,S=X.baseId,C=X.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:X.util.schemaHasRules(z,X.RULES.all);if(G+="var "+L+" = errors;var "+D+";",C){var T=X.compositeRule;X.compositeRule=N.compositeRule=!0,N.schema=z,N.schemaPath=j,N.errSchemaPath=A,G+=" var "+M+" = false; for (var "+w+" = 0; "+w+" < "+F+".length; "+w+"++) { ",N.errorPath=X.util.getPathExpr(X.errorPath,w,X.opts.jsonPointers,!0);var b=F+"["+w+"]";N.dataPathArr[_]=w;var k=X.validate(N);if(N.baseId=S,X.util.varOccurences(k,g)<2)G+=" "+X.util.varReplace(k,g,b)+" ";else G+=" var "+g+" = "+b+"; "+k+" ";G+=" if ("+M+") break; } ",X.compositeRule=N.compositeRule=T,G+=" "+K+" if (!"+M+") {"}else G+=" if ("+F+".length == 0) {";var I=I||[];if(I.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: {} ",X.opts.messages!==!1)G+=" , message: 'should contain a valid item' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var E=G;if(G=I.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+E+"]); ";else G+=" validate.errors = ["+E+"]; return false; ";else G+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" } else { ",C)G+=" errors = "+L+"; if (vErrors !== null) { if ("+L+") vErrors.length = "+L+"; else vErrors = null; } ";if(X.opts.allErrors)G+=" } ";return G}}),FH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="errs__"+H,L=X.util.copy(X),N="";L.level++;var K="valid"+L.level,M={},w={},_=X.opts.ownProperties;for(T in z){if(T=="__proto__")continue;var g=z[T],S=Array.isArray(g)?w:M;S[T]=g}G+="var "+D+" = errors;";var C=X.errorPath;G+="var missing"+H+";";for(var T in w)if(S=w[T],S.length){if(G+=" if ( "+F+X.util.getProperty(T)+" !== undefined ",_)G+=" && Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(T)+"') ";if(V){G+=" && ( ";var b=S;if(b){var k,I=-1,E=b.length-1;while(I<E){if(k=b[I+=1],I)G+=" || ";var R=X.util.getProperty(k),Z=F+R;if(G+=" ( ( "+Z+" === undefined ",_)G+=" || ! Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(k)+"') ";G+=") && (missing"+H+" = "+X.util.toQuotedString(X.opts.jsonPointers?k:R)+") ) "}}G+=")) { ";var v="missing"+H,y="' + "+v+" + '";if(X.opts._errorDataPathProperty)X.errorPath=X.opts.jsonPointers?X.util.getPathExpr(C,v,!0):C+" + "+v;var m=m||[];if(m.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { property: '"+X.util.escapeQuotes(T)+"', missingProperty: '"+y+"', depsCount: "+S.length+", deps: '"+X.util.escapeQuotes(S.length==1?S[0]:S.join(", "))+"' } ",X.opts.messages!==!1){if(G+=" , message: 'should have ",S.length==1)G+="property "+X.util.escapeQuotes(S[0]);else G+="properties "+X.util.escapeQuotes(S.join(", "));G+=" when property "+X.util.escapeQuotes(T)+" is present' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var i=G;if(G=m.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+i+"]); ";else G+=" validate.errors = ["+i+"]; return false; ";else G+=" var err = "+i+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{G+=" ) { ";var l=S;if(l){var k,r=-1,d=l.length-1;while(r<d){k=l[r+=1];var R=X.util.getProperty(k),y=X.util.escapeQuotes(k),Z=F+R;if(X.opts._errorDataPathProperty)X.errorPath=X.util.getPath(C,k,X.opts.jsonPointers);if(G+=" if ( "+Z+" === undefined ",_)G+=" || ! Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(k)+"') ";if(G+=") { var err = ",X.createErrors!==!1){if(G+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { property: '"+X.util.escapeQuotes(T)+"', missingProperty: '"+y+"', depsCount: "+S.length+", deps: '"+X.util.escapeQuotes(S.length==1?S[0]:S.join(", "))+"' } ",X.opts.messages!==!1){if(G+=" , message: 'should have ",S.length==1)G+="property "+X.util.escapeQuotes(S[0]);else G+="properties "+X.util.escapeQuotes(S.join(", "));G+=" when property "+X.util.escapeQuotes(T)+" is present' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}}if(G+=" } ",V)N+="}",G+=" else { "}X.errorPath=C;var t=L.baseId;for(var T in M){var g=M[T];if(X.opts.strictKeywords?typeof g=="object"&&Object.keys(g).length>0||g===!1:X.util.schemaHasRules(g,X.RULES.all)){if(G+=" "+K+" = true; if ( "+F+X.util.getProperty(T)+" !== undefined ",_)G+=" && Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(T)+"') ";if(G+=") { ",L.schema=g,L.schemaPath=j+X.util.getProperty(T),L.errSchemaPath=A+"/"+X.util.escapeFragment(T),G+=" "+X.validate(L)+" ",L.baseId=t,G+=" } ",V)G+=" if ("+K+") { ",N+="}"}}if(V)G+=" "+N+" if ("+D+" == errors) {";return G}}),NH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L=X.opts.$data&&z&&z.$data,N;if(L)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",N="schema"+H;else N=z;var K="i"+H,M="schema"+H;if(!L)G+=" var "+M+" = validate.schema"+j+";";if(G+="var "+D+";",L)G+=" if (schema"+H+" === undefined) "+D+" = true; else if (!Array.isArray(schema"+H+")) "+D+" = false; else {";if(G+=""+D+" = false;for (var "+K+"=0; "+K+"<"+M+".length; "+K+"++) if (equal("+F+", "+M+"["+K+"])) { "+D+" = true; break; }",L)G+=" } ";G+=" if (!"+D+") { ";var w=w||[];if(w.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { allowedValues: schema"+H+" } ",X.opts.messages!==!1)G+=" , message: 'should be equal to one of the allowed values' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var _=G;if(G=w.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+_+"]); ";else G+=" validate.errors = ["+_+"]; return false; ";else G+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" }",V)G+=" else { ";return G}}),jH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||"");if(X.opts.format===!1){if(V)G+=" if (true) { ";return G}var D=X.opts.$data&&z&&z.$data,L;if(D)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",L="schema"+H;else L=z;var N=X.opts.unknownFormats,K=Array.isArray(N);if(D){var M="format"+H,w="isObject"+H,_="formatType"+H;if(G+=" var "+M+" = formats["+L+"]; var "+w+" = typeof "+M+" == 'object' && !("+M+" instanceof RegExp) && "+M+".validate; var "+_+" = "+w+" && "+M+".type || 'string'; if ("+w+") { ",X.async)G+=" var async"+H+" = "+M+".async; ";if(G+=" "+M+" = "+M+".validate; } if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'string') || ";if(G+=" (",N!="ignore"){if(G+=" ("+L+" && !"+M+" ",K)G+=" && self._opts.unknownFormats.indexOf("+L+") == -1 ";G+=") || "}if(G+=" ("+M+" && "+_+" == '"+q+"' && !(typeof "+M+" == 'function' ? ",X.async)G+=" (async"+H+" ? await "+M+"("+F+") : "+M+"("+F+")) ";else G+=" "+M+"("+F+") ";G+=" : "+M+".test("+F+"))))) {"}else{var M=X.formats[z];if(!M)if(N=="ignore"){if(X.logger.warn('unknown format "'+z+'" ignored in schema at path "'+X.errSchemaPath+'"'),V)G+=" if (true) { ";return G}else if(K&&N.indexOf(z)>=0){if(V)G+=" if (true) { ";return G}else throw Error('unknown format "'+z+'" is used in schema at path "'+X.errSchemaPath+'"');var w=typeof M=="object"&&!(M instanceof RegExp)&&M.validate,_=w&&M.type||"string";if(w){var g=M.async===!0;M=M.validate}if(_!=q){if(V)G+=" if (true) { ";return G}if(g){if(!X.async)throw Error("async format in sync schema");var S="formats"+X.util.getProperty(z)+".validate";G+=" if (!(await "+S+"("+F+"))) { "}else{G+=" if (! ";var S="formats"+X.util.getProperty(z);if(w)S+=".validate";if(typeof M=="function")G+=" "+S+"("+F+") ";else G+=" "+S+".test("+F+") ";G+=") { "}}var C=C||[];if(C.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'format' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { format: ",D)G+=""+L;else G+=""+X.util.toQuotedString(z);if(G+=" } ",X.opts.messages!==!1){if(G+=` , message: 'should match format "`,D)G+="' + "+L+" + '";else G+=""+X.util.escapeQuotes(z);G+=`"' `}if(X.opts.verbose){if(G+=" , schema: ",D)G+="validate.schema"+j;else G+=""+X.util.toQuotedString(z);G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var T=G;if(G=C.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+T+"]); ";else G+=" validate.errors = ["+T+"]; return false; ";else G+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" } ",V)G+=" else { ";return G}}),KH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L="errs__"+H,N=X.util.copy(X);N.level++;var K="valid"+N.level,M=X.schema.then,w=X.schema.else,_=M!==void 0&&(X.opts.strictKeywords?typeof M=="object"&&Object.keys(M).length>0||M===!1:X.util.schemaHasRules(M,X.RULES.all)),g=w!==void 0&&(X.opts.strictKeywords?typeof w=="object"&&Object.keys(w).length>0||w===!1:X.util.schemaHasRules(w,X.RULES.all)),S=N.baseId;if(_||g){var C;N.createErrors=!1,N.schema=z,N.schemaPath=j,N.errSchemaPath=A,G+=" var "+L+" = errors; var "+D+" = true; ";var T=X.compositeRule;if(X.compositeRule=N.compositeRule=!0,G+=" "+X.validate(N)+" ",N.baseId=S,N.createErrors=!0,G+=" errors = "+L+"; if (vErrors !== null) { if ("+L+") vErrors.length = "+L+"; else vErrors = null; } ",X.compositeRule=N.compositeRule=T,_){if(G+=" if ("+K+") { ",N.schema=X.schema.then,N.schemaPath=X.schemaPath+".then",N.errSchemaPath=X.errSchemaPath+"/then",G+=" "+X.validate(N)+" ",N.baseId=S,G+=" "+D+" = "+K+"; ",_&&g)C="ifClause"+H,G+=" var "+C+" = 'then'; ";else C="'then'";if(G+=" } ",g)G+=" else { "}else G+=" if (!"+K+") { ";if(g){if(N.schema=X.schema.else,N.schemaPath=X.schemaPath+".else",N.errSchemaPath=X.errSchemaPath+"/else",G+=" "+X.validate(N)+" ",N.baseId=S,G+=" "+D+" = "+K+"; ",_&&g)C="ifClause"+H,G+=" var "+C+" = 'else'; ";else C="'else'";G+=" } "}if(G+=" if (!"+D+") { var err = ",X.createErrors!==!1){if(G+=" { keyword: 'if' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { failingKeyword: "+C+" } ",X.opts.messages!==!1)G+=` , message: 'should match "' + `+C+` + '" schema' `;if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";if(G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(vErrors); ";else G+=" validate.errors = vErrors; return false; ";if(G+=" } ",V)G+=" else { "}else if(V)G+=" if (true) { ";return G}}),MH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L="errs__"+H,N=X.util.copy(X),K="";N.level++;var M="valid"+N.level,w="i"+H,_=N.dataLevel=X.dataLevel+1,g="data"+_,S=X.baseId;if(G+="var "+L+" = errors;var "+D+";",Array.isArray(z)){var C=X.schema.additionalItems;if(C===!1){G+=" "+D+" = "+F+".length <= "+z.length+"; ";var T=A;A=X.errSchemaPath+"/additionalItems",G+=" if (!"+D+") { ";var b=b||[];if(b.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { limit: "+z.length+" } ",X.opts.messages!==!1)G+=" , message: 'should NOT have more than "+z.length+" items' ";if(X.opts.verbose)G+=" , schema: false , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var k=G;if(G=b.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+k+"]); ";else G+=" validate.errors = ["+k+"]; return false; ";else G+=" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" } ",A=T,V)K+="}",G+=" else { "}var I=z;if(I){var E,R=-1,Z=I.length-1;while(R<Z)if(E=I[R+=1],X.opts.strictKeywords?typeof E=="object"&&Object.keys(E).length>0||E===!1:X.util.schemaHasRules(E,X.RULES.all)){G+=" "+M+" = true; if ("+F+".length > "+R+") { ";var v=F+"["+R+"]";N.schema=E,N.schemaPath=j+"["+R+"]",N.errSchemaPath=A+"/"+R,N.errorPath=X.util.getPathExpr(X.errorPath,R,X.opts.jsonPointers,!0),N.dataPathArr[_]=R;var y=X.validate(N);if(N.baseId=S,X.util.varOccurences(y,g)<2)G+=" "+X.util.varReplace(y,g,v)+" ";else G+=" var "+g+" = "+v+"; "+y+" ";if(G+=" } ",V)G+=" if ("+M+") { ",K+="}"}}if(typeof C=="object"&&(X.opts.strictKeywords?typeof C=="object"&&Object.keys(C).length>0||C===!1:X.util.schemaHasRules(C,X.RULES.all))){N.schema=C,N.schemaPath=X.schemaPath+".additionalItems",N.errSchemaPath=X.errSchemaPath+"/additionalItems",G+=" "+M+" = true; if ("+F+".length > "+z.length+") { for (var "+w+" = "+z.length+"; "+w+" < "+F+".length; "+w+"++) { ",N.errorPath=X.util.getPathExpr(X.errorPath,w,X.opts.jsonPointers,!0);var v=F+"["+w+"]";N.dataPathArr[_]=w;var y=X.validate(N);if(N.baseId=S,X.util.varOccurences(y,g)<2)G+=" "+X.util.varReplace(y,g,v)+" ";else G+=" var "+g+" = "+v+"; "+y+" ";if(V)G+=" if (!"+M+") break; ";if(G+=" } } ",V)G+=" if ("+M+") { ",K+="}"}}else if(X.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:X.util.schemaHasRules(z,X.RULES.all)){N.schema=z,N.schemaPath=j,N.errSchemaPath=A,G+=" for (var "+w+" = 0; "+w+" < "+F+".length; "+w+"++) { ",N.errorPath=X.util.getPathExpr(X.errorPath,w,X.opts.jsonPointers,!0);var v=F+"["+w+"]";N.dataPathArr[_]=w;var y=X.validate(N);if(N.baseId=S,X.util.varOccurences(y,g)<2)G+=" "+X.util.varReplace(y,g,v)+" ";else G+=" var "+g+" = "+v+"; "+y+" ";if(V)G+=" if (!"+M+") break; ";G+=" }"}if(V)G+=" "+K+" if ("+L+" == errors) {";return G}}),Q5=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,S,F="data"+(U||""),D=X.opts.$data&&z&&z.$data,L;if(D)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",L="schema"+H;else L=z;var N=B=="maximum",K=N?"exclusiveMaximum":"exclusiveMinimum",M=X.schema[K],w=X.opts.$data&&M&&M.$data,_=N?"<":">",g=N?">":"<",S=void 0;if(!(D||typeof z=="number"||z===void 0))throw Error(B+" must be number");if(!(w||M===void 0||typeof M=="number"||typeof M=="boolean"))throw Error(K+" must be number or boolean");if(w){var C=X.util.getData(M.$data,U,X.dataPathArr),T="exclusive"+H,b="exclType"+H,k="exclIsNumber"+H,I="op"+H,E="' + "+I+" + '";G+=" var schemaExcl"+H+" = "+C+"; ",C="schemaExcl"+H,G+=" var "+T+"; var "+b+" = typeof "+C+"; if ("+b+" != 'boolean' && "+b+" != 'undefined' && "+b+" != 'number') { ";var S=K,R=R||[];if(R.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(S||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: {} ",X.opts.messages!==!1)G+=" , message: '"+K+" should be boolean' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var Z=G;if(G=R.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+Z+"]); ";else G+=" validate.errors = ["+Z+"]; return false; ";else G+=" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" } else if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'number') || ";if(G+=" "+b+" == 'number' ? ( ("+T+" = "+L+" === undefined || "+C+" "+_+"= "+L+") ? "+F+" "+g+"= "+C+" : "+F+" "+g+" "+L+" ) : ( ("+T+" = "+C+" === true) ? "+F+" "+g+"= "+L+" : "+F+" "+g+" "+L+" ) || "+F+" !== "+F+") { var op"+H+" = "+T+" ? '"+_+"' : '"+_+"='; ",z===void 0)S=K,A=X.errSchemaPath+"/"+K,L=C,D=w}else{var k=typeof M=="number",E=_;if(k&&D){var I="'"+E+"'";if(G+=" if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'number') || ";G+=" ( "+L+" === undefined || "+M+" "+_+"= "+L+" ? "+F+" "+g+"= "+M+" : "+F+" "+g+" "+L+" ) || "+F+" !== "+F+") { "}else{if(k&&z===void 0)T=!0,S=K,A=X.errSchemaPath+"/"+K,L=M,g+="=";else{if(k)L=Math[N?"min":"max"](M,z);if(M===(k?L:!0))T=!0,S=K,A=X.errSchemaPath+"/"+K,g+="=";else T=!1,E+="="}var I="'"+E+"'";if(G+=" if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'number') || ";G+=" "+F+" "+g+" "+L+" || "+F+" !== "+F+") { "}}S=S||B;var R=R||[];if(R.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(S||"_limit")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { comparison: "+I+", limit: "+L+", exclusive: "+T+" } ",X.opts.messages!==!1)if(G+=" , message: 'should be "+E+" ",D)G+="' + "+L;else G+=""+L+"'";if(X.opts.verbose){if(G+=" , schema: ",D)G+="validate.schema"+j;else G+=""+z;G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var Z=G;if(G=R.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+Z+"]); ";else G+=" validate.errors = ["+Z+"]; return false; ";else G+=" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" } ",V)G+=" else { ";return G}}),X5=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,K,F="data"+(U||""),D=X.opts.$data&&z&&z.$data,L;if(D)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",L="schema"+H;else L=z;if(!(D||typeof z=="number"))throw Error(B+" must be number");var N=B=="maxItems"?">":"<";if(G+="if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'number') || ";G+=" "+F+".length "+N+" "+L+") { ";var K=B,M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(K||"_limitItems")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { limit: "+L+" } ",X.opts.messages!==!1){if(G+=" , message: 'should NOT have ",B=="maxItems")G+="more";else G+="fewer";if(G+=" than ",D)G+="' + "+L+" + '";else G+=""+z;G+=" items' "}if(X.opts.verbose){if(G+=" , schema: ",D)G+="validate.schema"+j;else G+=""+z;G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+="} ",V)G+=" else { ";return G}}),Y5=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,K,F="data"+(U||""),D=X.opts.$data&&z&&z.$data,L;if(D)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",L="schema"+H;else L=z;if(!(D||typeof z=="number"))throw Error(B+" must be number");var N=B=="maxLength"?">":"<";if(G+="if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'number') || ";if(X.opts.unicode===!1)G+=" "+F+".length ";else G+=" ucs2length("+F+") ";G+=" "+N+" "+L+") { ";var K=B,M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(K||"_limitLength")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { limit: "+L+" } ",X.opts.messages!==!1){if(G+=" , message: 'should NOT be ",B=="maxLength")G+="longer";else G+="shorter";if(G+=" than ",D)G+="' + "+L+" + '";else G+=""+z;G+=" characters' "}if(X.opts.verbose){if(G+=" , schema: ",D)G+="validate.schema"+j;else G+=""+z;G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+="} ",V)G+=" else { ";return G}}),J5=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,K,F="data"+(U||""),D=X.opts.$data&&z&&z.$data,L;if(D)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",L="schema"+H;else L=z;if(!(D||typeof z=="number"))throw Error(B+" must be number");var N=B=="maxProperties"?">":"<";if(G+="if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'number') || ";G+=" Object.keys("+F+").length "+N+" "+L+") { ";var K=B,M=M||[];if(M.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(K||"_limitProperties")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { limit: "+L+" } ",X.opts.messages!==!1){if(G+=" , message: 'should NOT have ",B=="maxProperties")G+="more";else G+="fewer";if(G+=" than ",D)G+="' + "+L+" + '";else G+=""+z;G+=" properties' "}if(X.opts.verbose){if(G+=" , schema: ",D)G+="validate.schema"+j;else G+=""+z;G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var w=G;if(G=M.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+w+"]); ";else G+=" validate.errors = ["+w+"]; return false; ";else G+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+="} ",V)G+=" else { ";return G}}),AH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D=X.opts.$data&&z&&z.$data,L;if(D)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",L="schema"+H;else L=z;if(!(D||typeof z=="number"))throw Error(B+" must be number");if(G+="var division"+H+";if (",D)G+=" "+L+" !== undefined && ( typeof "+L+" != 'number' || ";if(G+=" (division"+H+" = "+F+" / "+L+", ",X.opts.multipleOfPrecision)G+=" Math.abs(Math.round(division"+H+") - division"+H+") > 1e-"+X.opts.multipleOfPrecision+" ";else G+=" division"+H+" !== parseInt(division"+H+") ";if(G+=" ) ",D)G+=" ) ";G+=" ) { ";var N=N||[];if(N.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { multipleOf: "+L+" } ",X.opts.messages!==!1)if(G+=" , message: 'should be multiple of ",D)G+="' + "+L;else G+=""+L+"'";if(X.opts.verbose){if(G+=" , schema: ",D)G+="validate.schema"+j;else G+=""+z;G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var K=G;if(G=N.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+K+"]); ";else G+=" validate.errors = ["+K+"]; return false; ";else G+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+="} ",V)G+=" else { ";return G}}),VH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="errs__"+H,L=X.util.copy(X);L.level++;var N="valid"+L.level;if(X.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:X.util.schemaHasRules(z,X.RULES.all)){L.schema=z,L.schemaPath=j,L.errSchemaPath=A,G+=" var "+D+" = errors; ";var K=X.compositeRule;X.compositeRule=L.compositeRule=!0,L.createErrors=!1;var M;if(L.opts.allErrors)M=L.opts.allErrors,L.opts.allErrors=!1;if(G+=" "+X.validate(L)+" ",L.createErrors=!0,M)L.opts.allErrors=M;X.compositeRule=L.compositeRule=K,G+=" if ("+N+") { ";var w=w||[];if(w.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'not' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: {} ",X.opts.messages!==!1)G+=" , message: 'should NOT be valid' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var _=G;if(G=w.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+_+"]); ";else G+=" validate.errors = ["+_+"]; return false; ";else G+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" } else { errors = "+D+"; if (vErrors !== null) { if ("+D+") vErrors.length = "+D+"; else vErrors = null; } ",X.opts.allErrors)G+=" } "}else{if(G+=" var err = ",X.createErrors!==!1){if(G+=" { keyword: 'not' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: {} ",X.opts.messages!==!1)G+=" , message: 'should NOT be valid' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";if(G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",V)G+=" if (false) { "}return G}}),DH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L="errs__"+H,N=X.util.copy(X),K="";N.level++;var M="valid"+N.level,w=N.baseId,_="prevValid"+H,g="passingSchemas"+H;G+="var "+L+" = errors , "+_+" = false , "+D+" = false , "+g+" = null; ";var S=X.compositeRule;X.compositeRule=N.compositeRule=!0;var C=z;if(C){var T,b=-1,k=C.length-1;while(b<k){if(T=C[b+=1],X.opts.strictKeywords?typeof T=="object"&&Object.keys(T).length>0||T===!1:X.util.schemaHasRules(T,X.RULES.all))N.schema=T,N.schemaPath=j+"["+b+"]",N.errSchemaPath=A+"/"+b,G+=" "+X.validate(N)+" ",N.baseId=w;else G+=" var "+M+" = true; ";if(b)G+=" if ("+M+" && "+_+") { "+D+" = false; "+g+" = ["+g+", "+b+"]; } else { ",K+="}";G+=" if ("+M+") { "+D+" = "+_+" = true; "+g+" = "+b+"; }"}}if(X.compositeRule=N.compositeRule=S,G+=""+K+"if (!"+D+") { var err = ",X.createErrors!==!1){if(G+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { passingSchemas: "+g+" } ",X.opts.messages!==!1)G+=" , message: 'should match exactly one schema in oneOf' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";if(G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(vErrors); ";else G+=" validate.errors = vErrors; return false; ";if(G+="} else { errors = "+L+"; if (vErrors !== null) { if ("+L+") vErrors.length = "+L+"; else vErrors = null; }",X.opts.allErrors)G+=" } ";return G}}),wH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D=X.opts.$data&&z&&z.$data,L;if(D)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",L="schema"+H;else L=z;var N=D?"(new RegExp("+L+"))":X.usePattern(z);if(G+="if ( ",D)G+=" ("+L+" !== undefined && typeof "+L+" != 'string') || ";G+=" !"+N+".test("+F+") ) { ";var K=K||[];if(K.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { pattern: ",D)G+=""+L;else G+=""+X.util.toQuotedString(z);if(G+=" } ",X.opts.messages!==!1){if(G+=` , message: 'should match pattern "`,D)G+="' + "+L+" + '";else G+=""+X.util.escapeQuotes(z);G+=`"' `}if(X.opts.verbose){if(G+=" , schema: ",D)G+="validate.schema"+j;else G+=""+X.util.toQuotedString(z);G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var M=G;if(G=K.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+M+"]); ";else G+=" validate.errors = ["+M+"]; return false; ";else G+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+="} ",V)G+=" else { ";return G}}),OH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="errs__"+H,L=X.util.copy(X),N="";L.level++;var K="valid"+L.level,M="key"+H,w="idx"+H,_=L.dataLevel=X.dataLevel+1,g="data"+_,S="dataProperties"+H,C=Object.keys(z||{}).filter(r),T=X.schema.patternProperties||{},b=Object.keys(T).filter(r),k=X.schema.additionalProperties,I=C.length||b.length,E=k===!1,R=typeof k=="object"&&Object.keys(k).length,Z=X.opts.removeAdditional,v=E||R||Z,y=X.opts.ownProperties,m=X.baseId,i=X.schema.required;if(i&&!(X.opts.$data&&i.$data)&&i.length<X.opts.loopRequired)var l=X.util.toHash(i);function r(v1){return v1!=="__proto__"}if(G+="var "+D+" = errors;var "+K+" = true;",y)G+=" var "+S+" = undefined;";if(v){if(y)G+=" "+S+" = "+S+" || Object.keys("+F+"); for (var "+w+"=0; "+w+"<"+S+".length; "+w+"++) { var "+M+" = "+S+"["+w+"]; ";else G+=" for (var "+M+" in "+F+") { ";if(I){if(G+=" var isAdditional"+H+" = !(false ",C.length)if(C.length>8)G+=" || validate.schema"+j+".hasOwnProperty("+M+") ";else{var d=C;if(d){var t,Q0=-1,$=d.length-1;while(Q0<$)t=d[Q0+=1],G+=" || "+M+" == "+X.util.toQuotedString(t)+" "}}if(b.length){var H0=b;if(H0){var E0,M0=-1,h=H0.length-1;while(M0<h)E0=H0[M0+=1],G+=" || "+X.usePattern(E0)+".test("+M+") "}}G+=" ); if (isAdditional"+H+") { "}if(Z=="all")G+=" delete "+F+"["+M+"]; ";else{var n=X.errorPath,z0="' + "+M+" + '";if(X.opts._errorDataPathProperty)X.errorPath=X.util.getPathExpr(X.errorPath,M,X.opts.jsonPointers);if(E)if(Z)G+=" delete "+F+"["+M+"]; ";else{G+=" "+K+" = false; ";var D0=A;A=X.errSchemaPath+"/additionalProperties";var a=a||[];if(a.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { additionalProperty: '"+z0+"' } ",X.opts.messages!==!1){if(G+=" , message: '",X.opts._errorDataPathProperty)G+="is an invalid additional property";else G+="should NOT have additional properties";G+="' "}if(X.opts.verbose)G+=" , schema: false , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var X0=G;if(G=a.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+X0+"]); ";else G+=" validate.errors = ["+X0+"]; return false; ";else G+=" var err = "+X0+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(A=D0,V)G+=" break; "}else if(R)if(Z=="failing"){G+=" var "+D+" = errors; ";var P0=X.compositeRule;X.compositeRule=L.compositeRule=!0,L.schema=k,L.schemaPath=X.schemaPath+".additionalProperties",L.errSchemaPath=X.errSchemaPath+"/additionalProperties",L.errorPath=X.opts._errorDataPathProperty?X.errorPath:X.util.getPathExpr(X.errorPath,M,X.opts.jsonPointers);var _0=F+"["+M+"]";L.dataPathArr[_]=M;var A0=X.validate(L);if(L.baseId=m,X.util.varOccurences(A0,g)<2)G+=" "+X.util.varReplace(A0,g,_0)+" ";else G+=" var "+g+" = "+_0+"; "+A0+" ";G+=" if (!"+K+") { errors = "+D+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+F+"["+M+"]; } ",X.compositeRule=L.compositeRule=P0}else{L.schema=k,L.schemaPath=X.schemaPath+".additionalProperties",L.errSchemaPath=X.errSchemaPath+"/additionalProperties",L.errorPath=X.opts._errorDataPathProperty?X.errorPath:X.util.getPathExpr(X.errorPath,M,X.opts.jsonPointers);var _0=F+"["+M+"]";L.dataPathArr[_]=M;var A0=X.validate(L);if(L.baseId=m,X.util.varOccurences(A0,g)<2)G+=" "+X.util.varReplace(A0,g,_0)+" ";else G+=" var "+g+" = "+_0+"; "+A0+" ";if(V)G+=" if (!"+K+") break; "}X.errorPath=n}if(I)G+=" } ";if(G+=" } ",V)G+=" if ("+K+") { ",N+="}"}var l0=X.opts.useDefaults&&!X.compositeRule;if(C.length){var p0=C;if(p0){var t,y0=-1,U1=p0.length-1;while(y0<U1){t=p0[y0+=1];var e0=z[t];if(X.opts.strictKeywords?typeof e0=="object"&&Object.keys(e0).length>0||e0===!1:X.util.schemaHasRules(e0,X.RULES.all)){var j1=X.util.getProperty(t),_0=F+j1,n0=l0&&e0.default!==void 0;L.schema=e0,L.schemaPath=j+j1,L.errSchemaPath=A+"/"+X.util.escapeFragment(t),L.errorPath=X.util.getPath(X.errorPath,t,X.opts.jsonPointers),L.dataPathArr[_]=X.util.toQuotedString(t);var A0=X.validate(L);if(L.baseId=m,X.util.varOccurences(A0,g)<2){A0=X.util.varReplace(A0,g,_0);var H1=_0}else{var H1=g;G+=" var "+g+" = "+_0+"; "}if(n0)G+=" "+A0+" ";else{if(l&&l[t]){if(G+=" if ( "+H1+" === undefined ",y)G+=" || ! Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(t)+"') ";G+=") { "+K+" = false; ";var n=X.errorPath,D0=A,I1=X.util.escapeQuotes(t);if(X.opts._errorDataPathProperty)X.errorPath=X.util.getPath(n,t,X.opts.jsonPointers);A=X.errSchemaPath+"/required";var a=a||[];if(a.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'required' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { missingProperty: '"+I1+"' } ",X.opts.messages!==!1){if(G+=" , message: '",X.opts._errorDataPathProperty)G+="is a required property";else G+="should have required property \\'"+I1+"\\'";G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var X0=G;if(G=a.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+X0+"]); ";else G+=" validate.errors = ["+X0+"]; return false; ";else G+=" var err = "+X0+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";A=D0,X.errorPath=n,G+=" } else { "}else if(V){if(G+=" if ( "+H1+" === undefined ",y)G+=" || ! Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(t)+"') ";G+=") { "+K+" = true; } else { "}else{if(G+=" if ("+H1+" !== undefined ",y)G+=" && Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(t)+"') ";G+=" ) { "}G+=" "+A0+" } "}}if(V)G+=" if ("+K+") { ",N+="}"}}}if(b.length){var O1=b;if(O1){var E0,UQ=-1,sQ=O1.length-1;while(UQ<sQ){E0=O1[UQ+=1];var e0=T[E0];if(X.opts.strictKeywords?typeof e0=="object"&&Object.keys(e0).length>0||e0===!1:X.util.schemaHasRules(e0,X.RULES.all)){if(L.schema=e0,L.schemaPath=X.schemaPath+".patternProperties"+X.util.getProperty(E0),L.errSchemaPath=X.errSchemaPath+"/patternProperties/"+X.util.escapeFragment(E0),y)G+=" "+S+" = "+S+" || Object.keys("+F+"); for (var "+w+"=0; "+w+"<"+S+".length; "+w+"++) { var "+M+" = "+S+"["+w+"]; ";else G+=" for (var "+M+" in "+F+") { ";G+=" if ("+X.usePattern(E0)+".test("+M+")) { ",L.errorPath=X.util.getPathExpr(X.errorPath,M,X.opts.jsonPointers);var _0=F+"["+M+"]";L.dataPathArr[_]=M;var A0=X.validate(L);if(L.baseId=m,X.util.varOccurences(A0,g)<2)G+=" "+X.util.varReplace(A0,g,_0)+" ";else G+=" var "+g+" = "+_0+"; "+A0+" ";if(V)G+=" if (!"+K+") break; ";if(G+=" } ",V)G+=" else "+K+" = true; ";if(G+=" } ",V)G+=" if ("+K+") { ",N+="}"}}}}if(V)G+=" "+N+" if ("+D+" == errors) {";return G}}),RH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="errs__"+H,L=X.util.copy(X),N="";L.level++;var K="valid"+L.level;if(G+="var "+D+" = errors;",X.opts.strictKeywords?typeof z=="object"&&Object.keys(z).length>0||z===!1:X.util.schemaHasRules(z,X.RULES.all)){L.schema=z,L.schemaPath=j,L.errSchemaPath=A;var M="key"+H,w="idx"+H,_="i"+H,g="' + "+M+" + '",S=L.dataLevel=X.dataLevel+1,C="data"+S,T="dataProperties"+H,b=X.opts.ownProperties,k=X.baseId;if(b)G+=" var "+T+" = undefined; ";if(b)G+=" "+T+" = "+T+" || Object.keys("+F+"); for (var "+w+"=0; "+w+"<"+T+".length; "+w+"++) { var "+M+" = "+T+"["+w+"]; ";else G+=" for (var "+M+" in "+F+") { ";G+=" var startErrs"+H+" = errors; ";var I=M,E=X.compositeRule;X.compositeRule=L.compositeRule=!0;var R=X.validate(L);if(L.baseId=k,X.util.varOccurences(R,C)<2)G+=" "+X.util.varReplace(R,C,I)+" ";else G+=" var "+C+" = "+I+"; "+R+" ";if(X.compositeRule=L.compositeRule=E,G+=" if (!"+K+") { for (var "+_+"=startErrs"+H+"; "+_+"<errors; "+_+"++) { vErrors["+_+"].propertyName = "+M+"; } var err = ",X.createErrors!==!1){if(G+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { propertyName: '"+g+"' } ",X.opts.messages!==!1)G+=" , message: 'property name \\'"+g+"\\' is invalid' ";if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";if(G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(vErrors); ";else G+=" validate.errors = vErrors; return false; ";if(V)G+=" break; ";G+=" } }"}if(V)G+=" "+N+" if ("+D+" == errors) {";return G}}),ZH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L=X.opts.$data&&z&&z.$data,N;if(L)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",N="schema"+H;else N=z;var K="schema"+H;if(!L)if(z.length<X.opts.loopRequired&&X.schema.properties&&Object.keys(X.schema.properties).length){var M=[],w=z;if(w){var _,g=-1,S=w.length-1;while(g<S){_=w[g+=1];var C=X.schema.properties[_];if(!(C&&(X.opts.strictKeywords?typeof C=="object"&&Object.keys(C).length>0||C===!1:X.util.schemaHasRules(C,X.RULES.all))))M[M.length]=_}}}else var M=z;if(L||M.length){var T=X.errorPath,b=L||M.length>=X.opts.loopRequired,k=X.opts.ownProperties;if(V)if(G+=" var missing"+H+"; ",b){if(!L)G+=" var "+K+" = validate.schema"+j+"; ";var I="i"+H,E="schema"+H+"["+I+"]",R="' + "+E+" + '";if(X.opts._errorDataPathProperty)X.errorPath=X.util.getPathExpr(T,E,X.opts.jsonPointers);if(G+=" var "+D+" = true; ",L)G+=" if (schema"+H+" === undefined) "+D+" = true; else if (!Array.isArray(schema"+H+")) "+D+" = false; else {";if(G+=" for (var "+I+" = 0; "+I+" < "+K+".length; "+I+"++) { "+D+" = "+F+"["+K+"["+I+"]] !== undefined ",k)G+=" && Object.prototype.hasOwnProperty.call("+F+", "+K+"["+I+"]) ";if(G+="; if (!"+D+") break; } ",L)G+=" } ";G+=" if (!"+D+") { ";var Z=Z||[];if(Z.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'required' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { missingProperty: '"+R+"' } ",X.opts.messages!==!1){if(G+=" , message: '",X.opts._errorDataPathProperty)G+="is a required property";else G+="should have required property \\'"+R+"\\'";G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var v=G;if(G=Z.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+v+"]); ";else G+=" validate.errors = ["+v+"]; return false; ";else G+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";G+=" } else { "}else{G+=" if ( ";var y=M;if(y){var m,I=-1,i=y.length-1;while(I<i){if(m=y[I+=1],I)G+=" || ";var l=X.util.getProperty(m),r=F+l;if(G+=" ( ( "+r+" === undefined ",k)G+=" || ! Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(m)+"') ";G+=") && (missing"+H+" = "+X.util.toQuotedString(X.opts.jsonPointers?m:l)+") ) "}}G+=") { ";var E="missing"+H,R="' + "+E+" + '";if(X.opts._errorDataPathProperty)X.errorPath=X.opts.jsonPointers?X.util.getPathExpr(T,E,!0):T+" + "+E;var Z=Z||[];if(Z.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'required' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { missingProperty: '"+R+"' } ",X.opts.messages!==!1){if(G+=" , message: '",X.opts._errorDataPathProperty)G+="is a required property";else G+="should have required property \\'"+R+"\\'";G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";var v=G;if(G=Z.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+v+"]); ";else G+=" validate.errors = ["+v+"]; return false; ";else G+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";G+=" } else { "}else if(b){if(!L)G+=" var "+K+" = validate.schema"+j+"; ";var I="i"+H,E="schema"+H+"["+I+"]",R="' + "+E+" + '";if(X.opts._errorDataPathProperty)X.errorPath=X.util.getPathExpr(T,E,X.opts.jsonPointers);if(L){if(G+=" if ("+K+" && !Array.isArray("+K+")) { var err = ",X.createErrors!==!1){if(G+=" { keyword: 'required' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { missingProperty: '"+R+"' } ",X.opts.messages!==!1){if(G+=" , message: '",X.opts._errorDataPathProperty)G+="is a required property";else G+="should have required property \\'"+R+"\\'";G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+K+" !== undefined) { "}if(G+=" for (var "+I+" = 0; "+I+" < "+K+".length; "+I+"++) { if ("+F+"["+K+"["+I+"]] === undefined ",k)G+=" || ! Object.prototype.hasOwnProperty.call("+F+", "+K+"["+I+"]) ";if(G+=") { var err = ",X.createErrors!==!1){if(G+=" { keyword: 'required' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { missingProperty: '"+R+"' } ",X.opts.messages!==!1){if(G+=" , message: '",X.opts._errorDataPathProperty)G+="is a required property";else G+="should have required property \\'"+R+"\\'";G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";if(G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",L)G+=" } "}else{var d=M;if(d){var m,t=-1,Q0=d.length-1;while(t<Q0){m=d[t+=1];var l=X.util.getProperty(m),R=X.util.escapeQuotes(m),r=F+l;if(X.opts._errorDataPathProperty)X.errorPath=X.util.getPath(T,m,X.opts.jsonPointers);if(G+=" if ( "+r+" === undefined ",k)G+=" || ! Object.prototype.hasOwnProperty.call("+F+", '"+X.util.escapeQuotes(m)+"') ";if(G+=") { var err = ",X.createErrors!==!1){if(G+=" { keyword: 'required' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { missingProperty: '"+R+"' } ",X.opts.messages!==!1){if(G+=" , message: '",X.opts._errorDataPathProperty)G+="is a required property";else G+="should have required property \\'"+R+"\\'";G+="' "}if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" ";G+=" } "}else G+=" {} ";G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}}X.errorPath=T}else if(V)G+=" if (true) {";return G}}),EH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F="data"+(U||""),D="valid"+H,L=X.opts.$data&&z&&z.$data,N;if(L)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",N="schema"+H;else N=z;if((z||L)&&X.opts.uniqueItems!==!1){if(L)G+=" var "+D+"; if ("+N+" === false || "+N+" === undefined) "+D+" = true; else if (typeof "+N+" != 'boolean') "+D+" = false; else { ";G+=" var i = "+F+".length , "+D+" = true , j; if (i > 1) { ";var K=X.schema.items&&X.schema.items.type,M=Array.isArray(K);if(!K||K=="object"||K=="array"||M&&(K.indexOf("object")>=0||K.indexOf("array")>=0))G+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+F+"[i], "+F+"[j])) { "+D+" = false; break outer; } } } ";else{G+=" var itemIndices = {}, item; for (;i--;) { var item = "+F+"[i]; ";var w="checkDataType"+(M?"s":"");if(G+=" if ("+X.util[w](K,"item",X.opts.strictNumbers,!0)+") continue; ",M)G+=` if (typeof item == 'string') item = '"' + item; `;G+=" if (typeof itemIndices[item] == 'number') { "+D+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}if(G+=" } ",L)G+=" } ";G+=" if (!"+D+") { ";var _=_||[];if(_.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { i: i, j: j } ",X.opts.messages!==!1)G+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' ";if(X.opts.verbose){if(G+=" , schema: ",L)G+="validate.schema"+j;else G+=""+z;G+=" , parentSchema: validate.schema"+X.schemaPath+" , data: "+F+" "}G+=" } "}else G+=" {} ";var g=G;if(G=_.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+g+"]); ";else G+=" validate.errors = ["+g+"]; return false; ";else G+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(G+=" } ",V)G+=" else { "}else if(V)G+=" if (true) { ";return G}}),PH=V0((Q,Y)=>{Y.exports={$ref:BH(),allOf:qH(),anyOf:HH(),$comment:zH(),const:UH(),contains:LH(),dependencies:FH(),enum:NH(),format:jH(),if:KH(),items:MH(),maximum:Q5(),minimum:Q5(),maxItems:X5(),minItems:X5(),maxLength:Y5(),minLength:Y5(),maxProperties:J5(),minProperties:J5(),multipleOf:AH(),not:VH(),oneOf:DH(),pattern:wH(),properties:OH(),propertyNames:RH(),required:ZH(),uniqueItems:EH(),validate:A5()}}),SH=V0((Q,Y)=>{var J=PH(),X=O8().toHash;Y.exports=function(){var q=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],G=["type","$comment"],H=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],U=["number","integer","string","array","object","boolean","null"];return q.all=X(G),q.types=X(U),q.forEach(function(z){if(z.rules=z.rules.map(function(j){var A;if(typeof j=="object"){var V=Object.keys(j)[0];A=j[V],j=V,A.forEach(function(D){G.push(D),q.all[D]=!0})}G.push(j);var F=q.all[j]={keyword:j,code:J[j],implements:A};return F}),q.all.$comment={keyword:"$comment",code:J.$comment},z.type)q.types[z.type]=z}),q.keywords=X(G.concat(H)),q.custom={},q}}),IH=V0((Q,Y)=>{var J=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];Y.exports=function(X,B){for(var q=0;q<B.length;q++){X=JSON.parse(JSON.stringify(X));var G=B[q].split("/"),H=X,U;for(U=1;U<G.length;U++)H=H[G[U]];for(U=0;U<J.length;U++){var z=J[U],j=H[z];if(j)H[z]={anyOf:[j,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}}}return X}}),CH=V0((Q,Y)=>{var J=lX().MissingRef;Y.exports=X;function X(B,q,G){var H=this;if(typeof this._opts.loadSchema!="function")throw Error("options.loadSchema should be a function");if(typeof q=="function")G=q,q=void 0;var U=z(B).then(function(){var A=H._addSchema(B,void 0,q);return A.validate||j(A)});if(G)U.then(function(A){G(null,A)},G);return U;function z(A){var V=A.$schema;return V&&!H.getSchema(V)?X.call(H,{$ref:V},!0):Promise.resolve()}function j(A){try{return H._compile(A)}catch(F){if(F instanceof J)return V(F);throw F}function V(F){var D=F.missingSchema;if(K(D))throw Error("Schema "+D+" is loaded but "+F.missingRef+" cannot be resolved");var L=H._loadingSchemas[D];if(!L)L=H._loadingSchemas[D]=H._opts.loadSchema(D),L.then(N,N);return L.then(function(M){if(!K(D))return z(M).then(function(){if(!K(D))H.addSchema(M,D,void 0,q)})}).then(function(){return j(A)});function N(){delete H._loadingSchemas[D]}function K(M){return H._refs[M]||H._schemas[M]}}}}}),bH=V0((Q,Y)=>{Y.exports=function(X,B,q){var G=" ",H=X.level,U=X.dataLevel,z=X.schema[B],j=X.schemaPath+X.util.getProperty(B),A=X.errSchemaPath+"/"+B,V=!X.opts.allErrors,F,D="data"+(U||""),L="valid"+H,N="errs__"+H,K=X.opts.$data&&z&&z.$data,M;if(K)G+=" var schema"+H+" = "+X.util.getData(z.$data,U,X.dataPathArr)+"; ",M="schema"+H;else M=z;var w=this,_="definition"+H,g=w.definition,S="",C,T,b,k,I;if(K&&g.$data){I="keywordValidate"+H;var E=g.validateSchema;G+=" var "+_+" = RULES.custom['"+B+"'].definition; var "+I+" = "+_+".validate;"}else{if(k=X.useCustomRule(w,z,X.schema,X),!k)return;M="validate.schema"+j,I=k.code,C=g.compile,T=g.inline,b=g.macro}var R=I+".errors",Z="i"+H,v="ruleErr"+H,y=g.async;if(y&&!X.async)throw Error("async keyword in sync schema");if(!(T||b))G+=""+R+" = null;";if(G+="var "+N+" = errors;var "+L+";",K&&g.$data){if(S+="}",G+=" if ("+M+" === undefined) { "+L+" = true; } else { ",E)S+="}",G+=" "+L+" = "+_+".validateSchema("+M+"); if ("+L+") { "}if(T)if(g.statements)G+=" "+k.validate+" ";else G+=" "+L+" = "+k.validate+"; ";else if(b){var m=X.util.copy(X),S="";m.level++;var i="valid"+m.level;m.schema=k.validate,m.schemaPath="";var l=X.compositeRule;X.compositeRule=m.compositeRule=!0;var r=X.validate(m).replace(/validate\.schema/g,I);X.compositeRule=m.compositeRule=l,G+=" "+r}else{var d=d||[];if(d.push(G),G="",G+=" "+I+".call( ",X.opts.passContext)G+="this";else G+="self";if(C||g.schema===!1)G+=" , "+D+" ";else G+=" , "+M+" , "+D+" , validate.schema"+X.schemaPath+" ";if(G+=" , (dataPath || '')",X.errorPath!='""')G+=" + "+X.errorPath;var t=U?"data"+(U-1||""):"parentData",Q0=U?X.dataPathArr[U]:"parentDataProperty";G+=" , "+t+" , "+Q0+" , rootData ) ";var $=G;if(G=d.pop(),g.errors===!1){if(G+=" "+L+" = ",y)G+="await ";G+=""+$+"; "}else if(y)R="customErrors"+H,G+=" var "+R+" = null; try { "+L+" = await "+$+"; } catch (e) { "+L+" = false; if (e instanceof ValidationError) "+R+" = e.errors; else throw e; } ";else G+=" "+R+" = null; "+L+" = "+$+"; "}if(g.modifying)G+=" if ("+t+") "+D+" = "+t+"["+Q0+"];";if(G+=""+S,g.valid){if(V)G+=" if (true) { "}else{if(G+=" if ( ",g.valid===void 0)if(G+=" !",b)G+=""+i;else G+=""+L;else G+=" "+!g.valid+" ";G+=") { ",F=w.keyword;var d=d||[];d.push(G),G="";var d=d||[];if(d.push(G),G="",X.createErrors!==!1){if(G+=" { keyword: '"+(F||"custom")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { keyword: '"+w.keyword+"' } ",X.opts.messages!==!1)G+=` , message: 'should pass "`+w.keyword+`" keyword validation' `;if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+D+" ";G+=" } "}else G+=" {} ";var H0=G;if(G=d.pop(),!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(["+H0+"]); ";else G+=" validate.errors = ["+H0+"]; return false; ";else G+=" var err = "+H0+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var E0=G;if(G=d.pop(),T)if(g.errors){if(g.errors!="full"){if(G+=" for (var "+Z+"="+N+"; "+Z+"<errors; "+Z+"++) { var "+v+" = vErrors["+Z+"]; if ("+v+".dataPath === undefined) "+v+".dataPath = (dataPath || '') + "+X.errorPath+"; if ("+v+".schemaPath === undefined) { "+v+'.schemaPath = "'+A+'"; } ',X.opts.verbose)G+=" "+v+".schema = "+M+"; "+v+".data = "+D+"; ";G+=" } "}}else if(g.errors===!1)G+=" "+E0+" ";else{if(G+=" if ("+N+" == errors) { "+E0+" } else { for (var "+Z+"="+N+"; "+Z+"<errors; "+Z+"++) { var "+v+" = vErrors["+Z+"]; if ("+v+".dataPath === undefined) "+v+".dataPath = (dataPath || '') + "+X.errorPath+"; if ("+v+".schemaPath === undefined) { "+v+'.schemaPath = "'+A+'"; } ',X.opts.verbose)G+=" "+v+".schema = "+M+"; "+v+".data = "+D+"; ";G+=" } } "}else if(b){if(G+=" var err = ",X.createErrors!==!1){if(G+=" { keyword: '"+(F||"custom")+"' , dataPath: (dataPath || '') + "+X.errorPath+" , schemaPath: "+X.util.toQuotedString(A)+" , params: { keyword: '"+w.keyword+"' } ",X.opts.messages!==!1)G+=` , message: 'should pass "`+w.keyword+`" keyword validation' `;if(X.opts.verbose)G+=" , schema: validate.schema"+j+" , parentSchema: validate.schema"+X.schemaPath+" , data: "+D+" ";G+=" } "}else G+=" {} ";if(G+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!X.compositeRule&&V)if(X.async)G+=" throw new ValidationError(vErrors); ";else G+=" validate.errors = vErrors; return false; "}else if(g.errors===!1)G+=" "+E0+" ";else{if(G+=" if (Array.isArray("+R+")) { if (vErrors === null) vErrors = "+R+"; else vErrors = vErrors.concat("+R+"); errors = vErrors.length; for (var "+Z+"="+N+"; "+Z+"<errors; "+Z+"++) { var "+v+" = vErrors["+Z+"]; if ("+v+".dataPath === undefined) "+v+".dataPath = (dataPath || '') + "+X.errorPath+"; "+v+'.schemaPath = "'+A+'"; ',X.opts.verbose)G+=" "+v+".schema = "+M+"; "+v+".data = "+D+"; ";G+=" } } else { "+E0+" } "}if(G+=" } ",V)G+=" else { "}return G}}),V5=V0((Q,Y)=>{Y.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),TH=V0((Q,Y)=>{var J=V5();Y.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:J.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:J.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}}),_H=V0((Q,Y)=>{var J=/^[a-z_$][a-z0-9_$-]*$/i,X=bH(),B=TH();Y.exports={add:q,get:G,remove:H,validate:U};function q(z,j){var A=this.RULES;if(A.keywords[z])throw Error("Keyword "+z+" is already defined");if(!J.test(z))throw Error("Keyword "+z+" is not a valid identifier");if(j){this.validateKeyword(j,!0);var V=j.type;if(Array.isArray(V))for(var F=0;F<V.length;F++)L(z,V[F],j);else L(z,V,j);var D=j.metaSchema;if(D){if(j.$data&&this._opts.$data)D={anyOf:[D,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]};j.validateSchema=this.compile(D,!0)}}A.keywords[z]=A.all[z]=!0;function L(N,K,M){var w;for(var _=0;_<A.length;_++){var g=A[_];if(g.type==K){w=g;break}}if(!w)w={type:K,rules:[]},A.push(w);var S={keyword:N,definition:M,custom:!0,code:X,implements:M.implements};w.rules.push(S),A.custom[N]=S}return this}function G(z){var j=this.RULES.custom[z];return j?j.definition:this.RULES.keywords[z]||!1}function H(z){var j=this.RULES;delete j.keywords[z],delete j.all[z],delete j.custom[z];for(var A=0;A<j.length;A++){var V=j[A].rules;for(var F=0;F<V.length;F++)if(V[F].keyword==z){V.splice(F,1);break}}return this}function U(z,j){U.errors=null;var A=this._validateKeyword=this._validateKeyword||this.compile(B,!0);if(A(z))return!0;if(U.errors=A.errors,j)throw Error("custom keyword definition is invalid: "+this.errorsText(A.errors));else return!1}}),kH=V0((Q,Y)=>{Y.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),vH=V0((Q,Y)=>{var J=JH(),X=dX(),B=WH(),q=K5(),G=M5(),H=GH(),U=SH(),z=IH(),j=O8();Y.exports=N,N.prototype.validate=K,N.prototype.compile=M,N.prototype.addSchema=w,N.prototype.addMetaSchema=_,N.prototype.validateSchema=g,N.prototype.getSchema=C,N.prototype.removeSchema=k,N.prototype.addFormat=l,N.prototype.errorsText=i,N.prototype._addSchema=E,N.prototype._compile=R,N.prototype.compileAsync=CH();var A=_H();N.prototype.addKeyword=A.add,N.prototype.getKeyword=A.get,N.prototype.removeKeyword=A.remove,N.prototype.validateKeyword=A.validate;var V=lX();N.ValidationError=V.Validation,N.MissingRefError=V.MissingRef,N.$dataMetaSchema=z;var F="http://json-schema.org/draft-07/schema",D=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],L=["/properties"];function N(h){if(!(this instanceof N))return new N(h);if(h=this._opts=j.copy(h)||{},E0(this),this._schemas={},this._refs={},this._fragments={},this._formats=H(h.format),this._cache=h.cache||new B,this._loadingSchemas={},this._compilations=[],this.RULES=U(),this._getId=Z(h),h.loopRequired=h.loopRequired||1/0,h.errorDataPath=="property")h._errorDataPathProperty=!0;if(h.serialize===void 0)h.serialize=G;if(this._metaOpts=H0(this),h.formats)t(this);if(h.keywords)Q0(this);if(r(this),typeof h.meta=="object")this.addMetaSchema(h.meta);if(h.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});d(this)}function K(h,n){var z0;if(typeof h=="string"){if(z0=this.getSchema(h),!z0)throw Error('no schema with key or ref "'+h+'"')}else{var D0=this._addSchema(h);z0=D0.validate||this._compile(D0)}var a=z0(n);if(z0.$async!==!0)this.errors=z0.errors;return a}function M(h,n){var z0=this._addSchema(h,void 0,n);return z0.validate||this._compile(z0)}function w(h,n,z0,D0){if(Array.isArray(h)){for(var a=0;a<h.length;a++)this.addSchema(h[a],void 0,z0,D0);return this}var X0=this._getId(h);if(X0!==void 0&&typeof X0!="string")throw Error("schema id must be string");return n=X.normalizeId(n||X0),$(this,n),this._schemas[n]=this._addSchema(h,z0,D0,!0),this}function _(h,n,z0){return this.addSchema(h,n,z0,!0),this}function g(h,n){var z0=h.$schema;if(z0!==void 0&&typeof z0!="string")throw Error("$schema must be a string");if(z0=z0||this._opts.defaultMeta||S(this),!z0)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var D0=this.validate(z0,h);if(!D0&&n){var a="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(a);else throw Error(a)}return D0}function S(h){var n=h._opts.meta;return h._opts.defaultMeta=typeof n=="object"?h._getId(n)||n:h.getSchema(F)?F:void 0,h._opts.defaultMeta}function C(h){var n=b(this,h);switch(typeof n){case"object":return n.validate||this._compile(n);case"string":return this.getSchema(n);case"undefined":return T(this,h)}}function T(h,n){var z0=X.schema.call(h,{schema:{}},n);if(z0){var{schema:D0,root:a,baseId:X0}=z0,P0=J.call(h,D0,a,void 0,X0);return h._fragments[n]=new q({ref:n,fragment:!0,schema:D0,root:a,baseId:X0,validate:P0}),P0}}function b(h,n){return n=X.normalizeId(n),h._schemas[n]||h._refs[n]||h._fragments[n]}function k(h){if(h instanceof RegExp)return I(this,this._schemas,h),I(this,this._refs,h),this;switch(typeof h){case"undefined":return I(this,this._schemas),I(this,this._refs),this._cache.clear(),this;case"string":var n=b(this,h);if(n)this._cache.del(n.cacheKey);return delete this._schemas[h],delete this._refs[h],this;case"object":var z0=this._opts.serialize,D0=z0?z0(h):h;this._cache.del(D0);var a=this._getId(h);if(a)a=X.normalizeId(a),delete this._schemas[a],delete this._refs[a]}return this}function I(h,n,z0){for(var D0 in n){var a=n[D0];if(!a.meta&&(!z0||z0.test(D0)))h._cache.del(a.cacheKey),delete n[D0]}}function E(h,n,z0,D0){if(typeof h!="object"&&typeof h!="boolean")throw Error("schema should be object or boolean");var a=this._opts.serialize,X0=a?a(h):h,P0=this._cache.get(X0);if(P0)return P0;D0=D0||this._opts.addUsedSchema!==!1;var _0=X.normalizeId(this._getId(h));if(_0&&D0)$(this,_0);var A0=this._opts.validateSchema!==!1&&!n,l0;if(A0&&!(l0=_0&&_0==X.normalizeId(h.$schema)))this.validateSchema(h,!0);var p0=X.ids.call(this,h),y0=new q({id:_0,schema:h,localRefs:p0,cacheKey:X0,meta:z0});if(_0[0]!="#"&&D0)this._refs[_0]=y0;if(this._cache.put(X0,y0),A0&&l0)this.validateSchema(h,!0);return y0}function R(h,n){if(h.compiling){if(h.validate=a,a.schema=h.schema,a.errors=null,a.root=n?n:a,h.schema.$async===!0)a.$async=!0;return a}h.compiling=!0;var z0;if(h.meta)z0=this._opts,this._opts=this._metaOpts;var D0;try{D0=J.call(this,h.schema,n,h.localRefs)}catch(X0){throw delete h.validate,X0}finally{if(h.compiling=!1,h.meta)this._opts=z0}return h.validate=D0,h.refs=D0.refs,h.refVal=D0.refVal,h.root=D0.root,D0;function a(){var X0=h.validate,P0=X0.apply(this,arguments);return a.errors=X0.errors,P0}}function Z(h){switch(h.schemaId){case"auto":return m;case"id":return v;default:return y}}function v(h){if(h.$id)this.logger.warn("schema $id ignored",h.$id);return h.id}function y(h){if(h.id)this.logger.warn("schema id ignored",h.id);return h.$id}function m(h){if(h.$id&&h.id&&h.$id!=h.id)throw Error("schema $id is different from id");return h.$id||h.id}function i(h,n){if(h=h||this.errors,!h)return"No errors";n=n||{};var z0=n.separator===void 0?", ":n.separator,D0=n.dataVar===void 0?"data":n.dataVar,a="";for(var X0=0;X0<h.length;X0++){var P0=h[X0];if(P0)a+=D0+P0.dataPath+" "+P0.message+z0}return a.slice(0,-z0.length)}function l(h,n){if(typeof n=="string")n=new RegExp(n);return this._formats[h]=n,this}function r(h){var n;if(h._opts.$data)n=kH(),h.addMetaSchema(n,n.$id,!0);if(h._opts.meta===!1)return;var z0=V5();if(h._opts.$data)z0=z(z0,L);h.addMetaSchema(z0,F,!0),h._refs["http://json-schema.org/schema"]=F}function d(h){var n=h._opts.schemas;if(!n)return;if(Array.isArray(n))h.addSchema(n);else for(var z0 in n)h.addSchema(n[z0],z0)}function t(h){for(var n in h._opts.formats){var z0=h._opts.formats[n];h.addFormat(n,z0)}}function Q0(h){for(var n in h._opts.keywords){var z0=h._opts.keywords[n];h.addKeyword(n,z0)}}function $(h,n){if(h._schemas[n]||h._refs[n])throw Error('schema with key or id "'+n+'" already exists')}function H0(h){var n=j.copy(h._opts);for(var z0=0;z0<D.length;z0++)delete n[D[z0]];return n}function E0(h){var n=h._opts.logger;if(n===!1)h.logger={log:M0,warn:M0,error:M0};else{if(n===void 0)n=console;if(!(typeof n=="object"&&n.log&&n.warn&&n.error))throw Error("logger must implement log, warn and error methods");h.logger=n}}function M0(){}}),yH=50;function D5(Q=yH){let Y=new AbortController;return gH(Q,Y.signal),Y}var mH={cwd(){return process.cwd()},existsSync(Q){return K0.existsSync(Q)},async stat(Q){return hH(Q)},statSync(Q){return K0.statSync(Q)},readFileSync(Q,Y){return K0.readFileSync(Q,{encoding:Y.encoding})},readFileBytesSync(Q){return K0.readFileSync(Q)},readSync(Q,Y){let J=void 0;try{J=K0.openSync(Q,"r");let X=Buffer.alloc(Y.length),B=K0.readSync(J,X,0,Y.length,0);return{buffer:X,bytesRead:B}}finally{if(J)K0.closeSync(J)}},writeFileSync(Q,Y,J){if(!J.flush){let B={encoding:J.encoding};if(J.mode!==void 0)B.mode=J.mode;K0.writeFileSync(Q,Y,B);return}let X;try{let B=J.mode!==void 0?J.mode:void 0;X=K0.openSync(Q,"w",B),K0.writeFileSync(X,Y,{encoding:J.encoding}),K0.fsyncSync(X)}finally{if(X)K0.closeSync(X)}},appendFileSync(Q,Y){K0.appendFileSync(Q,Y)},copyFileSync(Q,Y){K0.copyFileSync(Q,Y)},unlinkSync(Q){K0.unlinkSync(Q)},renameSync(Q,Y){K0.renameSync(Q,Y)},linkSync(Q,Y){K0.linkSync(Q,Y)},symlinkSync(Q,Y){K0.symlinkSync(Q,Y)},readlinkSync(Q){return K0.readlinkSync(Q)},realpathSync(Q){return K0.realpathSync(Q)},mkdirSync(Q){if(!K0.existsSync(Q))K0.mkdirSync(Q,{recursive:!0,mode:448})},readdirSync(Q){return K0.readdirSync(Q,{withFileTypes:!0})},readdirStringSync(Q){return K0.readdirSync(Q)},isDirEmptySync(Q){return this.readdirSync(Q).length===0},rmdirSync(Q){K0.rmdirSync(Q)},rmSync(Q,Y){K0.rmSync(Q,Y)},createWriteStream(Q){return K0.createWriteStream(Q)}},uH=mH;function j9(){return uH}class B8 extends Error{}function w5(){return process.versions.bun!==void 0}class O5{options;child;childStdin;childStdout;ready=!1;abortController;exitError;exitListeners=[];processExitHandler;abortHandler;constructor(Q){this.options=Q,this.abortController=Q.abortController||D5(),this.initialize()}initialize(){try{let{additionalDirectories:Q=[],agents:Y,cwd:J,executable:X=w5()?"bun":"node",executableArgs:B=[],extraArgs:q={},pathToClaudeCodeExecutable:G,env:H={...process.env},stderr:U,customSystemPrompt:z,appendSystemPrompt:j,maxThinkingTokens:A,maxTurns:V,maxBudgetUsd:F,model:D,fallbackModel:L,permissionMode:N,allowDangerouslySkipPermissions:K,permissionPromptToolName:M,continueConversation:w,resume:_,settingSources:g,allowedTools:S=[],disallowedTools:C=[],mcpServers:T,strictMcpConfig:b,canUseTool:k,includePartialMessages:I,plugins:E}=this.options,R=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(typeof z==="string")R.push("--system-prompt",z);if(j)R.push("--append-system-prompt",j);if(A!==void 0)R.push("--max-thinking-tokens",A.toString());if(V)R.push("--max-turns",V.toString());if(F!==void 0)R.push("--max-budget-usd",F.toString());if(D)R.push("--model",D);if(H.DEBUG)R.push("--debug-to-stderr");if(k){if(M)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");R.push("--permission-prompt-tool","stdio")}else if(M)R.push("--permission-prompt-tool",M);if(w)R.push("--continue");if(_)R.push("--resume",_);if(S.length>0)R.push("--allowedTools",S.join(","));if(C.length>0)R.push("--disallowedTools",C.join(","));if(T&&Object.keys(T).length>0)R.push("--mcp-config",JSON.stringify({mcpServers:T}));if(Y&&Object.keys(Y).length>0)R.push("--agents",JSON.stringify(Y));if(g)R.push("--setting-sources",g.join(","));if(b)R.push("--strict-mcp-config");if(N)R.push("--permission-mode",N);if(K)R.push("--allow-dangerously-skip-permissions");if(L){if(D&&L===D)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");R.push("--fallback-model",L)}if(I)R.push("--include-partial-messages");for(let r of Q)R.push("--add-dir",r);if(E&&E.length>0)for(let r of E)if(r.type==="local")R.push("--plugin-dir",r.path);else throw Error(`Unsupported plugin type: ${r.type}`);if(this.options.forkSession)R.push("--fork-session");if(this.options.resumeSessionAt)R.push("--resume-session-at",this.options.resumeSessionAt);for(let[r,d]of Object.entries(q))if(d===null)R.push(`--${r}`);else R.push(`--${r}`,d);if(!H.CLAUDE_CODE_ENTRYPOINT)H.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!j9().existsSync(G)){let r=G5(G)?`Claude Code native binary not found at ${G}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${G}. Is options.pathToClaudeCodeExecutable set?`;throw ReferenceError(r)}let v=G5(G),y=v?G:X,m=v?[...B,...R]:[...B,G,...R];this.logForDebugging(v?`Spawning Claude Code native binary: ${y} ${m.join(" ")}`:`Spawning Claude Code process: ${y} ${m.join(" ")}`);let i=H.DEBUG||U?"pipe":"ignore";if(this.child=$H(y,m,{cwd:J,stdio:["pipe","pipe",i],signal:this.abortController.signal,env:H}),this.childStdin=this.child.stdin,this.childStdout=this.child.stdout,H.DEBUG||U)this.child.stderr.on("data",(r)=>{this.logForDebugging(r.toString())});let l=()=>{if(this.child&&!this.child.killed)this.child.kill("SIGTERM")};this.processExitHandler=l,this.abortHandler=l,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.child.on("error",(r)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new B8("Claude Code process aborted by user");else this.exitError=Error(`Failed to spawn Claude Code process: ${r.message}`),this.logForDebugging(this.exitError.message)}),this.child.on("close",(r,d)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new B8("Claude Code process aborted by user");else{let t=this.getProcessExitError(r,d);if(t)this.exitError=t,this.logForDebugging(t.message)}}),this.ready=!0}catch(Q){throw this.ready=!1,Q}}getProcessExitError(Q,Y){if(Q!==0&&Q!==null)return Error(`Claude Code process exited with code ${Q}`);else if(Y)return Error(`Claude Code process terminated by signal ${Y}`);return}logForDebugging(Q){if(process.env.DEBUG)process.stderr.write(`${Q}
41
- `);if(this.options.stderr)this.options.stderr(Q)}write(Q){if(this.abortController.signal.aborted)throw new B8("Operation aborted");if(!this.ready||!this.childStdin)throw Error("ProcessTransport is not ready for writing");if(this.child?.killed||this.child?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);if(process.env.DEBUG_SDK)process.stderr.write(`[ProcessTransport] Writing to stdin: ${Q.substring(0,100)}
42
- `);try{if(!this.childStdin.write(Q)&&process.env.DEBUG_SDK)console.warn("[ProcessTransport] Write buffer full, data queued")}catch(Y){throw this.ready=!1,Error(`Failed to write to process stdin: ${Y.message}`)}}close(){if(this.childStdin)this.childStdin.end(),this.childStdin=void 0;if(this.processExitHandler)process.off("exit",this.processExitHandler),this.processExitHandler=void 0;if(this.abortHandler)this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0;for(let{handler:Q}of this.exitListeners)this.child?.off("exit",Q);if(this.exitListeners=[],this.child&&!this.child.killed)this.child.kill("SIGTERM"),setTimeout(()=>{if(this.child&&!this.child.killed)this.child.kill("SIGKILL")},5000);this.ready=!1}isReady(){return this.ready}async*readMessages(){if(!this.childStdout)throw Error("ProcessTransport output stream not available");let Q=fH({input:this.childStdout});try{for await(let Y of Q)if(Y.trim())yield JSON.parse(Y);await this.waitForExit()}catch(Y){throw Y}finally{Q.close()}}endInput(){if(this.childStdin)this.childStdin.end()}getInputStream(){return this.childStdin}onExit(Q){if(!this.child)return()=>{};let Y=(J,X)=>{let B=this.getProcessExitError(J,X);Q(B)};return this.child.on("exit",Y),this.exitListeners.push({callback:Q,handler:Y}),()=>{if(this.child)this.child.off("exit",Y);let J=this.exitListeners.findIndex((X)=>X.handler===Y);if(J!==-1)this.exitListeners.splice(J,1)}}async waitForExit(){if(!this.child){if(this.exitError)throw this.exitError;return}if(this.child.exitCode!==null||this.child.killed){if(this.exitError)throw this.exitError;return}return new Promise((Q,Y)=>{let J=(B,q)=>{if(this.abortController.signal.aborted){Y(new B8("Operation aborted"));return}let G=this.getProcessExitError(B,q);if(G)Y(G);else Q()};this.child.once("exit",J);let X=(B)=>{this.child.off("exit",J),Y(B)};this.child.once("error",X),this.child.once("exit",()=>{this.child.off("error",X)})})}}function G5(Q){return![".js",".mjs",".tsx",".ts",".jsx"].some((J)=>Q.endsWith(J))}class R5{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(Q){this.returned=Q}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise((Q,Y)=>{this.readResolve=Q,this.readReject=Y})}enqueue(Q){if(this.readResolve){let Y=this.readResolve;this.readResolve=void 0,this.readReject=void 0,Y({done:!1,value:Q})}else this.queue.push(Q)}done(){if(this.isDone=!0,this.readResolve){let Q=this.readResolve;this.readResolve=void 0,this.readReject=void 0,Q({done:!0,value:void 0})}}error(Q){if(this.hasError=Q,this.readReject){let Y=this.readReject;this.readResolve=void 0,this.readReject=void 0,Y(Q)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}class Z5{sendMcpMessage;isClosed=!1;constructor(Q){this.sendMcpMessage=Q}onclose;onerror;onmessage;async start(){}async send(Q){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(Q)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}var cH=typeof global=="object"&&global&&global.Object===Object&&global,dH=cH,lH=typeof self=="object"&&self&&self.Object===Object&&self,pH=dH||lH||Function("return this")(),pX=pH,nH=pX.Symbol,$Q=nH,E5=Object.prototype,iH=E5.hasOwnProperty,aH=E5.toString,r8=$Q?$Q.toStringTag:void 0;function sH(Q){var Y=iH.call(Q,r8),J=Q[r8];try{Q[r8]=void 0;var X=!0}catch(q){}var B=aH.call(Q);if(X)if(Y)Q[r8]=J;else delete Q[r8];return B}var oH=sH,rH=Object.prototype,tH=rH.toString;function eH(Q){return tH.call(Q)}var Qz=eH,Xz="[object Null]",Yz="[object Undefined]",B5=$Q?$Q.toStringTag:void 0;function Jz(Q){if(Q==null)return Q===void 0?Yz:Xz;return B5&&B5 in Object(Q)?oH(Q):Qz(Q)}var Wz=Jz;function Gz(Q){var Y=typeof Q;return Q!=null&&(Y=="object"||Y=="function")}var P5=Gz,Bz="[object AsyncFunction]",qz="[object Function]",Hz="[object GeneratorFunction]",zz="[object Proxy]";function Uz(Q){if(!P5(Q))return!1;var Y=Wz(Q);return Y==qz||Y==Hz||Y==Bz||Y==zz}var Lz=Uz,Fz=pX["__core-js_shared__"],kX=Fz,q5=function(){var Q=/[^.]+$/.exec(kX&&kX.keys&&kX.keys.IE_PROTO||"");return Q?"Symbol(src)_1."+Q:""}();function Nz(Q){return!!q5&&q5 in Q}var jz=Nz,Kz=Function.prototype,Mz=Kz.toString;function Az(Q){if(Q!=null){try{return Mz.call(Q)}catch(Y){}try{return Q+""}catch(Y){}}return""}var Vz=Az,Dz=/[\\^$.*+?()[\]{}|]/g,wz=/^\[object .+?Constructor\]$/,Oz=Function.prototype,Rz=Object.prototype,Zz=Oz.toString,Ez=Rz.hasOwnProperty,Pz=RegExp("^"+Zz.call(Ez).replace(Dz,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Sz(Q){if(!P5(Q)||jz(Q))return!1;var Y=Lz(Q)?Pz:wz;return Y.test(Vz(Q))}var Iz=Sz;function Cz(Q,Y){return Q==null?void 0:Q[Y]}var bz=Cz;function Tz(Q,Y){var J=bz(Q,Y);return Iz(J)?J:void 0}var S5=Tz;function _z(Q,Y){return Q===Y||Q!==Q&&Y!==Y}var kz=_z,vz=S5(Object,"create"),t8=vz;function xz(){this.__data__=t8?t8(null):{},this.size=0}var gz=xz;function yz(Q){var Y=this.has(Q)&&delete this.__data__[Q];return this.size-=Y?1:0,Y}var $z=yz,fz="__lodash_hash_undefined__",hz=Object.prototype,mz=hz.hasOwnProperty;function uz(Q){var Y=this.__data__;if(t8){var J=Y[Q];return J===fz?void 0:J}return mz.call(Y,Q)?Y[Q]:void 0}var cz=uz,dz=Object.prototype,lz=dz.hasOwnProperty;function pz(Q){var Y=this.__data__;return t8?Y[Q]!==void 0:lz.call(Y,Q)}var nz=pz,iz="__lodash_hash_undefined__";function az(Q,Y){var J=this.__data__;return this.size+=this.has(Q)?0:1,J[Q]=t8&&Y===void 0?iz:Y,this}var sz=az;function R8(Q){var Y=-1,J=Q==null?0:Q.length;this.clear();while(++Y<J){var X=Q[Y];this.set(X[0],X[1])}}R8.prototype.clear=gz;R8.prototype.delete=$z;R8.prototype.get=cz;R8.prototype.has=nz;R8.prototype.set=sz;var H5=R8;function oz(){this.__data__=[],this.size=0}var rz=oz;function tz(Q,Y){var J=Q.length;while(J--)if(kz(Q[J][0],Y))return J;return-1}var mQ=tz,ez=Array.prototype,QU=ez.splice;function XU(Q){var Y=this.__data__,J=mQ(Y,Q);if(J<0)return!1;var X=Y.length-1;if(J==X)Y.pop();else QU.call(Y,J,1);return--this.size,!0}var YU=XU;function JU(Q){var Y=this.__data__,J=mQ(Y,Q);return J<0?void 0:Y[J][1]}var WU=JU;function GU(Q){return mQ(this.__data__,Q)>-1}var BU=GU;function qU(Q,Y){var J=this.__data__,X=mQ(J,Q);if(X<0)++this.size,J.push([Q,Y]);else J[X][1]=Y;return this}var HU=qU;function Z8(Q){var Y=-1,J=Q==null?0:Q.length;this.clear();while(++Y<J){var X=Q[Y];this.set(X[0],X[1])}}Z8.prototype.clear=rz;Z8.prototype.delete=YU;Z8.prototype.get=WU;Z8.prototype.has=BU;Z8.prototype.set=HU;var zU=Z8,UU=S5(pX,"Map"),LU=UU;function FU(){this.size=0,this.__data__={hash:new H5,map:new(LU||zU),string:new H5}}var NU=FU;function jU(Q){var Y=typeof Q;return Y=="string"||Y=="number"||Y=="symbol"||Y=="boolean"?Q!=="__proto__":Q===null}var KU=jU;function MU(Q,Y){var J=Q.__data__;return KU(Y)?J[typeof Y=="string"?"string":"hash"]:J.map}var uQ=MU;function AU(Q){var Y=uQ(this,Q).delete(Q);return this.size-=Y?1:0,Y}var VU=AU;function DU(Q){return uQ(this,Q).get(Q)}var wU=DU;function OU(Q){return uQ(this,Q).has(Q)}var RU=OU;function ZU(Q,Y){var J=uQ(this,Q),X=J.size;return J.set(Q,Y),this.size+=J.size==X?0:1,this}var EU=ZU;function E8(Q){var Y=-1,J=Q==null?0:Q.length;this.clear();while(++Y<J){var X=Q[Y];this.set(X[0],X[1])}}E8.prototype.clear=NU;E8.prototype.delete=VU;E8.prototype.get=wU;E8.prototype.has=RU;E8.prototype.set=EU;var I5=E8,PU="Expected a function";function nX(Q,Y){if(typeof Q!="function"||Y!=null&&typeof Y!="function")throw TypeError(PU);var J=function(){var X=arguments,B=Y?Y.apply(this,X):X[0],q=J.cache;if(q.has(B))return q.get(B);var G=Q.apply(this,X);return J.cache=q.set(B,G)||q,G};return J.cache=new(nX.Cache||I5),J}nX.Cache=I5;var GQ=nX,z5=2000;function SU(Q){for(let Y=0;Y<Q.length;Y+=z5)process.stderr.write(Q.substring(Y,Y+z5))}var IU=GQ((Q)=>{if(!Q||Q.trim()==="")return null;let Y=Q.split(",").map((q)=>q.trim()).filter(Boolean);if(Y.length===0)return null;let J=Y.some((q)=>q.startsWith("!")),X=Y.some((q)=>!q.startsWith("!"));if(J&&X)return null;let B=Y.map((q)=>q.replace(/^!/,"").toLowerCase());return{include:J?[]:B,exclude:J?B:[],isExclusive:J}});function CU(Q){let Y=[],J=Q.match(/^MCP server ["']([^"']+)["']/);if(J&&J[1])Y.push("mcp"),Y.push(J[1].toLowerCase());else{let q=Q.match(/^([^:[]+):/);if(q&&q[1])Y.push(q[1].trim().toLowerCase())}let X=Q.match(/^\[([^\]]+)]/);if(X&&X[1])Y.push(X[1].trim().toLowerCase());if(Q.toLowerCase().includes("statsig event:"))Y.push("statsig");let B=Q.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(B&&B[1]){let q=B[1].trim().toLowerCase();if(q.length<30&&!q.includes(" "))Y.push(q)}return Array.from(new Set(Y))}function bU(Q,Y){if(!Y)return!0;if(Q.length===0)return!1;if(Y.isExclusive)return!Q.some((J)=>Y.exclude.includes(J));else return Q.some((J)=>Y.include.includes(J))}function TU(Q,Y){if(!Y)return!0;let J=CU(Q);return bU(J,Y)}function vU(){return process.env.CLAUDE_CONFIG_DIR??_U(kU(),".claude")}function U5(Q){if(!Q)return!1;if(typeof Q==="boolean")return Q;let Y=Q.toLowerCase().trim();return["1","true","yes","on"].includes(Y)}var $U={name:"BASH_MAX_OUTPUT_LENGTH",default:30000,validate:(Q)=>{if(!Q)return{effective:30000,status:"valid"};let X=parseInt(Q,10);if(isNaN(X)||X<=0)return{effective:30000,status:"invalid",message:`Invalid value "${Q}" (using default: 30000)`};if(X>150000)return{effective:150000,status:"capped",message:`Capped from ${X} to 150000`};return{effective:X,status:"valid"}}},fU={name:"CLAUDE_CODE_MAX_OUTPUT_TOKENS",default:32000,validate:(Q)=>{if(!Q)return{effective:32000,status:"valid"};let X=parseInt(Q,10);if(isNaN(X)||X<=0)return{effective:32000,status:"invalid",message:`Invalid value "${Q}" (using default: 32000)`};if(X>64000)return{effective:64000,status:"capped",message:`Capped from ${X} to 64000`};return{effective:X,status:"valid"}}};function hU(){let Q=gU(xU());return{originalCwd:Q,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:Q,modelUsage:{},mainLoopModelOverride:void 0,maxRateLimitFallbackActive:!1,initialMainLoopModel:null,modelStrings:null,isNonInteractiveSession:!0,isInteractive:!1,clientType:"cli",sessionIngressToken:void 0,oauthTokenFromFd:void 0,apiKeyFromFd:void 0,flagSettingsPath:void 0,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,sessionId:yU(),loggerProvider:null,eventLogger:null,meterProvider:null,tracerProvider:null,agentColorMap:new Map,agentColorIndex:0,envVarValidators:[$U,fU],lastAPIRequest:null,inMemoryErrorLog:[],inlinePlugins:[]}}var mU=hU();function uU(){return mU.sessionId}var RD=GQ(()=>{return U5(process.env.DEBUG)||U5(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||b5()||process.argv.some((Q)=>Q.startsWith("--debug="))}),cU=GQ(()=>{let Q=process.argv.find((J)=>J.startsWith("--debug="));if(!Q)return null;let Y=Q.substring(8);return IU(Y)}),b5=GQ(()=>{return process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e")});function dU(Q){if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let Y=cU();return TU(Q,Y)}var lU=!1;function L9(Q,{level:Y}={level:"debug"}){if(!dU(Q))return;if(lU&&Q.includes(`
43
- `))Q=JSON.stringify(Q);let J=`[${Y.toUpperCase()}] ${Q.trim()}
44
- `;if(b5()){SU(J);return}if(!j9().existsSync(gX(yQ())))j9().mkdirSync(gX(yQ()));j9().appendFileSync(yQ(),J),pU()}function yQ(){return process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??C5(vU(),"debug",`${uU()}.txt`)}var pU=GQ(()=>{try{let Q=yQ(),Y=gX(Q),J=C5(Y,"latest");if(!j9().existsSync(Y))j9().mkdirSync(Y);if(j9().existsSync(J))try{j9().unlinkSync(J)}catch{}j9().symlinkSync(Q,J)}catch{}});class T5{transport;isSingleUserTurn;canUseTool;hooks;abortController;pendingControlResponses=new Map;cleanupPerformed=!1;sdkMessages;inputStream=new R5;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;sdkMcpTransports=new Map;pendingMcpResponses=new Map;firstResultReceivedPromise;firstResultReceivedResolve;streamCloseTimeout;constructor(Q,Y,J,X,B,q=new Map){this.transport=Q,this.isSingleUserTurn=Y,this.canUseTool=J,this.hooks=X,this.abortController=B,this.streamCloseTimeout=parseInt(process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT||"")||60000;for(let[G,H]of q){let U=new Z5((z)=>this.sendMcpServerMessageToCli(G,z));this.sdkMcpTransports.set(G,U),H.connect(U)}this.sdkMessages=this.readSdkMessages(),this.firstResultReceivedPromise=new Promise((G)=>{this.firstResultReceivedResolve=G}),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError(Q){this.inputStream.error(Q)}cleanup(Q){if(this.cleanupPerformed)return;this.cleanupPerformed=!0;try{if(this.transport.close(),this.pendingControlResponses.clear(),this.pendingMcpResponses.clear(),Q)this.inputStream.error(Q);else this.inputStream.done()}catch(Y){}}next(...[Q]){return this.sdkMessages.next(...[Q])}return(Q){return this.sdkMessages.return(Q)}throw(Q){return this.sdkMessages.throw(Q)}[Symbol.asyncIterator](){return this.sdkMessages}[Symbol.asyncDispose](){return this.sdkMessages[Symbol.asyncDispose]()}async readMessages(){try{for await(let Q of this.transport.readMessages()){if(Q.type==="control_response"){let Y=this.pendingControlResponses.get(Q.response.request_id);if(Y)Y(Q.response);continue}else if(Q.type==="control_request"){this.handleControlRequest(Q);continue}else if(Q.type==="control_cancel_request"){this.handleControlCancelRequest(Q);continue}else if(Q.type==="keep_alive")continue;if(Q.type==="result"){if(this.firstResultReceivedResolve)this.firstResultReceivedResolve();if(this.isSingleUserTurn)this.transport.endInput()}this.inputStream.enqueue(Q)}this.inputStream.done(),this.cleanup()}catch(Q){this.inputStream.error(Q),this.cleanup(Q)}}async handleControlRequest(Q){let Y=new AbortController;this.cancelControllers.set(Q.request_id,Y);try{let J=await this.processControlRequest(Q,Y.signal),X={type:"control_response",response:{subtype:"success",request_id:Q.request_id,response:J}};await Promise.resolve(this.transport.write(JSON.stringify(X)+`
45
- `))}catch(J){let X={type:"control_response",response:{subtype:"error",request_id:Q.request_id,error:J.message||String(J)}};await Promise.resolve(this.transport.write(JSON.stringify(X)+`
46
- `))}finally{this.cancelControllers.delete(Q.request_id)}}handleControlCancelRequest(Q){let Y=this.cancelControllers.get(Q.request_id);if(Y)Y.abort(),this.cancelControllers.delete(Q.request_id)}async processControlRequest(Q,Y){if(Q.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");return this.canUseTool(Q.request.tool_name,Q.request.input,{signal:Y,suggestions:Q.request.permission_suggestions,toolUseID:Q.request.tool_use_id})}else if(Q.request.subtype==="hook_callback")return await this.handleHookCallbacks(Q.request.callback_id,Q.request.input,Q.request.tool_use_id,Y);else if(Q.request.subtype==="mcp_message"){let J=Q.request,X=this.sdkMcpTransports.get(J.server_name);if(!X)throw Error(`SDK MCP server not found: ${J.server_name}`);if("method"in J.message&&"id"in J.message&&J.message.id!==null)return{mcp_response:await this.handleMcpControlRequest(J.server_name,J,X)};else{if(X.onmessage)X.onmessage(J.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}throw Error("Unsupported control request subtype: "+Q.request.subtype)}async*readSdkMessages(){for await(let Q of this.inputStream)yield Q}async initialize(){let Q;if(this.hooks){Q={};for(let[B,q]of Object.entries(this.hooks))if(q.length>0)Q[B]=q.map((G)=>{let H=[];for(let U of G.hooks){let z=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(z,U),H.push(z)}return{matcher:G.matcher,hookCallbackIds:H}})}let Y=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,J={subtype:"initialize",hooks:Q,sdkMcpServers:Y};return(await this.request(J)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode(Q){await this.request({subtype:"set_permission_mode",mode:Q})}async setModel(Q){await this.request({subtype:"set_model",model:Q})}async setMaxThinkingTokens(Q){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:Q})}async processPendingPermissionRequests(Q){for(let Y of Q)if(Y.request.subtype==="can_use_tool")this.handleControlRequest(Y).catch(()=>{})}request(Q){let Y=Math.random().toString(36).substring(2,15),J={request_id:Y,type:"control_request",request:Q};return new Promise((X,B)=>{this.pendingControlResponses.set(Y,(q)=>{if(q.subtype==="success")X(q);else if(B(Error(q.error)),q.pending_permission_requests)this.processPendingPermissionRequests(q.pending_permission_requests)}),Promise.resolve(this.transport.write(JSON.stringify(J)+`
47
- `))})}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async accountInfo(){return(await this.initialization).account}async streamInput(Q){L9("[Query.streamInput] Starting to process input stream"),L9(`[Query.streamInput] this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`);try{let Y=0;for await(let X of Q){if(Y++,L9(`[Query.streamInput] Processing message ${Y}: ${X.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(JSON.stringify(X)+`
48
- `))}L9(`[Query.streamInput] Finished processing ${Y} messages from input stream`),L9(`[Query.streamInput] About to check MCP servers. this.sdkMcpTransports.size = ${this.sdkMcpTransports.size}`);let J=this.hooks&&Object.keys(this.hooks).length>0;if((this.sdkMcpTransports.size>0||J)&&this.firstResultReceivedPromise){L9("[Query.streamInput] Entering Promise.race to wait for result");let X;if(await Promise.race([this.firstResultReceivedPromise.then(()=>{if(L9("[Query.streamInput] Received first result, closing input stream"),X)clearTimeout(X)}),new Promise((B)=>{X=setTimeout(()=>{L9("[Query.streamInput] Timed out waiting for first result, closing input stream"),B()},this.streamCloseTimeout)})]),X)clearTimeout(X)}L9("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(Y){if(!(Y instanceof B8))throw Y}}handleHookCallbacks(Q,Y,J,X){let B=this.hookCallbacks.get(Q);if(!B)throw Error(`No hook callback found for ID: ${Q}`);return B(Y,J,{signal:X})}sendMcpServerMessageToCli(Q,Y){if("id"in Y&&Y.id!==null&&Y.id!==void 0){let J=`${Q}:${Y.id}`,X=this.pendingMcpResponses.get(J);if(X){X.resolve(Y),this.pendingMcpResponses.delete(J);return}}throw Error("No pending request found")}handleMcpControlRequest(Q,Y,J){let X="id"in Y.message?Y.message.id:null,B=`${Q}:${X}`;return new Promise((q,G)=>{let H=()=>{this.pendingMcpResponses.delete(B)},U=(j)=>{H(),q(j)},z=(j)=>{H(),G(j)};if(this.pendingMcpResponses.set(B,{resolve:U,reject:z}),J.onmessage)J.onmessage(Y.message);else{H(),G(Error("No message handler registered"));return}})}}var O={};eq(O,{void:()=>bL,util:()=>x0,unknown:()=>IL,union:()=>vL,undefined:()=>EL,tuple:()=>yL,transformer:()=>N5,symbol:()=>ZL,string:()=>$5,strictObject:()=>kL,setErrorMap:()=>aU,set:()=>hL,record:()=>$L,quotelessJson:()=>nU,promise:()=>pL,preprocess:()=>aL,pipeline:()=>sL,ostring:()=>oL,optional:()=>nL,onumber:()=>rL,oboolean:()=>tL,objectUtil:()=>yX,object:()=>_L,number:()=>f5,nullable:()=>iL,null:()=>PL,never:()=>CL,nativeEnum:()=>lL,nan:()=>wL,map:()=>fL,makeIssue:()=>hQ,literal:()=>cL,lazy:()=>uL,late:()=>VL,isValid:()=>y9,isDirty:()=>fX,isAsync:()=>e8,isAborted:()=>$X,intersection:()=>gL,instanceof:()=>DL,getParsedType:()=>N9,getErrorMap:()=>fQ,function:()=>mL,enum:()=>dL,effect:()=>N5,discriminatedUnion:()=>xL,defaultErrorMap:()=>z8,datetimeRegex:()=>x5,date:()=>RL,custom:()=>y5,coerce:()=>eL,boolean:()=>h5,bigint:()=>OL,array:()=>TL,any:()=>SL,addIssueToContext:()=>G0,ZodVoid:()=>XQ,ZodUnknown:()=>E9,ZodUnion:()=>N8,ZodUndefined:()=>L8,ZodType:()=>R0,ZodTuple:()=>r1,ZodTransformer:()=>T1,ZodSymbol:()=>QQ,ZodString:()=>f1,ZodSet:()=>h9,ZodSchema:()=>R0,ZodRecord:()=>YQ,ZodReadonly:()=>w8,ZodPromise:()=>m9,ZodPipeline:()=>BQ,ZodParsedType:()=>q0,ZodOptional:()=>m1,ZodObject:()=>t0,ZodNumber:()=>P9,ZodNullable:()=>K9,ZodNull:()=>F8,ZodNever:()=>o1,ZodNativeEnum:()=>A8,ZodNaN:()=>WQ,ZodMap:()=>JQ,ZodLiteral:()=>M8,ZodLazy:()=>K8,ZodIssueCode:()=>o,ZodIntersection:()=>j8,ZodFunction:()=>H8,ZodFirstPartyTypeKind:()=>j0,ZodError:()=>S1,ZodEnum:()=>I9,ZodEffects:()=>T1,ZodDiscriminatedUnion:()=>cQ,ZodDefault:()=>V8,ZodDate:()=>$9,ZodCatch:()=>D8,ZodBranded:()=>dQ,ZodBoolean:()=>U8,ZodBigInt:()=>S9,ZodArray:()=>h1,ZodAny:()=>f9,Schema:()=>R0,ParseStatus:()=>N1,OK:()=>A1,NEVER:()=>QF,INVALID:()=>F0,EMPTY_PATH:()=>sU,DIRTY:()=>q8,BRAND:()=>AL});var x0;(function(Q){Q.assertEqual=(B)=>{};function Y(B){}Q.assertIs=Y;function J(B){throw Error()}Q.assertNever=J,Q.arrayToEnum=(B)=>{let q={};for(let G of B)q[G]=G;return q},Q.getValidEnumValues=(B)=>{let q=Q.objectKeys(B).filter((H)=>typeof B[B[H]]!=="number"),G={};for(let H of q)G[H]=B[H];return Q.objectValues(G)},Q.objectValues=(B)=>{return Q.objectKeys(B).map(function(q){return B[q]})},Q.objectKeys=typeof Object.keys==="function"?(B)=>Object.keys(B):(B)=>{let q=[];for(let G in B)if(Object.prototype.hasOwnProperty.call(B,G))q.push(G);return q},Q.find=(B,q)=>{for(let G of B)if(q(G))return G;return},Q.isInteger=typeof Number.isInteger==="function"?(B)=>Number.isInteger(B):(B)=>typeof B==="number"&&Number.isFinite(B)&&Math.floor(B)===B;function X(B,q=" | "){return B.map((G)=>typeof G==="string"?`'${G}'`:G).join(q)}Q.joinValues=X,Q.jsonStringifyReplacer=(B,q)=>{if(typeof q==="bigint")return q.toString();return q}})(x0||(x0={}));var yX;(function(Q){Q.mergeShapes=(Y,J)=>{return{...Y,...J}}})(yX||(yX={}));var q0=x0.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),N9=(Q)=>{switch(typeof Q){case"undefined":return q0.undefined;case"string":return q0.string;case"number":return Number.isNaN(Q)?q0.nan:q0.number;case"boolean":return q0.boolean;case"function":return q0.function;case"bigint":return q0.bigint;case"symbol":return q0.symbol;case"object":if(Array.isArray(Q))return q0.array;if(Q===null)return q0.null;if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return q0.promise;if(typeof Map<"u"&&Q instanceof Map)return q0.map;if(typeof Set<"u"&&Q instanceof Set)return q0.set;if(typeof Date<"u"&&Q instanceof Date)return q0.date;return q0.object;default:return q0.unknown}},o=x0.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),nU=(Q)=>{return JSON.stringify(Q,null,2).replace(/"([^"]+)":/g,"$1:")};class S1 extends Error{get errors(){return this.issues}constructor(Q){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let Y=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,Y);else this.__proto__=Y;this.name="ZodError",this.issues=Q}format(Q){let Y=Q||function(B){return B.message},J={_errors:[]},X=(B)=>{for(let q of B.issues)if(q.code==="invalid_union")q.unionErrors.map(X);else if(q.code==="invalid_return_type")X(q.returnTypeError);else if(q.code==="invalid_arguments")X(q.argumentsError);else if(q.path.length===0)J._errors.push(Y(q));else{let G=J,H=0;while(H<q.path.length){let U=q.path[H];if(H!==q.path.length-1)G[U]=G[U]||{_errors:[]};else G[U]=G[U]||{_errors:[]},G[U]._errors.push(Y(q));G=G[U],H++}}};return X(this),J}static assert(Q){if(!(Q instanceof S1))throw Error(`Not a ZodError: ${Q}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x0.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(Q=(Y)=>Y.message){let Y={},J=[];for(let X of this.issues)if(X.path.length>0){let B=X.path[0];Y[B]=Y[B]||[],Y[B].push(Q(X))}else J.push(Q(X));return{formErrors:J,fieldErrors:Y}}get formErrors(){return this.flatten()}}S1.create=(Q)=>{return new S1(Q)};var iU=(Q,Y)=>{let J;switch(Q.code){case o.invalid_type:if(Q.received===q0.undefined)J="Required";else J=`Expected ${Q.expected}, received ${Q.received}`;break;case o.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify(Q.expected,x0.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:J=`Unrecognized key(s) in object: ${x0.joinValues(Q.keys,", ")}`;break;case o.invalid_union:J="Invalid input";break;case o.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${x0.joinValues(Q.options)}`;break;case o.invalid_enum_value:J=`Invalid enum value. Expected ${x0.joinValues(Q.options)}, received '${Q.received}'`;break;case o.invalid_arguments:J="Invalid function arguments";break;case o.invalid_return_type:J="Invalid function return type";break;case o.invalid_date:J="Invalid date";break;case o.invalid_string:if(typeof Q.validation==="object")if("includes"in Q.validation){if(J=`Invalid input: must include "${Q.validation.includes}"`,typeof Q.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${Q.validation.position}`}else if("startsWith"in Q.validation)J=`Invalid input: must start with "${Q.validation.startsWith}"`;else if("endsWith"in Q.validation)J=`Invalid input: must end with "${Q.validation.endsWith}"`;else x0.assertNever(Q.validation);else if(Q.validation!=="regex")J=`Invalid ${Q.validation}`;else J="Invalid";break;case o.too_small:if(Q.type==="array")J=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at least":"more than"} ${Q.minimum} element(s)`;else if(Q.type==="string")J=`String must contain ${Q.exact?"exactly":Q.inclusive?"at least":"over"} ${Q.minimum} character(s)`;else if(Q.type==="number")J=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="bigint")J=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="date")J=`Date must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Q.minimum))}`;else J="Invalid input";break;case o.too_big:if(Q.type==="array")J=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at most":"less than"} ${Q.maximum} element(s)`;else if(Q.type==="string")J=`String must contain ${Q.exact?"exactly":Q.inclusive?"at most":"under"} ${Q.maximum} character(s)`;else if(Q.type==="number")J=`Number must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="bigint")J=`BigInt must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="date")J=`Date must be ${Q.exact?"exactly":Q.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Q.maximum))}`;else J="Invalid input";break;case o.custom:J="Invalid input";break;case o.invalid_intersection_types:J="Intersection results could not be merged";break;case o.not_multiple_of:J=`Number must be a multiple of ${Q.multipleOf}`;break;case o.not_finite:J="Number must be finite";break;default:J=Y.defaultError,x0.assertNever(Q)}return{message:J}},z8=iU,_5=z8;function aU(Q){_5=Q}function fQ(){return _5}var hQ=(Q)=>{let{data:Y,path:J,errorMaps:X,issueData:B}=Q,q=[...J,...B.path||[]],G={...B,path:q};if(B.message!==void 0)return{...B,path:q,message:B.message};let H="",U=X.filter((z)=>!!z).slice().reverse();for(let z of U)H=z(G,{data:Y,defaultError:H}).message;return{...B,path:q,message:H}},sU=[];function G0(Q,Y){let J=fQ(),X=hQ({issueData:Y,data:Q.data,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,J,J===z8?void 0:z8].filter((B)=>!!B)});Q.common.issues.push(X)}class N1{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(Q,Y){let J=[];for(let X of Y){if(X.status==="aborted")return F0;if(X.status==="dirty")Q.dirty();J.push(X.value)}return{status:Q.value,value:J}}static async mergeObjectAsync(Q,Y){let J=[];for(let X of Y){let B=await X.key,q=await X.value;J.push({key:B,value:q})}return N1.mergeObjectSync(Q,J)}static mergeObjectSync(Q,Y){let J={};for(let X of Y){let{key:B,value:q}=X;if(B.status==="aborted")return F0;if(q.status==="aborted")return F0;if(B.status==="dirty")Q.dirty();if(q.status==="dirty")Q.dirty();if(B.value!=="__proto__"&&(typeof q.value<"u"||X.alwaysSet))J[B.value]=q.value}return{status:Q.value,value:J}}}var F0=Object.freeze({status:"aborted"}),q8=(Q)=>({status:"dirty",value:Q}),A1=(Q)=>({status:"valid",value:Q}),$X=(Q)=>Q.status==="aborted",fX=(Q)=>Q.status==="dirty",y9=(Q)=>Q.status==="valid",e8=(Q)=>typeof Promise<"u"&&Q instanceof Promise,L0;(function(Q){Q.errToObj=(Y)=>typeof Y==="string"?{message:Y}:Y||{},Q.toString=(Y)=>typeof Y==="string"?Y:Y?.message})(L0||(L0={}));class u1{constructor(Q,Y,J,X){this._cachedPath=[],this.parent=Q,this.data=Y,this._path=J,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var L5=(Q,Y)=>{if(y9(Y))return{success:!0,data:Y.value};else{if(!Q.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new S1(Q.common.issues);return this._error=J,this._error}}}};function O0(Q){if(!Q)return{};let{errorMap:Y,invalid_type_error:J,required_error:X,description:B}=Q;if(Y&&(J||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Y)return{errorMap:Y,description:B};return{errorMap:(G,H)=>{let{message:U}=Q;if(G.code==="invalid_enum_value")return{message:U??H.defaultError};if(typeof H.data>"u")return{message:U??X??H.defaultError};if(G.code!=="invalid_type")return{message:H.defaultError};return{message:U??J??H.defaultError}},description:B}}class R0{get description(){return this._def.description}_getType(Q){return N9(Q.data)}_getOrReturnCtx(Q,Y){return Y||{common:Q.parent.common,data:Q.data,parsedType:N9(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}_processInputParams(Q){return{status:new N1,ctx:{common:Q.parent.common,data:Q.data,parsedType:N9(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}}_parseSync(Q){let Y=this._parse(Q);if(e8(Y))throw Error("Synchronous parse encountered promise.");return Y}_parseAsync(Q){let Y=this._parse(Q);return Promise.resolve(Y)}parse(Q,Y){let J=this.safeParse(Q,Y);if(J.success)return J.data;throw J.error}safeParse(Q,Y){let J={common:{issues:[],async:Y?.async??!1,contextualErrorMap:Y?.errorMap},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:N9(Q)},X=this._parseSync({data:Q,path:J.path,parent:J});return L5(J,X)}"~validate"(Q){let Y={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:N9(Q)};if(!this["~standard"].async)try{let J=this._parseSync({data:Q,path:[],parent:Y});return y9(J)?{value:J.value}:{issues:Y.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;Y.common={issues:[],async:!0}}return this._parseAsync({data:Q,path:[],parent:Y}).then((J)=>y9(J)?{value:J.value}:{issues:Y.common.issues})}async parseAsync(Q,Y){let J=await this.safeParseAsync(Q,Y);if(J.success)return J.data;throw J.error}async safeParseAsync(Q,Y){let J={common:{issues:[],contextualErrorMap:Y?.errorMap,async:!0},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:N9(Q)},X=this._parse({data:Q,path:J.path,parent:J}),B=await(e8(X)?X:Promise.resolve(X));return L5(J,B)}refine(Q,Y){let J=(X)=>{if(typeof Y==="string"||typeof Y>"u")return{message:Y};else if(typeof Y==="function")return Y(X);else return Y};return this._refinement((X,B)=>{let q=Q(X),G=()=>B.addIssue({code:o.custom,...J(X)});if(typeof Promise<"u"&&q instanceof Promise)return q.then((H)=>{if(!H)return G(),!1;else return!0});if(!q)return G(),!1;else return!0})}refinement(Q,Y){return this._refinement((J,X)=>{if(!Q(J))return X.addIssue(typeof Y==="function"?Y(J,X):Y),!1;else return!0})}_refinement(Q){return new T1({schema:this,typeName:j0.ZodEffects,effect:{type:"refinement",refinement:Q}})}superRefine(Q){return this._refinement(Q)}constructor(Q){this.spa=this.safeParseAsync,this._def=Q,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(Y)=>this["~validate"](Y)}}optional(){return m1.create(this,this._def)}nullable(){return K9.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return h1.create(this)}promise(){return m9.create(this,this._def)}or(Q){return N8.create([this,Q],this._def)}and(Q){return j8.create(this,Q,this._def)}transform(Q){return new T1({...O0(this._def),schema:this,typeName:j0.ZodEffects,effect:{type:"transform",transform:Q}})}default(Q){let Y=typeof Q==="function"?Q:()=>Q;return new V8({...O0(this._def),innerType:this,defaultValue:Y,typeName:j0.ZodDefault})}brand(){return new dQ({typeName:j0.ZodBranded,type:this,...O0(this._def)})}catch(Q){let Y=typeof Q==="function"?Q:()=>Q;return new D8({...O0(this._def),innerType:this,catchValue:Y,typeName:j0.ZodCatch})}describe(Q){return new this.constructor({...this._def,description:Q})}pipe(Q){return BQ.create(this,Q)}readonly(){return w8.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var oU=/^c[^\s-]{8,}$/i,rU=/^[0-9a-z]+$/,tU=/^[0-9A-HJKMNP-TV-Z]{26}$/i,eU=/^[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}$/i,QL=/^[a-z0-9_-]{21}$/i,XL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,YL=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,JL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,WL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vX,GL=/^(?:(?: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])$/,BL=/^(?:(?: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])$/,qL=/^(([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]))$/,HL=/^(([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])$/,zL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,UL=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,k5="((\\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])))",LL=new RegExp(`^${k5}$`);function v5(Q){let Y="[0-5]\\d";if(Q.precision)Y=`${Y}\\.\\d{${Q.precision}}`;else if(Q.precision==null)Y=`${Y}(\\.\\d+)?`;let J=Q.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${Y})${J}`}function FL(Q){return new RegExp(`^${v5(Q)}$`)}function x5(Q){let Y=`${k5}T${v5(Q)}`,J=[];if(J.push(Q.local?"Z?":"Z"),Q.offset)J.push("([+-]\\d{2}:?\\d{2})");return Y=`${Y}(${J.join("|")})`,new RegExp(`^${Y}$`)}function NL(Q,Y){if((Y==="v4"||!Y)&&GL.test(Q))return!0;if((Y==="v6"||!Y)&&qL.test(Q))return!0;return!1}function jL(Q,Y){if(!XL.test(Q))return!1;try{let[J]=Q.split(".");if(!J)return!1;let X=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),B=JSON.parse(atob(X));if(typeof B!=="object"||B===null)return!1;if("typ"in B&&B?.typ!=="JWT")return!1;if(!B.alg)return!1;if(Y&&B.alg!==Y)return!1;return!0}catch{return!1}}function KL(Q,Y){if((Y==="v4"||!Y)&&BL.test(Q))return!0;if((Y==="v6"||!Y)&&HL.test(Q))return!0;return!1}class f1 extends R0{_parse(Q){if(this._def.coerce)Q.data=String(Q.data);if(this._getType(Q)!==q0.string){let B=this._getOrReturnCtx(Q);return G0(B,{code:o.invalid_type,expected:q0.string,received:B.parsedType}),F0}let J=new N1,X=void 0;for(let B of this._def.checks)if(B.kind==="min"){if(Q.data.length<B.value)X=this._getOrReturnCtx(Q,X),G0(X,{code:o.too_small,minimum:B.value,type:"string",inclusive:!0,exact:!1,message:B.message}),J.dirty()}else if(B.kind==="max"){if(Q.data.length>B.value)X=this._getOrReturnCtx(Q,X),G0(X,{code:o.too_big,maximum:B.value,type:"string",inclusive:!0,exact:!1,message:B.message}),J.dirty()}else if(B.kind==="length"){let q=Q.data.length>B.value,G=Q.data.length<B.value;if(q||G){if(X=this._getOrReturnCtx(Q,X),q)G0(X,{code:o.too_big,maximum:B.value,type:"string",inclusive:!0,exact:!0,message:B.message});else if(G)G0(X,{code:o.too_small,minimum:B.value,type:"string",inclusive:!0,exact:!0,message:B.message});J.dirty()}}else if(B.kind==="email"){if(!JL.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"email",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="emoji"){if(!vX)vX=new RegExp(WL,"u");if(!vX.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"emoji",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="uuid"){if(!eU.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"uuid",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="nanoid"){if(!QL.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"nanoid",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="cuid"){if(!oU.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"cuid",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="cuid2"){if(!rU.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"cuid2",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="ulid"){if(!tU.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"ulid",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="url")try{new URL(Q.data)}catch{X=this._getOrReturnCtx(Q,X),G0(X,{validation:"url",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="regex"){if(B.regex.lastIndex=0,!B.regex.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"regex",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="trim")Q.data=Q.data.trim();else if(B.kind==="includes"){if(!Q.data.includes(B.value,B.position))X=this._getOrReturnCtx(Q,X),G0(X,{code:o.invalid_string,validation:{includes:B.value,position:B.position},message:B.message}),J.dirty()}else if(B.kind==="toLowerCase")Q.data=Q.data.toLowerCase();else if(B.kind==="toUpperCase")Q.data=Q.data.toUpperCase();else if(B.kind==="startsWith"){if(!Q.data.startsWith(B.value))X=this._getOrReturnCtx(Q,X),G0(X,{code:o.invalid_string,validation:{startsWith:B.value},message:B.message}),J.dirty()}else if(B.kind==="endsWith"){if(!Q.data.endsWith(B.value))X=this._getOrReturnCtx(Q,X),G0(X,{code:o.invalid_string,validation:{endsWith:B.value},message:B.message}),J.dirty()}else if(B.kind==="datetime"){if(!x5(B).test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{code:o.invalid_string,validation:"datetime",message:B.message}),J.dirty()}else if(B.kind==="date"){if(!LL.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{code:o.invalid_string,validation:"date",message:B.message}),J.dirty()}else if(B.kind==="time"){if(!FL(B).test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{code:o.invalid_string,validation:"time",message:B.message}),J.dirty()}else if(B.kind==="duration"){if(!YL.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"duration",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="ip"){if(!NL(Q.data,B.version))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"ip",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="jwt"){if(!jL(Q.data,B.alg))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"jwt",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="cidr"){if(!KL(Q.data,B.version))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"cidr",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="base64"){if(!zL.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"base64",code:o.invalid_string,message:B.message}),J.dirty()}else if(B.kind==="base64url"){if(!UL.test(Q.data))X=this._getOrReturnCtx(Q,X),G0(X,{validation:"base64url",code:o.invalid_string,message:B.message}),J.dirty()}else x0.assertNever(B);return{status:J.value,value:Q.data}}_regex(Q,Y,J){return this.refinement((X)=>Q.test(X),{validation:Y,code:o.invalid_string,...L0.errToObj(J)})}_addCheck(Q){return new f1({...this._def,checks:[...this._def.checks,Q]})}email(Q){return this._addCheck({kind:"email",...L0.errToObj(Q)})}url(Q){return this._addCheck({kind:"url",...L0.errToObj(Q)})}emoji(Q){return this._addCheck({kind:"emoji",...L0.errToObj(Q)})}uuid(Q){return this._addCheck({kind:"uuid",...L0.errToObj(Q)})}nanoid(Q){return this._addCheck({kind:"nanoid",...L0.errToObj(Q)})}cuid(Q){return this._addCheck({kind:"cuid",...L0.errToObj(Q)})}cuid2(Q){return this._addCheck({kind:"cuid2",...L0.errToObj(Q)})}ulid(Q){return this._addCheck({kind:"ulid",...L0.errToObj(Q)})}base64(Q){return this._addCheck({kind:"base64",...L0.errToObj(Q)})}base64url(Q){return this._addCheck({kind:"base64url",...L0.errToObj(Q)})}jwt(Q){return this._addCheck({kind:"jwt",...L0.errToObj(Q)})}ip(Q){return this._addCheck({kind:"ip",...L0.errToObj(Q)})}cidr(Q){return this._addCheck({kind:"cidr",...L0.errToObj(Q)})}datetime(Q){if(typeof Q==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:Q});return this._addCheck({kind:"datetime",precision:typeof Q?.precision>"u"?null:Q?.precision,offset:Q?.offset??!1,local:Q?.local??!1,...L0.errToObj(Q?.message)})}date(Q){return this._addCheck({kind:"date",message:Q})}time(Q){if(typeof Q==="string")return this._addCheck({kind:"time",precision:null,message:Q});return this._addCheck({kind:"time",precision:typeof Q?.precision>"u"?null:Q?.precision,...L0.errToObj(Q?.message)})}duration(Q){return this._addCheck({kind:"duration",...L0.errToObj(Q)})}regex(Q,Y){return this._addCheck({kind:"regex",regex:Q,...L0.errToObj(Y)})}includes(Q,Y){return this._addCheck({kind:"includes",value:Q,position:Y?.position,...L0.errToObj(Y?.message)})}startsWith(Q,Y){return this._addCheck({kind:"startsWith",value:Q,...L0.errToObj(Y)})}endsWith(Q,Y){return this._addCheck({kind:"endsWith",value:Q,...L0.errToObj(Y)})}min(Q,Y){return this._addCheck({kind:"min",value:Q,...L0.errToObj(Y)})}max(Q,Y){return this._addCheck({kind:"max",value:Q,...L0.errToObj(Y)})}length(Q,Y){return this._addCheck({kind:"length",value:Q,...L0.errToObj(Y)})}nonempty(Q){return this.min(1,L0.errToObj(Q))}trim(){return new f1({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new f1({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new f1({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((Q)=>Q.kind==="datetime")}get isDate(){return!!this._def.checks.find((Q)=>Q.kind==="date")}get isTime(){return!!this._def.checks.find((Q)=>Q.kind==="time")}get isDuration(){return!!this._def.checks.find((Q)=>Q.kind==="duration")}get isEmail(){return!!this._def.checks.find((Q)=>Q.kind==="email")}get isURL(){return!!this._def.checks.find((Q)=>Q.kind==="url")}get isEmoji(){return!!this._def.checks.find((Q)=>Q.kind==="emoji")}get isUUID(){return!!this._def.checks.find((Q)=>Q.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((Q)=>Q.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((Q)=>Q.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((Q)=>Q.kind==="cuid2")}get isULID(){return!!this._def.checks.find((Q)=>Q.kind==="ulid")}get isIP(){return!!this._def.checks.find((Q)=>Q.kind==="ip")}get isCIDR(){return!!this._def.checks.find((Q)=>Q.kind==="cidr")}get isBase64(){return!!this._def.checks.find((Q)=>Q.kind==="base64")}get isBase64url(){return!!this._def.checks.find((Q)=>Q.kind==="base64url")}get minLength(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxLength(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q}}f1.create=(Q)=>{return new f1({checks:[],typeName:j0.ZodString,coerce:Q?.coerce??!1,...O0(Q)})};function ML(Q,Y){let J=(Q.toString().split(".")[1]||"").length,X=(Y.toString().split(".")[1]||"").length,B=J>X?J:X,q=Number.parseInt(Q.toFixed(B).replace(".","")),G=Number.parseInt(Y.toFixed(B).replace(".",""));return q%G/10**B}class P9 extends R0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(Q){if(this._def.coerce)Q.data=Number(Q.data);if(this._getType(Q)!==q0.number){let B=this._getOrReturnCtx(Q);return G0(B,{code:o.invalid_type,expected:q0.number,received:B.parsedType}),F0}let J=void 0,X=new N1;for(let B of this._def.checks)if(B.kind==="int"){if(!x0.isInteger(Q.data))J=this._getOrReturnCtx(Q,J),G0(J,{code:o.invalid_type,expected:"integer",received:"float",message:B.message}),X.dirty()}else if(B.kind==="min"){if(B.inclusive?Q.data<B.value:Q.data<=B.value)J=this._getOrReturnCtx(Q,J),G0(J,{code:o.too_small,minimum:B.value,type:"number",inclusive:B.inclusive,exact:!1,message:B.message}),X.dirty()}else if(B.kind==="max"){if(B.inclusive?Q.data>B.value:Q.data>=B.value)J=this._getOrReturnCtx(Q,J),G0(J,{code:o.too_big,maximum:B.value,type:"number",inclusive:B.inclusive,exact:!1,message:B.message}),X.dirty()}else if(B.kind==="multipleOf"){if(ML(Q.data,B.value)!==0)J=this._getOrReturnCtx(Q,J),G0(J,{code:o.not_multiple_of,multipleOf:B.value,message:B.message}),X.dirty()}else if(B.kind==="finite"){if(!Number.isFinite(Q.data))J=this._getOrReturnCtx(Q,J),G0(J,{code:o.not_finite,message:B.message}),X.dirty()}else x0.assertNever(B);return{status:X.value,value:Q.data}}gte(Q,Y){return this.setLimit("min",Q,!0,L0.toString(Y))}gt(Q,Y){return this.setLimit("min",Q,!1,L0.toString(Y))}lte(Q,Y){return this.setLimit("max",Q,!0,L0.toString(Y))}lt(Q,Y){return this.setLimit("max",Q,!1,L0.toString(Y))}setLimit(Q,Y,J,X){return new P9({...this._def,checks:[...this._def.checks,{kind:Q,value:Y,inclusive:J,message:L0.toString(X)}]})}_addCheck(Q){return new P9({...this._def,checks:[...this._def.checks,Q]})}int(Q){return this._addCheck({kind:"int",message:L0.toString(Q)})}positive(Q){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L0.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L0.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L0.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L0.toString(Q)})}multipleOf(Q,Y){return this._addCheck({kind:"multipleOf",value:Q,message:L0.toString(Y)})}finite(Q){return this._addCheck({kind:"finite",message:L0.toString(Q)})}safe(Q){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L0.toString(Q)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L0.toString(Q)})}get minValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q}get isInt(){return!!this._def.checks.find((Q)=>Q.kind==="int"||Q.kind==="multipleOf"&&x0.isInteger(Q.value))}get isFinite(){let Q=null,Y=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(Y===null||J.value>Y)Y=J.value}else if(J.kind==="max"){if(Q===null||J.value<Q)Q=J.value}return Number.isFinite(Y)&&Number.isFinite(Q)}}P9.create=(Q)=>{return new P9({checks:[],typeName:j0.ZodNumber,coerce:Q?.coerce||!1,...O0(Q)})};class S9 extends R0{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(Q){if(this._def.coerce)try{Q.data=BigInt(Q.data)}catch{return this._getInvalidInput(Q)}if(this._getType(Q)!==q0.bigint)return this._getInvalidInput(Q);let J=void 0,X=new N1;for(let B of this._def.checks)if(B.kind==="min"){if(B.inclusive?Q.data<B.value:Q.data<=B.value)J=this._getOrReturnCtx(Q,J),G0(J,{code:o.too_small,type:"bigint",minimum:B.value,inclusive:B.inclusive,message:B.message}),X.dirty()}else if(B.kind==="max"){if(B.inclusive?Q.data>B.value:Q.data>=B.value)J=this._getOrReturnCtx(Q,J),G0(J,{code:o.too_big,type:"bigint",maximum:B.value,inclusive:B.inclusive,message:B.message}),X.dirty()}else if(B.kind==="multipleOf"){if(Q.data%B.value!==BigInt(0))J=this._getOrReturnCtx(Q,J),G0(J,{code:o.not_multiple_of,multipleOf:B.value,message:B.message}),X.dirty()}else x0.assertNever(B);return{status:X.value,value:Q.data}}_getInvalidInput(Q){let Y=this._getOrReturnCtx(Q);return G0(Y,{code:o.invalid_type,expected:q0.bigint,received:Y.parsedType}),F0}gte(Q,Y){return this.setLimit("min",Q,!0,L0.toString(Y))}gt(Q,Y){return this.setLimit("min",Q,!1,L0.toString(Y))}lte(Q,Y){return this.setLimit("max",Q,!0,L0.toString(Y))}lt(Q,Y){return this.setLimit("max",Q,!1,L0.toString(Y))}setLimit(Q,Y,J,X){return new S9({...this._def,checks:[...this._def.checks,{kind:Q,value:Y,inclusive:J,message:L0.toString(X)}]})}_addCheck(Q){return new S9({...this._def,checks:[...this._def.checks,Q]})}positive(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L0.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L0.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L0.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L0.toString(Q)})}multipleOf(Q,Y){return this._addCheck({kind:"multipleOf",value:Q,message:L0.toString(Y)})}get minValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q}get maxValue(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q}}S9.create=(Q)=>{return new S9({checks:[],typeName:j0.ZodBigInt,coerce:Q?.coerce??!1,...O0(Q)})};class U8 extends R0{_parse(Q){if(this._def.coerce)Q.data=Boolean(Q.data);if(this._getType(Q)!==q0.boolean){let J=this._getOrReturnCtx(Q);return G0(J,{code:o.invalid_type,expected:q0.boolean,received:J.parsedType}),F0}return A1(Q.data)}}U8.create=(Q)=>{return new U8({typeName:j0.ZodBoolean,coerce:Q?.coerce||!1,...O0(Q)})};class $9 extends R0{_parse(Q){if(this._def.coerce)Q.data=new Date(Q.data);if(this._getType(Q)!==q0.date){let B=this._getOrReturnCtx(Q);return G0(B,{code:o.invalid_type,expected:q0.date,received:B.parsedType}),F0}if(Number.isNaN(Q.data.getTime())){let B=this._getOrReturnCtx(Q);return G0(B,{code:o.invalid_date}),F0}let J=new N1,X=void 0;for(let B of this._def.checks)if(B.kind==="min"){if(Q.data.getTime()<B.value)X=this._getOrReturnCtx(Q,X),G0(X,{code:o.too_small,message:B.message,inclusive:!0,exact:!1,minimum:B.value,type:"date"}),J.dirty()}else if(B.kind==="max"){if(Q.data.getTime()>B.value)X=this._getOrReturnCtx(Q,X),G0(X,{code:o.too_big,message:B.message,inclusive:!0,exact:!1,maximum:B.value,type:"date"}),J.dirty()}else x0.assertNever(B);return{status:J.value,value:new Date(Q.data.getTime())}}_addCheck(Q){return new $9({...this._def,checks:[...this._def.checks,Q]})}min(Q,Y){return this._addCheck({kind:"min",value:Q.getTime(),message:L0.toString(Y)})}max(Q,Y){return this._addCheck({kind:"max",value:Q.getTime(),message:L0.toString(Y)})}get minDate(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}return Q!=null?new Date(Q):null}get maxDate(){let Q=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(Q===null||Y.value<Q)Q=Y.value}return Q!=null?new Date(Q):null}}$9.create=(Q)=>{return new $9({checks:[],coerce:Q?.coerce||!1,typeName:j0.ZodDate,...O0(Q)})};class QQ extends R0{_parse(Q){if(this._getType(Q)!==q0.symbol){let J=this._getOrReturnCtx(Q);return G0(J,{code:o.invalid_type,expected:q0.symbol,received:J.parsedType}),F0}return A1(Q.data)}}QQ.create=(Q)=>{return new QQ({typeName:j0.ZodSymbol,...O0(Q)})};class L8 extends R0{_parse(Q){if(this._getType(Q)!==q0.undefined){let J=this._getOrReturnCtx(Q);return G0(J,{code:o.invalid_type,expected:q0.undefined,received:J.parsedType}),F0}return A1(Q.data)}}L8.create=(Q)=>{return new L8({typeName:j0.ZodUndefined,...O0(Q)})};class F8 extends R0{_parse(Q){if(this._getType(Q)!==q0.null){let J=this._getOrReturnCtx(Q);return G0(J,{code:o.invalid_type,expected:q0.null,received:J.parsedType}),F0}return A1(Q.data)}}F8.create=(Q)=>{return new F8({typeName:j0.ZodNull,...O0(Q)})};class f9 extends R0{constructor(){super(...arguments);this._any=!0}_parse(Q){return A1(Q.data)}}f9.create=(Q)=>{return new f9({typeName:j0.ZodAny,...O0(Q)})};class E9 extends R0{constructor(){super(...arguments);this._unknown=!0}_parse(Q){return A1(Q.data)}}E9.create=(Q)=>{return new E9({typeName:j0.ZodUnknown,...O0(Q)})};class o1 extends R0{_parse(Q){let Y=this._getOrReturnCtx(Q);return G0(Y,{code:o.invalid_type,expected:q0.never,received:Y.parsedType}),F0}}o1.create=(Q)=>{return new o1({typeName:j0.ZodNever,...O0(Q)})};class XQ extends R0{_parse(Q){if(this._getType(Q)!==q0.undefined){let J=this._getOrReturnCtx(Q);return G0(J,{code:o.invalid_type,expected:q0.void,received:J.parsedType}),F0}return A1(Q.data)}}XQ.create=(Q)=>{return new XQ({typeName:j0.ZodVoid,...O0(Q)})};class h1 extends R0{_parse(Q){let{ctx:Y,status:J}=this._processInputParams(Q),X=this._def;if(Y.parsedType!==q0.array)return G0(Y,{code:o.invalid_type,expected:q0.array,received:Y.parsedType}),F0;if(X.exactLength!==null){let q=Y.data.length>X.exactLength.value,G=Y.data.length<X.exactLength.value;if(q||G)G0(Y,{code:q?o.too_big:o.too_small,minimum:G?X.exactLength.value:void 0,maximum:q?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),J.dirty()}if(X.minLength!==null){if(Y.data.length<X.minLength.value)G0(Y,{code:o.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),J.dirty()}if(X.maxLength!==null){if(Y.data.length>X.maxLength.value)G0(Y,{code:o.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),J.dirty()}if(Y.common.async)return Promise.all([...Y.data].map((q,G)=>{return X.type._parseAsync(new u1(Y,q,Y.path,G))})).then((q)=>{return N1.mergeArray(J,q)});let B=[...Y.data].map((q,G)=>{return X.type._parseSync(new u1(Y,q,Y.path,G))});return N1.mergeArray(J,B)}get element(){return this._def.type}min(Q,Y){return new h1({...this._def,minLength:{value:Q,message:L0.toString(Y)}})}max(Q,Y){return new h1({...this._def,maxLength:{value:Q,message:L0.toString(Y)}})}length(Q,Y){return new h1({...this._def,exactLength:{value:Q,message:L0.toString(Y)}})}nonempty(Q){return this.min(1,Q)}}h1.create=(Q,Y)=>{return new h1({type:Q,minLength:null,maxLength:null,exactLength:null,typeName:j0.ZodArray,...O0(Y)})};function G8(Q){if(Q instanceof t0){let Y={};for(let J in Q.shape){let X=Q.shape[J];Y[J]=m1.create(G8(X))}return new t0({...Q._def,shape:()=>Y})}else if(Q instanceof h1)return new h1({...Q._def,type:G8(Q.element)});else if(Q instanceof m1)return m1.create(G8(Q.unwrap()));else if(Q instanceof K9)return K9.create(G8(Q.unwrap()));else if(Q instanceof r1)return r1.create(Q.items.map((Y)=>G8(Y)));else return Q}class t0 extends R0{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let Q=this._def.shape(),Y=x0.objectKeys(Q);return this._cached={shape:Q,keys:Y},this._cached}_parse(Q){if(this._getType(Q)!==q0.object){let U=this._getOrReturnCtx(Q);return G0(U,{code:o.invalid_type,expected:q0.object,received:U.parsedType}),F0}let{status:J,ctx:X}=this._processInputParams(Q),{shape:B,keys:q}=this._getCached(),G=[];if(!(this._def.catchall instanceof o1&&this._def.unknownKeys==="strip")){for(let U in X.data)if(!q.includes(U))G.push(U)}let H=[];for(let U of q){let z=B[U],j=X.data[U];H.push({key:{status:"valid",value:U},value:z._parse(new u1(X,j,X.path,U)),alwaysSet:U in X.data})}if(this._def.catchall instanceof o1){let U=this._def.unknownKeys;if(U==="passthrough")for(let z of G)H.push({key:{status:"valid",value:z},value:{status:"valid",value:X.data[z]}});else if(U==="strict"){if(G.length>0)G0(X,{code:o.unrecognized_keys,keys:G}),J.dirty()}else if(U==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let U=this._def.catchall;for(let z of G){let j=X.data[z];H.push({key:{status:"valid",value:z},value:U._parse(new u1(X,j,X.path,z)),alwaysSet:z in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let U=[];for(let z of H){let j=await z.key,A=await z.value;U.push({key:j,value:A,alwaysSet:z.alwaysSet})}return U}).then((U)=>{return N1.mergeObjectSync(J,U)});else return N1.mergeObjectSync(J,H)}get shape(){return this._def.shape()}strict(Q){return L0.errToObj,new t0({...this._def,unknownKeys:"strict",...Q!==void 0?{errorMap:(Y,J)=>{let X=this._def.errorMap?.(Y,J).message??J.defaultError;if(Y.code==="unrecognized_keys")return{message:L0.errToObj(Q).message??X};return{message:X}}}:{}})}strip(){return new t0({...this._def,unknownKeys:"strip"})}passthrough(){return new t0({...this._def,unknownKeys:"passthrough"})}extend(Q){return new t0({...this._def,shape:()=>({...this._def.shape(),...Q})})}merge(Q){return new t0({unknownKeys:Q._def.unknownKeys,catchall:Q._def.catchall,shape:()=>({...this._def.shape(),...Q._def.shape()}),typeName:j0.ZodObject})}setKey(Q,Y){return this.augment({[Q]:Y})}catchall(Q){return new t0({...this._def,catchall:Q})}pick(Q){let Y={};for(let J of x0.objectKeys(Q))if(Q[J]&&this.shape[J])Y[J]=this.shape[J];return new t0({...this._def,shape:()=>Y})}omit(Q){let Y={};for(let J of x0.objectKeys(this.shape))if(!Q[J])Y[J]=this.shape[J];return new t0({...this._def,shape:()=>Y})}deepPartial(){return G8(this)}partial(Q){let Y={};for(let J of x0.objectKeys(this.shape)){let X=this.shape[J];if(Q&&!Q[J])Y[J]=X;else Y[J]=X.optional()}return new t0({...this._def,shape:()=>Y})}required(Q){let Y={};for(let J of x0.objectKeys(this.shape))if(Q&&!Q[J])Y[J]=this.shape[J];else{let B=this.shape[J];while(B instanceof m1)B=B._def.innerType;Y[J]=B}return new t0({...this._def,shape:()=>Y})}keyof(){return g5(x0.objectKeys(this.shape))}}t0.create=(Q,Y)=>{return new t0({shape:()=>Q,unknownKeys:"strip",catchall:o1.create(),typeName:j0.ZodObject,...O0(Y)})};t0.strictCreate=(Q,Y)=>{return new t0({shape:()=>Q,unknownKeys:"strict",catchall:o1.create(),typeName:j0.ZodObject,...O0(Y)})};t0.lazycreate=(Q,Y)=>{return new t0({shape:Q,unknownKeys:"strip",catchall:o1.create(),typeName:j0.ZodObject,...O0(Y)})};class N8 extends R0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=this._def.options;function X(B){for(let G of B)if(G.result.status==="valid")return G.result;for(let G of B)if(G.result.status==="dirty")return Y.common.issues.push(...G.ctx.common.issues),G.result;let q=B.map((G)=>new S1(G.ctx.common.issues));return G0(Y,{code:o.invalid_union,unionErrors:q}),F0}if(Y.common.async)return Promise.all(J.map(async(B)=>{let q={...Y,common:{...Y.common,issues:[]},parent:null};return{result:await B._parseAsync({data:Y.data,path:Y.path,parent:q}),ctx:q}})).then(X);else{let B=void 0,q=[];for(let H of J){let U={...Y,common:{...Y.common,issues:[]},parent:null},z=H._parseSync({data:Y.data,path:Y.path,parent:U});if(z.status==="valid")return z;else if(z.status==="dirty"&&!B)B={result:z,ctx:U};if(U.common.issues.length)q.push(U.common.issues)}if(B)return Y.common.issues.push(...B.ctx.common.issues),B.result;let G=q.map((H)=>new S1(H));return G0(Y,{code:o.invalid_union,unionErrors:G}),F0}}get options(){return this._def.options}}N8.create=(Q,Y)=>{return new N8({options:Q,typeName:j0.ZodUnion,...O0(Y)})};var F9=(Q)=>{if(Q instanceof K8)return F9(Q.schema);else if(Q instanceof T1)return F9(Q.innerType());else if(Q instanceof M8)return[Q.value];else if(Q instanceof I9)return Q.options;else if(Q instanceof A8)return x0.objectValues(Q.enum);else if(Q instanceof V8)return F9(Q._def.innerType);else if(Q instanceof L8)return[void 0];else if(Q instanceof F8)return[null];else if(Q instanceof m1)return[void 0,...F9(Q.unwrap())];else if(Q instanceof K9)return[null,...F9(Q.unwrap())];else if(Q instanceof dQ)return F9(Q.unwrap());else if(Q instanceof w8)return F9(Q.unwrap());else if(Q instanceof D8)return F9(Q._def.innerType);else return[]};class cQ extends R0{_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==q0.object)return G0(Y,{code:o.invalid_type,expected:q0.object,received:Y.parsedType}),F0;let J=this.discriminator,X=Y.data[J],B=this.optionsMap.get(X);if(!B)return G0(Y,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),F0;if(Y.common.async)return B._parseAsync({data:Y.data,path:Y.path,parent:Y});else return B._parseSync({data:Y.data,path:Y.path,parent:Y})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(Q,Y,J){let X=new Map;for(let B of Y){let q=F9(B.shape[Q]);if(!q.length)throw Error(`A discriminator value for key \`${Q}\` could not be extracted from all schema options`);for(let G of q){if(X.has(G))throw Error(`Discriminator property ${String(Q)} has duplicate value ${String(G)}`);X.set(G,B)}}return new cQ({typeName:j0.ZodDiscriminatedUnion,discriminator:Q,options:Y,optionsMap:X,...O0(J)})}}function hX(Q,Y){let J=N9(Q),X=N9(Y);if(Q===Y)return{valid:!0,data:Q};else if(J===q0.object&&X===q0.object){let B=x0.objectKeys(Y),q=x0.objectKeys(Q).filter((H)=>B.indexOf(H)!==-1),G={...Q,...Y};for(let H of q){let U=hX(Q[H],Y[H]);if(!U.valid)return{valid:!1};G[H]=U.data}return{valid:!0,data:G}}else if(J===q0.array&&X===q0.array){if(Q.length!==Y.length)return{valid:!1};let B=[];for(let q=0;q<Q.length;q++){let G=Q[q],H=Y[q],U=hX(G,H);if(!U.valid)return{valid:!1};B.push(U.data)}return{valid:!0,data:B}}else if(J===q0.date&&X===q0.date&&+Q===+Y)return{valid:!0,data:Q};else return{valid:!1}}class j8 extends R0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q),X=(B,q)=>{if($X(B)||$X(q))return F0;let G=hX(B.value,q.value);if(!G.valid)return G0(J,{code:o.invalid_intersection_types}),F0;if(fX(B)||fX(q))Y.dirty();return{status:Y.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([B,q])=>X(B,q));else return X(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}j8.create=(Q,Y,J)=>{return new j8({left:Q,right:Y,typeName:j0.ZodIntersection,...O0(J)})};class r1 extends R0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==q0.array)return G0(J,{code:o.invalid_type,expected:q0.array,received:J.parsedType}),F0;if(J.data.length<this._def.items.length)return G0(J,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F0;if(!this._def.rest&&J.data.length>this._def.items.length)G0(J,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y.dirty();let B=[...J.data].map((q,G)=>{let H=this._def.items[G]||this._def.rest;if(!H)return null;return H._parse(new u1(J,q,J.path,G))}).filter((q)=>!!q);if(J.common.async)return Promise.all(B).then((q)=>{return N1.mergeArray(Y,q)});else return N1.mergeArray(Y,B)}get items(){return this._def.items}rest(Q){return new r1({...this._def,rest:Q})}}r1.create=(Q,Y)=>{if(!Array.isArray(Q))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new r1({items:Q,typeName:j0.ZodTuple,rest:null,...O0(Y)})};class YQ extends R0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==q0.object)return G0(J,{code:o.invalid_type,expected:q0.object,received:J.parsedType}),F0;let X=[],B=this._def.keyType,q=this._def.valueType;for(let G in J.data)X.push({key:B._parse(new u1(J,G,J.path,G)),value:q._parse(new u1(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return N1.mergeObjectAsync(Y,X);else return N1.mergeObjectSync(Y,X)}get element(){return this._def.valueType}static create(Q,Y,J){if(Y instanceof R0)return new YQ({keyType:Q,valueType:Y,typeName:j0.ZodRecord,...O0(J)});return new YQ({keyType:f1.create(),valueType:Q,typeName:j0.ZodRecord,...O0(Y)})}}class JQ extends R0{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==q0.map)return G0(J,{code:o.invalid_type,expected:q0.map,received:J.parsedType}),F0;let X=this._def.keyType,B=this._def.valueType,q=[...J.data.entries()].map(([G,H],U)=>{return{key:X._parse(new u1(J,G,J.path,[U,"key"])),value:B._parse(new u1(J,H,J.path,[U,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let H of q){let U=await H.key,z=await H.value;if(U.status==="aborted"||z.status==="aborted")return F0;if(U.status==="dirty"||z.status==="dirty")Y.dirty();G.set(U.value,z.value)}return{status:Y.value,value:G}})}else{let G=new Map;for(let H of q){let{key:U,value:z}=H;if(U.status==="aborted"||z.status==="aborted")return F0;if(U.status==="dirty"||z.status==="dirty")Y.dirty();G.set(U.value,z.value)}return{status:Y.value,value:G}}}}JQ.create=(Q,Y,J)=>{return new JQ({valueType:Y,keyType:Q,typeName:j0.ZodMap,...O0(J)})};class h9 extends R0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.parsedType!==q0.set)return G0(J,{code:o.invalid_type,expected:q0.set,received:J.parsedType}),F0;let X=this._def;if(X.minSize!==null){if(J.data.size<X.minSize.value)G0(J,{code:o.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),Y.dirty()}if(X.maxSize!==null){if(J.data.size>X.maxSize.value)G0(J,{code:o.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),Y.dirty()}let B=this._def.valueType;function q(H){let U=new Set;for(let z of H){if(z.status==="aborted")return F0;if(z.status==="dirty")Y.dirty();U.add(z.value)}return{status:Y.value,value:U}}let G=[...J.data.values()].map((H,U)=>B._parse(new u1(J,H,J.path,U)));if(J.common.async)return Promise.all(G).then((H)=>q(H));else return q(G)}min(Q,Y){return new h9({...this._def,minSize:{value:Q,message:L0.toString(Y)}})}max(Q,Y){return new h9({...this._def,maxSize:{value:Q,message:L0.toString(Y)}})}size(Q,Y){return this.min(Q,Y).max(Q,Y)}nonempty(Q){return this.min(1,Q)}}h9.create=(Q,Y)=>{return new h9({valueType:Q,minSize:null,maxSize:null,typeName:j0.ZodSet,...O0(Y)})};class H8 extends R0{constructor(){super(...arguments);this.validate=this.implement}_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==q0.function)return G0(Y,{code:o.invalid_type,expected:q0.function,received:Y.parsedType}),F0;function J(G,H){return hQ({data:G,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,fQ(),z8].filter((U)=>!!U),issueData:{code:o.invalid_arguments,argumentsError:H}})}function X(G,H){return hQ({data:G,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,fQ(),z8].filter((U)=>!!U),issueData:{code:o.invalid_return_type,returnTypeError:H}})}let B={errorMap:Y.common.contextualErrorMap},q=Y.data;if(this._def.returns instanceof m9){let G=this;return A1(async function(...H){let U=new S1([]),z=await G._def.args.parseAsync(H,B).catch((V)=>{throw U.addIssue(J(H,V)),U}),j=await Reflect.apply(q,this,z);return await G._def.returns._def.type.parseAsync(j,B).catch((V)=>{throw U.addIssue(X(j,V)),U})})}else{let G=this;return A1(function(...H){let U=G._def.args.safeParse(H,B);if(!U.success)throw new S1([J(H,U.error)]);let z=Reflect.apply(q,this,U.data),j=G._def.returns.safeParse(z,B);if(!j.success)throw new S1([X(z,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...Q){return new H8({...this._def,args:r1.create(Q).rest(E9.create())})}returns(Q){return new H8({...this._def,returns:Q})}implement(Q){return this.parse(Q)}strictImplement(Q){return this.parse(Q)}static create(Q,Y,J){return new H8({args:Q?Q:r1.create([]).rest(E9.create()),returns:Y||E9.create(),typeName:j0.ZodFunction,...O0(J)})}}class K8 extends R0{get schema(){return this._def.getter()}_parse(Q){let{ctx:Y}=this._processInputParams(Q);return this._def.getter()._parse({data:Y.data,path:Y.path,parent:Y})}}K8.create=(Q,Y)=>{return new K8({getter:Q,typeName:j0.ZodLazy,...O0(Y)})};class M8 extends R0{_parse(Q){if(Q.data!==this._def.value){let Y=this._getOrReturnCtx(Q);return G0(Y,{received:Y.data,code:o.invalid_literal,expected:this._def.value}),F0}return{status:"valid",value:Q.data}}get value(){return this._def.value}}M8.create=(Q,Y)=>{return new M8({value:Q,typeName:j0.ZodLiteral,...O0(Y)})};function g5(Q,Y){return new I9({values:Q,typeName:j0.ZodEnum,...O0(Y)})}class I9 extends R0{_parse(Q){if(typeof Q.data!=="string"){let Y=this._getOrReturnCtx(Q),J=this._def.values;return G0(Y,{expected:x0.joinValues(J),received:Y.parsedType,code:o.invalid_type}),F0}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(Q.data)){let Y=this._getOrReturnCtx(Q),J=this._def.values;return G0(Y,{received:Y.data,code:o.invalid_enum_value,options:J}),F0}return A1(Q.data)}get options(){return this._def.values}get enum(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}get Values(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}get Enum(){let Q={};for(let Y of this._def.values)Q[Y]=Y;return Q}extract(Q,Y=this._def){return I9.create(Q,{...this._def,...Y})}exclude(Q,Y=this._def){return I9.create(this.options.filter((J)=>!Q.includes(J)),{...this._def,...Y})}}I9.create=g5;class A8 extends R0{_parse(Q){let Y=x0.getValidEnumValues(this._def.values),J=this._getOrReturnCtx(Q);if(J.parsedType!==q0.string&&J.parsedType!==q0.number){let X=x0.objectValues(Y);return G0(J,{expected:x0.joinValues(X),received:J.parsedType,code:o.invalid_type}),F0}if(!this._cache)this._cache=new Set(x0.getValidEnumValues(this._def.values));if(!this._cache.has(Q.data)){let X=x0.objectValues(Y);return G0(J,{received:J.data,code:o.invalid_enum_value,options:X}),F0}return A1(Q.data)}get enum(){return this._def.values}}A8.create=(Q,Y)=>{return new A8({values:Q,typeName:j0.ZodNativeEnum,...O0(Y)})};class m9 extends R0{unwrap(){return this._def.type}_parse(Q){let{ctx:Y}=this._processInputParams(Q);if(Y.parsedType!==q0.promise&&Y.common.async===!1)return G0(Y,{code:o.invalid_type,expected:q0.promise,received:Y.parsedType}),F0;let J=Y.parsedType===q0.promise?Y.data:Promise.resolve(Y.data);return A1(J.then((X)=>{return this._def.type.parseAsync(X,{path:Y.path,errorMap:Y.common.contextualErrorMap})}))}}m9.create=(Q,Y)=>{return new m9({type:Q,typeName:j0.ZodPromise,...O0(Y)})};class T1 extends R0{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j0.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q),X=this._def.effect||null,B={addIssue:(q)=>{if(G0(J,q),q.fatal)Y.abort();else Y.dirty()},get path(){return J.path}};if(B.addIssue=B.addIssue.bind(B),X.type==="preprocess"){let q=X.transform(J.data,B);if(J.common.async)return Promise.resolve(q).then(async(G)=>{if(Y.value==="aborted")return F0;let H=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(H.status==="aborted")return F0;if(H.status==="dirty")return q8(H.value);if(Y.value==="dirty")return q8(H.value);return H});else{if(Y.value==="aborted")return F0;let G=this._def.schema._parseSync({data:q,path:J.path,parent:J});if(G.status==="aborted")return F0;if(G.status==="dirty")return q8(G.value);if(Y.value==="dirty")return q8(G.value);return G}}if(X.type==="refinement"){let q=(G)=>{let H=X.refinement(G,B);if(J.common.async)return Promise.resolve(H);if(H instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return F0;if(G.status==="dirty")Y.dirty();return q(G.value),{status:Y.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return F0;if(G.status==="dirty")Y.dirty();return q(G.value).then(()=>{return{status:Y.value,value:G.value}})})}if(X.type==="transform")if(J.common.async===!1){let q=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!y9(q))return F0;let G=X.transform(q.value,B);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:Y.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((q)=>{if(!y9(q))return F0;return Promise.resolve(X.transform(q.value,B)).then((G)=>({status:Y.value,value:G}))});x0.assertNever(X)}}T1.create=(Q,Y,J)=>{return new T1({schema:Q,typeName:j0.ZodEffects,effect:Y,...O0(J)})};T1.createWithPreprocess=(Q,Y,J)=>{return new T1({schema:Y,effect:{type:"preprocess",transform:Q},typeName:j0.ZodEffects,...O0(J)})};class m1 extends R0{_parse(Q){if(this._getType(Q)===q0.undefined)return A1(void 0);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}m1.create=(Q,Y)=>{return new m1({innerType:Q,typeName:j0.ZodOptional,...O0(Y)})};class K9 extends R0{_parse(Q){if(this._getType(Q)===q0.null)return A1(null);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}K9.create=(Q,Y)=>{return new K9({innerType:Q,typeName:j0.ZodNullable,...O0(Y)})};class V8 extends R0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;if(Y.parsedType===q0.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:Y.path,parent:Y})}removeDefault(){return this._def.innerType}}V8.create=(Q,Y)=>{return new V8({innerType:Q,typeName:j0.ZodDefault,defaultValue:typeof Y.default==="function"?Y.default:()=>Y.default,...O0(Y)})};class D8 extends R0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J={...Y,common:{...Y.common,issues:[]}},X=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(e8(X))return X.then((B)=>{return{status:"valid",value:B.status==="valid"?B.value:this._def.catchValue({get error(){return new S1(J.common.issues)},input:J.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new S1(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}D8.create=(Q,Y)=>{return new D8({innerType:Q,typeName:j0.ZodCatch,catchValue:typeof Y.catch==="function"?Y.catch:()=>Y.catch,...O0(Y)})};class WQ extends R0{_parse(Q){if(this._getType(Q)!==q0.nan){let J=this._getOrReturnCtx(Q);return G0(J,{code:o.invalid_type,expected:q0.nan,received:J.parsedType}),F0}return{status:"valid",value:Q.data}}}WQ.create=(Q)=>{return new WQ({typeName:j0.ZodNaN,...O0(Q)})};var AL=Symbol("zod_brand");class dQ extends R0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;return this._def.type._parse({data:J,path:Y.path,parent:Y})}unwrap(){return this._def.type}}class BQ extends R0{_parse(Q){let{status:Y,ctx:J}=this._processInputParams(Q);if(J.common.async)return(async()=>{let B=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(B.status==="aborted")return F0;if(B.status==="dirty")return Y.dirty(),q8(B.value);else return this._def.out._parseAsync({data:B.value,path:J.path,parent:J})})();else{let X=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(X.status==="aborted")return F0;if(X.status==="dirty")return Y.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:J.path,parent:J})}}static create(Q,Y){return new BQ({in:Q,out:Y,typeName:j0.ZodPipeline})}}class w8 extends R0{_parse(Q){let Y=this._def.innerType._parse(Q),J=(X)=>{if(y9(X))X.value=Object.freeze(X.value);return X};return e8(Y)?Y.then((X)=>J(X)):J(Y)}unwrap(){return this._def.innerType}}w8.create=(Q,Y)=>{return new w8({innerType:Q,typeName:j0.ZodReadonly,...O0(Y)})};function F5(Q,Y){let J=typeof Q==="function"?Q(Y):typeof Q==="string"?{message:Q}:Q;return typeof J==="string"?{message:J}:J}function y5(Q,Y={},J){if(Q)return f9.create().superRefine((X,B)=>{let q=Q(X);if(q instanceof Promise)return q.then((G)=>{if(!G){let H=F5(Y,X),U=H.fatal??J??!0;B.addIssue({code:"custom",...H,fatal:U})}});if(!q){let G=F5(Y,X),H=G.fatal??J??!0;B.addIssue({code:"custom",...G,fatal:H})}return});return f9.create()}var VL={object:t0.lazycreate},j0;(function(Q){Q.ZodString="ZodString",Q.ZodNumber="ZodNumber",Q.ZodNaN="ZodNaN",Q.ZodBigInt="ZodBigInt",Q.ZodBoolean="ZodBoolean",Q.ZodDate="ZodDate",Q.ZodSymbol="ZodSymbol",Q.ZodUndefined="ZodUndefined",Q.ZodNull="ZodNull",Q.ZodAny="ZodAny",Q.ZodUnknown="ZodUnknown",Q.ZodNever="ZodNever",Q.ZodVoid="ZodVoid",Q.ZodArray="ZodArray",Q.ZodObject="ZodObject",Q.ZodUnion="ZodUnion",Q.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Q.ZodIntersection="ZodIntersection",Q.ZodTuple="ZodTuple",Q.ZodRecord="ZodRecord",Q.ZodMap="ZodMap",Q.ZodSet="ZodSet",Q.ZodFunction="ZodFunction",Q.ZodLazy="ZodLazy",Q.ZodLiteral="ZodLiteral",Q.ZodEnum="ZodEnum",Q.ZodEffects="ZodEffects",Q.ZodNativeEnum="ZodNativeEnum",Q.ZodOptional="ZodOptional",Q.ZodNullable="ZodNullable",Q.ZodDefault="ZodDefault",Q.ZodCatch="ZodCatch",Q.ZodPromise="ZodPromise",Q.ZodBranded="ZodBranded",Q.ZodPipeline="ZodPipeline",Q.ZodReadonly="ZodReadonly"})(j0||(j0={}));var DL=(Q,Y={message:`Input not instance of ${Q.name}`})=>y5((J)=>J instanceof Q,Y),$5=f1.create,f5=P9.create,wL=WQ.create,OL=S9.create,h5=U8.create,RL=$9.create,ZL=QQ.create,EL=L8.create,PL=F8.create,SL=f9.create,IL=E9.create,CL=o1.create,bL=XQ.create,TL=h1.create,_L=t0.create,kL=t0.strictCreate,vL=N8.create,xL=cQ.create,gL=j8.create,yL=r1.create,$L=YQ.create,fL=JQ.create,hL=h9.create,mL=H8.create,uL=K8.create,cL=M8.create,dL=I9.create,lL=A8.create,pL=m9.create,N5=T1.create,nL=m1.create,iL=K9.create,aL=T1.createWithPreprocess,sL=BQ.create,oL=()=>$5().optional(),rL=()=>f5().optional(),tL=()=>h5().optional(),eL={string:(Q)=>f1.create({...Q,coerce:!0}),number:(Q)=>P9.create({...Q,coerce:!0}),boolean:(Q)=>U8.create({...Q,coerce:!0}),bigint:(Q)=>S9.create({...Q,coerce:!0}),date:(Q)=>$9.create({...Q,coerce:!0})},QF=F0;var lQ="2.0",m5=O.union([O.string(),O.number().int()]),u5=O.string(),XF=O.object({progressToken:O.optional(m5)}).passthrough(),_1=O.object({_meta:O.optional(XF)}).passthrough(),w1=O.object({method:O.string(),params:O.optional(_1)}),qQ=O.object({_meta:O.optional(O.object({}).passthrough())}).passthrough(),t1=O.object({method:O.string(),params:O.optional(qQ)}),k1=O.object({_meta:O.optional(O.object({}).passthrough())}).passthrough(),pQ=O.union([O.string(),O.number().int()]),YF=O.object({jsonrpc:O.literal(lQ),id:pQ}).merge(w1).strict();var JF=O.object({jsonrpc:O.literal(lQ)}).merge(t1).strict();var WF=O.object({jsonrpc:O.literal(lQ),id:pQ,result:k1}).strict();var j5;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError"})(j5||(j5={}));var GF=O.object({jsonrpc:O.literal(lQ),id:pQ,error:O.object({code:O.number().int(),message:O.string(),data:O.optional(O.unknown())})}).strict();var ZD=O.union([YF,JF,WF,GF]),c5=k1.strict(),d5=t1.extend({method:O.literal("notifications/cancelled"),params:qQ.extend({requestId:pQ,reason:O.string().optional()})}),HQ=O.object({name:O.string(),title:O.optional(O.string())}).passthrough(),l5=HQ.extend({version:O.string()}),BF=O.object({experimental:O.optional(O.object({}).passthrough()),sampling:O.optional(O.object({}).passthrough()),elicitation:O.optional(O.object({}).passthrough()),roots:O.optional(O.object({listChanged:O.optional(O.boolean())}).passthrough())}).passthrough(),qF=w1.extend({method:O.literal("initialize"),params:_1.extend({protocolVersion:O.string(),capabilities:BF,clientInfo:l5})}),HF=O.object({experimental:O.optional(O.object({}).passthrough()),logging:O.optional(O.object({}).passthrough()),completions:O.optional(O.object({}).passthrough()),prompts:O.optional(O.object({listChanged:O.optional(O.boolean())}).passthrough()),resources:O.optional(O.object({subscribe:O.optional(O.boolean()),listChanged:O.optional(O.boolean())}).passthrough()),tools:O.optional(O.object({listChanged:O.optional(O.boolean())}).passthrough())}).passthrough(),zF=k1.extend({protocolVersion:O.string(),capabilities:HF,serverInfo:l5,instructions:O.optional(O.string())}),UF=t1.extend({method:O.literal("notifications/initialized")}),p5=w1.extend({method:O.literal("ping")}),LF=O.object({progress:O.number(),total:O.optional(O.number()),message:O.optional(O.string())}).passthrough(),n5=t1.extend({method:O.literal("notifications/progress"),params:qQ.merge(LF).extend({progressToken:m5})}),nQ=w1.extend({params:_1.extend({cursor:O.optional(u5)}).optional()}),iQ=k1.extend({nextCursor:O.optional(u5)}),i5=O.object({uri:O.string(),mimeType:O.optional(O.string()),_meta:O.optional(O.object({}).passthrough())}).passthrough(),a5=i5.extend({text:O.string()}),iX=O.string().refine((Q)=>{try{return atob(Q),!0}catch(Y){return!1}},{message:"Invalid Base64 string"}),s5=i5.extend({blob:iX}),o5=HQ.extend({uri:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),_meta:O.optional(O.object({}).passthrough())}),FF=HQ.extend({uriTemplate:O.string(),description:O.optional(O.string()),mimeType:O.optional(O.string()),_meta:O.optional(O.object({}).passthrough())}),NF=nQ.extend({method:O.literal("resources/list")}),jF=iQ.extend({resources:O.array(o5)}),KF=nQ.extend({method:O.literal("resources/templates/list")}),MF=iQ.extend({resourceTemplates:O.array(FF)}),AF=w1.extend({method:O.literal("resources/read"),params:_1.extend({uri:O.string()})}),VF=k1.extend({contents:O.array(O.union([a5,s5]))}),DF=t1.extend({method:O.literal("notifications/resources/list_changed")}),wF=w1.extend({method:O.literal("resources/subscribe"),params:_1.extend({uri:O.string()})}),OF=w1.extend({method:O.literal("resources/unsubscribe"),params:_1.extend({uri:O.string()})}),RF=t1.extend({method:O.literal("notifications/resources/updated"),params:qQ.extend({uri:O.string()})}),ZF=O.object({name:O.string(),description:O.optional(O.string()),required:O.optional(O.boolean())}).passthrough(),EF=HQ.extend({description:O.optional(O.string()),arguments:O.optional(O.array(ZF)),_meta:O.optional(O.object({}).passthrough())}),PF=nQ.extend({method:O.literal("prompts/list")}),SF=iQ.extend({prompts:O.array(EF)}),IF=w1.extend({method:O.literal("prompts/get"),params:_1.extend({name:O.string(),arguments:O.optional(O.record(O.string()))})}),aX=O.object({type:O.literal("text"),text:O.string(),_meta:O.optional(O.object({}).passthrough())}).passthrough(),sX=O.object({type:O.literal("image"),data:iX,mimeType:O.string(),_meta:O.optional(O.object({}).passthrough())}).passthrough(),oX=O.object({type:O.literal("audio"),data:iX,mimeType:O.string(),_meta:O.optional(O.object({}).passthrough())}).passthrough(),CF=O.object({type:O.literal("resource"),resource:O.union([a5,s5]),_meta:O.optional(O.object({}).passthrough())}).passthrough(),bF=o5.extend({type:O.literal("resource_link")}),r5=O.union([aX,sX,oX,bF,CF]),TF=O.object({role:O.enum(["user","assistant"]),content:r5}).passthrough(),_F=k1.extend({description:O.optional(O.string()),messages:O.array(TF)}),kF=t1.extend({method:O.literal("notifications/prompts/list_changed")}),vF=O.object({title:O.optional(O.string()),readOnlyHint:O.optional(O.boolean()),destructiveHint:O.optional(O.boolean()),idempotentHint:O.optional(O.boolean()),openWorldHint:O.optional(O.boolean())}).passthrough(),xF=HQ.extend({description:O.optional(O.string()),inputSchema:O.object({type:O.literal("object"),properties:O.optional(O.object({}).passthrough()),required:O.optional(O.array(O.string()))}).passthrough(),outputSchema:O.optional(O.object({type:O.literal("object"),properties:O.optional(O.object({}).passthrough()),required:O.optional(O.array(O.string()))}).passthrough()),annotations:O.optional(vF),_meta:O.optional(O.object({}).passthrough())}),gF=nQ.extend({method:O.literal("tools/list")}),yF=iQ.extend({tools:O.array(xF)}),t5=k1.extend({content:O.array(r5).default([]),structuredContent:O.object({}).passthrough().optional(),isError:O.optional(O.boolean())}),ED=t5.or(k1.extend({toolResult:O.unknown()})),$F=w1.extend({method:O.literal("tools/call"),params:_1.extend({name:O.string(),arguments:O.optional(O.record(O.unknown()))})}),fF=t1.extend({method:O.literal("notifications/tools/list_changed")}),e5=O.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),hF=w1.extend({method:O.literal("logging/setLevel"),params:_1.extend({level:e5})}),mF=t1.extend({method:O.literal("notifications/message"),params:qQ.extend({level:e5,logger:O.optional(O.string()),data:O.unknown()})}),uF=O.object({name:O.string().optional()}).passthrough(),cF=O.object({hints:O.optional(O.array(uF)),costPriority:O.optional(O.number().min(0).max(1)),speedPriority:O.optional(O.number().min(0).max(1)),intelligencePriority:O.optional(O.number().min(0).max(1))}).passthrough(),dF=O.object({role:O.enum(["user","assistant"]),content:O.union([aX,sX,oX])}).passthrough(),lF=w1.extend({method:O.literal("sampling/createMessage"),params:_1.extend({messages:O.array(dF),systemPrompt:O.optional(O.string()),includeContext:O.optional(O.enum(["none","thisServer","allServers"])),temperature:O.optional(O.number()),maxTokens:O.number().int(),stopSequences:O.optional(O.array(O.string())),metadata:O.optional(O.object({}).passthrough()),modelPreferences:O.optional(cF)})}),pF=k1.extend({model:O.string(),stopReason:O.optional(O.enum(["endTurn","stopSequence","maxTokens"]).or(O.string())),role:O.enum(["user","assistant"]),content:O.discriminatedUnion("type",[aX,sX,oX])}),nF=O.object({type:O.literal("boolean"),title:O.optional(O.string()),description:O.optional(O.string()),default:O.optional(O.boolean())}).passthrough(),iF=O.object({type:O.literal("string"),title:O.optional(O.string()),description:O.optional(O.string()),minLength:O.optional(O.number()),maxLength:O.optional(O.number()),format:O.optional(O.enum(["email","uri","date","date-time"]))}).passthrough(),aF=O.object({type:O.enum(["number","integer"]),title:O.optional(O.string()),description:O.optional(O.string()),minimum:O.optional(O.number()),maximum:O.optional(O.number())}).passthrough(),sF=O.object({type:O.literal("string"),title:O.optional(O.string()),description:O.optional(O.string()),enum:O.array(O.string()),enumNames:O.optional(O.array(O.string()))}).passthrough(),oF=O.union([nF,iF,aF,sF]),rF=w1.extend({method:O.literal("elicitation/create"),params:_1.extend({message:O.string(),requestedSchema:O.object({type:O.literal("object"),properties:O.record(O.string(),oF),required:O.optional(O.array(O.string()))}).passthrough()})}),tF=k1.extend({action:O.enum(["accept","decline","cancel"]),content:O.optional(O.record(O.string(),O.unknown()))}),eF=O.object({type:O.literal("ref/resource"),uri:O.string()}).passthrough(),QN=O.object({type:O.literal("ref/prompt"),name:O.string()}).passthrough(),XN=w1.extend({method:O.literal("completion/complete"),params:_1.extend({ref:O.union([QN,eF]),argument:O.object({name:O.string(),value:O.string()}).passthrough(),context:O.optional(O.object({arguments:O.optional(O.record(O.string(),O.string()))}))})}),YN=k1.extend({completion:O.object({values:O.array(O.string()).max(100),total:O.optional(O.number().int()),hasMore:O.optional(O.boolean())}).passthrough()}),JN=O.object({uri:O.string().startsWith("file://"),name:O.optional(O.string()),_meta:O.optional(O.object({}).passthrough())}).passthrough(),WN=w1.extend({method:O.literal("roots/list")}),GN=k1.extend({roots:O.array(JN)}),BN=t1.extend({method:O.literal("notifications/roots/list_changed")}),PD=O.union([p5,qF,XN,hF,IF,PF,NF,KF,AF,wF,OF,$F,gF]),SD=O.union([d5,n5,UF,BN]),ID=O.union([c5,pF,tF,GN]),CD=O.union([p5,lF,rF,WN]),bD=O.union([d5,n5,mF,RF,DF,fF,kF]),TD=O.union([c5,zF,YN,_F,SF,jF,MF,VF,t5,yF]);var _D=tq(vH(),1);var kD=Symbol("Let zodToJsonSchema decide on which parser to use");var vD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var mX;(function(Q){Q.Completable="McpCompletable"})(mX||(mX={}));class uX extends R0{_parse(Q){let{ctx:Y}=this._processInputParams(Q),J=Y.data;return this._def.type._parse({data:J,path:Y.path,parent:Y})}unwrap(){return this._def.type}}uX.create=(Q,Y)=>{return new uX({type:Q,typeName:mX.Completable,complete:Y.complete,...qN(Y)})};function qN(Q){if(!Q)return{};let{errorMap:Y,invalid_type_error:J,required_error:X,description:B}=Q;if(Y&&(J||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Y)return{errorMap:Y,description:B};return{errorMap:(G,H)=>{var U,z;let{message:j}=Q;if(G.code==="invalid_enum_value")return{message:j!==null&&j!==void 0?j:H.defaultError};if(typeof H.data>"u")return{message:(U=j!==null&&j!==void 0?j:X)!==null&&U!==void 0?U:H.defaultError};if(G.code!=="invalid_type")return{message:H.defaultError};return{message:(z=j!==null&&j!==void 0?j:J)!==null&&z!==void 0?z:H.defaultError}},description:B}}function rX({prompt:Q,options:Y}){let{systemPrompt:J,settingSources:X,...B}=Y??{},q,G;if(J===void 0)q="";else if(typeof J==="string")q=J;else if(J.type==="preset")G=J.append;let H=B.pathToClaudeCodeExecutable;if(!H){let M0=xH(import.meta.url),h=W5(M0,"..");H=W5(h,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.30";let{abortController:U=D5(),additionalDirectories:z=[],agents:j,allowedTools:A=[],canUseTool:V,continue:F,cwd:D,disallowedTools:L=[],env:N,executable:K=w5()?"bun":"node",executableArgs:M=[],extraArgs:w={},fallbackModel:_,forkSession:g,hooks:S,includePartialMessages:C,maxThinkingTokens:T,maxTurns:b,maxBudgetUsd:k,mcpServers:I,model:E,permissionMode:R="default",allowDangerouslySkipPermissions:Z=!1,permissionPromptToolName:v,plugins:y,resume:m,resumeSessionAt:i,stderr:l,strictMcpConfig:r}=B,d=N;if(!d)d={...process.env};if(!d.CLAUDE_CODE_ENTRYPOINT)d.CLAUDE_CODE_ENTRYPOINT="sdk-ts";if(!H)throw Error("pathToClaudeCodeExecutable is required");let t={},Q0=new Map;if(I)for(let[M0,h]of Object.entries(I))if(h.type==="sdk"&&"instance"in h)Q0.set(M0,h.instance),t[M0]={type:"sdk",name:M0};else t[M0]=h;let $=typeof Q==="string",H0=new O5({abortController:U,additionalDirectories:z,agents:j,cwd:D,executable:K,executableArgs:M,extraArgs:w,pathToClaudeCodeExecutable:H,env:d,forkSession:g,stderr:l,customSystemPrompt:q,appendSystemPrompt:G,maxThinkingTokens:T,maxTurns:b,maxBudgetUsd:k,model:E,fallbackModel:_,permissionMode:R,allowDangerouslySkipPermissions:Z,permissionPromptToolName:v,continueConversation:F,resume:m,resumeSessionAt:i,settingSources:X??[],allowedTools:A,disallowedTools:L,mcpServers:t,strictMcpConfig:r,canUseTool:!!V,hooks:!!S,includePartialMessages:C,plugins:y}),E0=new T5(H0,$,V,S,U,Q0);if(typeof Q==="string")H0.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:Q}]},parent_tool_use_id:null})+`
49
- `);else E0.streamInput(Q);return E0}var LN="Image URLs are not supported by this provider; supply base64/data URLs.",e1="Unable to convert image content; supply base64/data URLs.";function FN(Q){return Q.replace(/\s+/g,"")}function NN(Q){return typeof Q==="string"&&Q.trim().toLowerCase().startsWith("image/")}function P8(Q,Y){let J=Q.trim(),X=FN(Y.trim());if(!J||!X)return;return{type:"image",source:{type:"base64",media_type:J,data:X}}}function eX(Q){if(typeof Q==="string"&&Q.trim())return Q.trim();return}function jN(Q,Y){let J=typeof Q.data==="string"?Q.data:void 0,X=eX(Q.mimeType??Q.mediaType??Q.media_type??Y);if(!J||!X)return;return P8(X,J)}function KN(Q,Y){let J=Q.trim();if(/^https?:\/\//i.test(J))return{warning:LN};let X=J.match(/^data:([^;]+);base64,(.+)$/i);if(X){let[,q,G]=X,H=P8(q,G);return H?{content:H}:{warning:e1}}let B=J.match(/^base64:([^,]+),(.+)$/i);if(B){let[,q,G]=B,H=P8(q,G);return H?{content:H}:{warning:e1}}if(Y){let q=P8(Y,J);if(q)return{content:q}}return{warning:e1}}function MN(Q){if(!Q||typeof Q!=="object")return{warning:e1};let Y=Q.image,J=eX(Q.mimeType);if(typeof Y==="string")return KN(Y,J);if(Y&&typeof Y==="object"){let X=jN(Y,J);return X?{content:X}:{warning:e1}}return{warning:e1}}function AN(Q){if(typeof Buffer<"u")return(Q instanceof Uint8Array?Buffer.from(Q):Buffer.from(new Uint8Array(Q))).toString("base64");if(typeof btoa==="function"){let Y=Q instanceof Uint8Array?Q:new Uint8Array(Q),J="",X=32768;for(let B=0;B<Y.length;B+=X){let q=Y.subarray(B,B+X);J+=String.fromCharCode(...q)}return btoa(J)}return}function VN(Q){let Y=eX(Q.mediaType??Q.mimeType);if(!Y||!NN(Y))return{};let J=Q.data;if(typeof J==="string"){let X=P8(Y,J);return X?{content:X}:{warning:e1}}if(J instanceof Uint8Array||typeof ArrayBuffer<"u"&&J instanceof ArrayBuffer){let X=AN(J);if(!X)return{warning:e1};let B=P8(Y,X);return B?{content:B}:{warning:e1}}return{warning:e1}}function QW(Q,Y={type:"regular"},J){let X=[],B=[],q,G=[],H=new Map,U=!1,z=(L)=>{return G.push({formatted:L}),G.length-1},j=(L,N)=>{if(U=!0,!H.has(L))H.set(L,[]);H.get(L)?.push(N)};for(let L of Q)switch(L.role){case"system":if(q=L.content,typeof L.content==="string"&&L.content.trim().length>0)z(L.content);else z("");break;case"user":if(typeof L.content==="string")X.push(L.content),z(`Human: ${L.content}`);else{let N=L.content.filter((M)=>M.type==="text").map((M)=>M.text).join(`
50
- `),K=z(N?`Human: ${N}`:"");if(N)X.push(N);for(let M of L.content)if(M.type==="image"){let{content:w,warning:_}=MN(M);if(w)j(K,w);else if(_)B.push(_)}else if(M.type==="file"){let{content:w,warning:_}=VN(M);if(w)j(K,w);else if(_)B.push(_)}}break;case"assistant":{let N="";if(typeof L.content==="string")N=L.content;else{let M=L.content.filter((_)=>_.type==="text").map((_)=>_.text).join(`
51
- `);if(M)N=M;if(L.content.filter((_)=>_.type==="tool-call").length>0)N+=`
52
- [Tool calls made]`}let K=`Assistant: ${N}`;X.push(K),z(K);break}case"tool":for(let N of L.content){let K=N.output.type==="text"?N.output.value:JSON.stringify(N.output.value),M=`Tool Result (${N.toolName}): ${K}`;X.push(M),z(M)}break}let A="";if(q)A=q;if(X.length>0){let L=[];for(let N=0;N<X.length;N++){let K=X[N];if(K.startsWith("Assistant:")||K.startsWith("Tool Result"))L.push(K);else L.push(`Human: ${K}`)}if(A){let N=L.join(`
53
-
54
- `);A=N?`${A}
55
-
56
- ${N}`:A}else A=L.join(`
57
-
58
- `)}let V=[],F=[],D=(L)=>{let N=H.get(L);if(!N)return;N.forEach((K)=>{V.push(K),F.push(K)})};if(G.length>0){let L="",N=!1,K=()=>{if(!L)return;V.push({type:"text",text:L}),L="",N=!0};G.forEach((M,w)=>{let _=M.formatted;if(_)if(!L)L=N?`
59
-
60
- ${_}`:_;else L+=`
61
-
62
- ${_}`;if(H.has(w))K(),D(w)}),K()}if(Y?.type==="object-json"&&J)A=`CRITICAL: You MUST respond with ONLY a JSON object. NO other text, NO explanations, NO questions.
63
-
64
- Your response MUST start with { and end with }
65
-
66
- The JSON MUST match this EXACT schema:
67
- ${JSON.stringify(J,null,2)}
68
-
69
- Now, based on the following conversation, generate ONLY the JSON object with the exact fields specified above:
70
-
71
- ${A}
72
-
73
- Remember: Your ENTIRE response must be ONLY the JSON object, starting with { and ending with }`,V=[{type:"text",text:A},...F];return{messagesPrompt:A,systemPrompt:q,...B.length>0&&{warnings:B},streamingContentParts:V.length>0?V:[{type:"text",text:A},...F],hasImageParts:U}}function DN(Q){let Y=Q.trim(),J=/```(?:json)?\s*([\s\S]*?)\s*```/i.exec(Y);if(J)Y=J[1];let X=/^\s*(?:const|let|var)\s+\w+\s*=\s*([\s\S]*)/i.exec(Y);if(X){if(Y=X[1],Y.trim().endsWith(";"))Y=Y.trim().slice(0,-1)}let B=Y.indexOf("{"),q=Y.indexOf("[");if(B===-1&&q===-1)return Q;let G=q===-1?B:B===-1?q:Math.min(B,q);Y=Y.slice(G);let H=(N)=>{let K=[];try{let M=qW.parse(N,K,{allowTrailingComma:!0});if(K.length===0)return JSON.stringify(M,null,2)}catch{}return},U=H(Y);if(U!==void 0)return U;let z=Y[0],j=z==="{"?"}":"]",A=[],V=0,F=!1,D=!1;for(let N=0;N<Y.length;N++){let K=Y[N];if(D){D=!1;continue}if(K==="\\"){D=!0;continue}if(K==='"'&&!F){F=!0;continue}if(K==='"'&&F){F=!1;continue}if(F)continue;if(K===z)V++;else if(K===j){if(V--,V===0)A.push(N+1)}}for(let N=A.length-1;N>=0;N--){let K=H(Y.slice(0,A[N]));if(K!==void 0)return K}let L=Math.max(0,Y.length-1000);for(let N=Y.length-1;N>L;N--){let K=H(Y.slice(0,N));if(K!==void 0)return K}return Q}function wN({message:Q,code:Y,exitCode:J,stderr:X,promptExcerpt:B,isRetryable:q=!1}){return new a0({message:Q,isRetryable:q,url:"claude-code-cli://command",requestBodyValues:B?{prompt:B}:void 0,data:{code:Y,exitCode:J,stderr:X,promptExcerpt:B}})}function ON({message:Q}){return new k9({message:Q||"Authentication failed. Please ensure Claude Code SDK is properly authenticated."})}function RN({message:Q,promptExcerpt:Y,timeoutMs:J}){let X={code:"TIMEOUT",promptExcerpt:Y};return new a0({message:Q,isRetryable:!0,url:"claude-code-cli://command",requestBodyValues:Y?{prompt:Y}:void 0,data:J!==void 0?{...X,timeoutMs:J}:X})}function XW(Q){switch(Q){case"success":return"stop";case"error_max_turns":return"length";case"error_during_execution":return"error";default:return"stop"}}var EN=W.object({debug:W.any().refine((Q)=>typeof Q==="function",{message:"debug must be a function"}),info:W.any().refine((Q)=>typeof Q==="function",{message:"info must be a function"}),warn:W.any().refine((Q)=>typeof Q==="function",{message:"warn must be a function"}),error:W.any().refine((Q)=>typeof Q==="function",{message:"error must be a function"})}),PN=W.object({pathToClaudeCodeExecutable:W.string().optional(),customSystemPrompt:W.string().optional(),appendSystemPrompt:W.string().optional(),systemPrompt:W.union([W.string(),W.object({type:W.literal("preset"),preset:W.literal("claude_code"),append:W.string().optional()})]).optional(),maxTurns:W.number().int().min(1).max(100).optional(),maxThinkingTokens:W.number().int().positive().max(1e5).optional(),cwd:W.string().refine((Q)=>{if(typeof process>"u"||!process.versions?.node)return!0;return!Q||ZN(Q)},{message:"Working directory must exist"}).optional(),executable:W.enum(["bun","deno","node"]).optional(),executableArgs:W.array(W.string()).optional(),permissionMode:W.enum(["default","acceptEdits","bypassPermissions","plan"]).optional(),permissionPromptToolName:W.string().optional(),continue:W.boolean().optional(),resume:W.string().optional(),allowedTools:W.array(W.string()).optional(),disallowedTools:W.array(W.string()).optional(),settingSources:W.array(W.enum(["user","project","local"])).optional(),streamingInput:W.enum(["auto","always","off"]).optional(),canUseTool:W.any().refine((Q)=>Q===void 0||typeof Q==="function",{message:"canUseTool must be a function"}).optional(),hooks:W.record(W.string(),W.array(W.object({matcher:W.string().optional(),hooks:W.array(W.any()).nonempty()}))).optional(),mcpServers:W.record(W.string(),W.union([W.object({type:W.literal("stdio").optional(),command:W.string(),args:W.array(W.string()).optional(),env:W.record(W.string(),W.string()).optional()}),W.object({type:W.literal("sse"),url:W.string(),headers:W.record(W.string(),W.string()).optional()}),W.object({type:W.literal("http"),url:W.string(),headers:W.record(W.string(),W.string()).optional()}),W.object({type:W.literal("sdk"),name:W.string(),instance:W.any()})])).optional(),verbose:W.boolean().optional(),logger:W.union([W.literal(!1),EN]).optional(),env:W.record(W.string(),W.string().optional()).optional(),additionalDirectories:W.array(W.string()).optional(),agents:W.record(W.string(),W.object({description:W.string(),tools:W.array(W.string()).optional(),prompt:W.string(),model:W.enum(["sonnet","opus","haiku","inherit"]).optional()})).optional(),includePartialMessages:W.boolean().optional(),fallbackModel:W.string().optional(),forkSession:W.boolean().optional(),stderr:W.any().refine((Q)=>Q===void 0||typeof Q==="function",{message:"stderr must be a function"}).optional(),strictMcpConfig:W.boolean().optional(),extraArgs:W.record(W.string(),W.union([W.string(),W.null()])).optional()}).strict();function SN(Q){let Y=["opus","sonnet","haiku"];if(!Q||Q.trim()==="")throw Error("Model ID cannot be empty");if(!Y.includes(Q))return`Unknown model ID: '${Q}'. Proceeding with custom model. Known models are: ${Y.join(", ")}`;return}function YW(Q){let Y=[],J=[];try{let X=PN.safeParse(Q);if(!X.success){let G=X.error;return(G.errors||G.issues||[]).forEach((U)=>{let z=U.path.join(".");J.push(`${z?`${z}: `:""}${U.message}`)}),{valid:!1,warnings:Y,errors:J}}let B=X.data;if(B.maxTurns&&B.maxTurns>20)Y.push(`High maxTurns value (${B.maxTurns}) may lead to long-running conversations`);if(B.maxThinkingTokens&&B.maxThinkingTokens>50000)Y.push(`Very high maxThinkingTokens (${B.maxThinkingTokens}) may increase response time`);if(B.allowedTools&&B.disallowedTools)Y.push("Both allowedTools and disallowedTools are specified. Only allowedTools will be used.");let q=(G,H)=>{G.forEach((U)=>{if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\([^)]*\))?$/.test(U)&&!U.startsWith("mcp__"))Y.push(`Unusual ${H} tool name format: '${U}'`)})};if(B.allowedTools)q(B.allowedTools,"allowed");if(B.disallowedTools)q(B.disallowedTools,"disallowed");return{valid:!0,warnings:Y,errors:J}}catch(X){return J.push(`Validation error: ${X instanceof Error?X.message:String(X)}`),{valid:!1,warnings:Y,errors:J}}}function IN(Q){if(Q.length>1e5)return`Very long prompt (${Q.length} characters) may cause performance issues or timeouts`;return}function CN(Q){if(Q&&!/^[a-zA-Z0-9-_]+$/.test(Q))return"Unusual session ID format. This may cause issues with session resumption.";return}var bN={debug:(Q)=>console.debug(`[DEBUG] ${Q}`),info:(Q)=>console.info(`[INFO] ${Q}`),warn:(Q)=>console.warn(`[WARN] ${Q}`),error:(Q)=>console.error(`[ERROR] ${Q}`)},TN={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function HW(Q){if(Q===!1)return TN;if(Q===void 0)return bN;return Q}function _N(Q,Y=!1){if(Y)return Q;return{debug:()=>{},info:()=>{},warn:Q.warn.bind(Q),error:Q.error.bind(Q)}}var JW="Claude Code SDK output ended unexpectedly; returning truncated response from buffered text. Await upstream fix to avoid data loss.",kN=512;function WW(Q,Y){if(!(Q instanceof SyntaxError||typeof Q?.name==="string"&&Q.name.toLowerCase()==="syntaxerror"))return!1;if(!Y)return!1;let B=(typeof Q?.message==="string"?Q.message:"").toLowerCase();if(!["unexpected end of json input","unexpected end of input","unexpected end of string","unexpected eof","end of file","unterminated string","unterminated string constant"].some((G)=>B.includes(G)))return!1;if(Y.length<kN)return!1;return!0}function tX(Q){if(Q&&typeof Q==="object"){let Y=Q;if(typeof Y.name==="string"&&Y.name==="AbortError")return!0;if(typeof Y.code==="string"&&Y.code.toUpperCase()==="ABORT_ERR")return!0}return!1}var GW="Claude Agent SDK features (hooks/MCP/images) require streaming input. Set `streamingInput: 'always'` or provide `canUseTool` (auto streams only when canUseTool is set).";function BW(Q,Y,J,X){let q={type:"user",message:{role:"user",content:X&&X.length>0?X:[{type:"text",text:Q}]},parent_tool_use_id:null,session_id:J??""};return{async*[Symbol.asyncIterator](){yield q,await Y}}}var vN={opus:"opus",sonnet:"sonnet",haiku:"haiku"},xN=class Q{specificationVersion="v2";defaultObjectGenerationMode="json";supportsImageUrls=!1;supportedUrls={};supportsStructuredOutputs=!1;static UNKNOWN_TOOL_NAME="unknown-tool";static MAX_TOOL_INPUT_SIZE=1048576;static MAX_TOOL_INPUT_WARN=102400;static MAX_DELTA_CALC_SIZE=1e4;modelId;settings;sessionId;modelValidationWarning;settingsValidationWarnings;logger;constructor(Y){this.modelId=Y.id,this.settings=Y.settings??{},this.settingsValidationWarnings=Y.settingsValidationWarnings??[];let J=HW(this.settings.logger);if(this.logger=_N(J,this.settings.verbose??!1),!this.modelId||typeof this.modelId!=="string"||this.modelId.trim()==="")throw new M9({modelId:this.modelId,modelType:"languageModel"});if(this.modelValidationWarning=SN(this.modelId),this.modelValidationWarning)this.logger.warn(`Claude Code Model: ${this.modelValidationWarning}`)}get provider(){return"claude-code"}getModel(){return vN[this.modelId]??this.modelId}extractToolUses(Y){if(!Array.isArray(Y))return[];return Y.filter((J)=>typeof J==="object"&&J!==null&&("type"in J)&&J.type==="tool_use").map((J)=>{let{id:X,name:B,input:q}=J;return{id:typeof X==="string"&&X.length>0?X:U9(),name:typeof B==="string"&&B.length>0?B:Q.UNKNOWN_TOOL_NAME,input:q}})}extractToolResults(Y){if(!Array.isArray(Y))return[];return Y.filter((J)=>typeof J==="object"&&J!==null&&("type"in J)&&J.type==="tool_result").map((J)=>{let{tool_use_id:X,content:B,is_error:q,name:G}=J;return{id:typeof X==="string"&&X.length>0?X:U9(),name:typeof G==="string"&&G.length>0?G:void 0,result:B,isError:Boolean(q)}})}extractToolErrors(Y){if(!Array.isArray(Y))return[];return Y.filter((J)=>typeof J==="object"&&J!==null&&("type"in J)&&J.type==="tool_error").map((J)=>{let{tool_use_id:X,error:B,name:q}=J;return{id:typeof X==="string"&&X.length>0?X:U9(),name:typeof q==="string"&&q.length>0?q:void 0,error:B}})}serializeToolInput(Y){if(typeof Y==="string")return this.checkInputSize(Y);if(Y===void 0)return"";try{let J=JSON.stringify(Y);return this.checkInputSize(J)}catch{let J=String(Y);return this.checkInputSize(J)}}checkInputSize(Y){let J=Y.length;if(J>Q.MAX_TOOL_INPUT_SIZE)throw Error(`Tool input exceeds maximum size of ${Q.MAX_TOOL_INPUT_SIZE} bytes (got ${J} bytes). This may indicate a malformed request or an attempt to process excessively large data.`);if(J>Q.MAX_TOOL_INPUT_WARN)this.logger.warn(`[claude-code] Large tool input detected: ${J} bytes. Performance may be impacted. Consider chunking or reducing input size.`);return Y}normalizeToolResult(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}generateAllWarnings(Y,J){let X=[],B=[];if(Y.temperature!==void 0)B.push("temperature");if(Y.topP!==void 0)B.push("topP");if(Y.topK!==void 0)B.push("topK");if(Y.presencePenalty!==void 0)B.push("presencePenalty");if(Y.frequencyPenalty!==void 0)B.push("frequencyPenalty");if(Y.stopSequences!==void 0&&Y.stopSequences.length>0)B.push("stopSequences");if(Y.seed!==void 0)B.push("seed");if(B.length>0)for(let G of B)X.push({type:"unsupported-setting",setting:G,details:`Claude Code SDK does not support the ${G} parameter. It will be ignored.`});if(this.modelValidationWarning)X.push({type:"other",message:this.modelValidationWarning});this.settingsValidationWarnings.forEach((G)=>{X.push({type:"other",message:G})});let q=IN(J);if(q)X.push({type:"other",message:q});return X}handleJsonExtraction(Y,J){let X=DN(Y),B=this.validateJsonExtraction(Y,X);if(!B.valid&&B.warning)J.push(B.warning);return X}createQueryOptions(Y){let J={model:this.getModel(),abortController:Y,resume:this.settings.resume??this.sessionId,pathToClaudeCodeExecutable:this.settings.pathToClaudeCodeExecutable,maxTurns:this.settings.maxTurns,maxThinkingTokens:this.settings.maxThinkingTokens,cwd:this.settings.cwd,executable:this.settings.executable,executableArgs:this.settings.executableArgs,permissionMode:this.settings.permissionMode,permissionPromptToolName:this.settings.permissionPromptToolName,continue:this.settings.continue,allowedTools:this.settings.allowedTools,disallowedTools:this.settings.disallowedTools,mcpServers:this.settings.mcpServers,canUseTool:this.settings.canUseTool};if(this.settings.systemPrompt!==void 0)J.systemPrompt=this.settings.systemPrompt;else if(this.settings.customSystemPrompt!==void 0)this.logger.warn("[claude-code] 'customSystemPrompt' is deprecated and will be removed in a future major release. Please use 'systemPrompt' instead (string or { type: 'preset', preset: 'claude_code', append? })."),J.systemPrompt=this.settings.customSystemPrompt;else if(this.settings.appendSystemPrompt!==void 0)this.logger.warn("[claude-code] 'appendSystemPrompt' is deprecated and will be removed in a future major release. Please use 'systemPrompt: { type: 'preset', preset: 'claude_code', append: <text> }' instead."),J.systemPrompt={type:"preset",preset:"claude_code",append:this.settings.appendSystemPrompt};if(this.settings.settingSources!==void 0)J.settingSources=this.settings.settingSources;if(this.settings.additionalDirectories!==void 0)J.additionalDirectories=this.settings.additionalDirectories;if(this.settings.agents!==void 0)J.agents=this.settings.agents;if(this.settings.includePartialMessages!==void 0)J.includePartialMessages=this.settings.includePartialMessages;if(this.settings.fallbackModel!==void 0)J.fallbackModel=this.settings.fallbackModel;if(this.settings.forkSession!==void 0)J.forkSession=this.settings.forkSession;if(this.settings.stderr!==void 0)J.stderr=this.settings.stderr;if(this.settings.strictMcpConfig!==void 0)J.strictMcpConfig=this.settings.strictMcpConfig;if(this.settings.extraArgs!==void 0)J.extraArgs=this.settings.extraArgs;if(this.settings.hooks)J.hooks=this.settings.hooks;if(this.settings.env!==void 0)J.env={...process.env,...this.settings.env};return J}handleClaudeCodeError(Y,J){if(tX(Y))throw Y;let X=(A)=>{return typeof A==="object"&&A!==null&&"message"in A},B=(A)=>{return typeof A==="object"&&A!==null},q=["not logged in","authentication","unauthorized","auth failed","please login","claude login"],G=X(Y)&&Y.message?Y.message.toLowerCase():"",H=B(Y)&&typeof Y.exitCode==="number"?Y.exitCode:void 0;if(q.some((A)=>G.includes(A))||H===401)return ON({message:X(Y)&&Y.message?Y.message:"Authentication failed. Please ensure Claude Code SDK is properly authenticated."});let z=B(Y)&&typeof Y.code==="string"?Y.code:"";if(z==="ETIMEDOUT"||G.includes("timeout"))return RN({message:X(Y)&&Y.message?Y.message:"Request timed out",promptExcerpt:J.substring(0,200)});let j=z==="ENOENT"||z==="ECONNREFUSED"||z==="ETIMEDOUT"||z==="ECONNRESET";return wN({message:X(Y)&&Y.message?Y.message:"Claude Code SDK error",code:z||void 0,exitCode:H,stderr:B(Y)&&typeof Y.stderr==="string"?Y.stderr:void 0,promptExcerpt:J.substring(0,200),isRetryable:j})}setSessionId(Y){this.sessionId=Y;let J=CN(Y);if(J)this.logger.warn(`Claude Code Session: ${J}`)}validateJsonExtraction(Y,J){if(J===Y)return{valid:!1,warning:{type:"other",message:"JSON extraction from model response may be incomplete or modified. The model may not have returned valid JSON."}};try{return JSON.parse(J),{valid:!0}}catch{return{valid:!1,warning:{type:"other",message:"JSON extraction resulted in invalid JSON. The response may be malformed."}}}}async doGenerate(Y){this.logger.debug(`[claude-code] Starting doGenerate request with model: ${this.modelId}`);let J=Y.responseFormat?.type==="json"?{type:"object-json"}:{type:"regular"};this.logger.debug(`[claude-code] Request mode: ${J.type}, response format: ${Y.responseFormat?.type??"none"}`);let{messagesPrompt:X,warnings:B,streamingContentParts:q,hasImageParts:G}=QW(Y.prompt,J,Y.responseFormat?.type==="json"?Y.responseFormat.schema:void 0);this.logger.debug(`[claude-code] Converted ${Y.prompt.length} messages, hasImageParts: ${G}`);let H=new AbortController,U;if(Y.abortSignal?.aborted)H.abort(Y.abortSignal.reason);else if(Y.abortSignal)U=()=>H.abort(Y.abortSignal?.reason),Y.abortSignal.addEventListener("abort",U,{once:!0});let z=this.createQueryOptions(H),j="",A={inputTokens:0,outputTokens:0,totalTokens:0},V="stop",F=!1,D,L,N,K=this.generateAllWarnings(Y,X);if(B)B.forEach((S)=>{K.push({type:"other",message:S})});let M=this.settings.streamingInput??"auto",w=M==="always"||M==="auto"&&!!this.settings.canUseTool;if(!w&&G)K.push({type:"other",message:GW});let _=()=>{},g=new Promise((S)=>{_=()=>S(void 0)});try{if(this.settings.canUseTool&&this.settings.permissionPromptToolName)throw Error("canUseTool requires streamingInput mode ('auto' or 'always') and cannot be used with permissionPromptToolName (SDK constraint). Set streamingInput: 'auto' (or 'always') and remove permissionPromptToolName, or remove canUseTool.");let S=w?BW(X,g,this.settings.resume??this.sessionId,q):X;this.logger.debug(`[claude-code] Executing query with streamingInput: ${w}, session: ${this.settings.resume??this.sessionId??"new"}`);let C=rX({prompt:S,options:z});for await(let T of C)if(this.logger.debug(`[claude-code] Received message type: ${T.type}`),T.type==="assistant")j+=T.message.content.map((b)=>b.type==="text"?b.text:"").join("");else if(T.type==="result"){if(_(),this.setSessionId(T.session_id),D=T.total_cost_usd,L=T.duration_ms,this.logger.info(`[claude-code] Request completed - Session: ${T.session_id}, Cost: $${D?.toFixed(4)??"N/A"}, Duration: ${L??"N/A"}ms`),"usage"in T)N=T.usage,A={inputTokens:(T.usage.cache_creation_input_tokens??0)+(T.usage.cache_read_input_tokens??0)+(T.usage.input_tokens??0),outputTokens:T.usage.output_tokens??0,totalTokens:(T.usage.cache_creation_input_tokens??0)+(T.usage.cache_read_input_tokens??0)+(T.usage.input_tokens??0)+(T.usage.output_tokens??0)},this.logger.debug(`[claude-code] Token usage - Input: ${A.inputTokens}, Output: ${A.outputTokens}, Total: ${A.totalTokens}`);V=XW(T.subtype),this.logger.debug(`[claude-code] Finish reason: ${V}`)}else if(T.type==="system"&&T.subtype==="init")this.setSessionId(T.session_id),this.logger.info(`[claude-code] Session initialized: ${T.session_id}`)}catch(S){if(_(),this.logger.debug(`[claude-code] Error during doGenerate: ${S instanceof Error?S.message:String(S)}`),tX(S))throw this.logger.debug("[claude-code] Request aborted by user"),Y.abortSignal?.aborted?Y.abortSignal.reason:S;if(WW(S,j))this.logger.warn(`[claude-code] Detected truncated response, returning ${j.length} characters of buffered text`),F=!0,V="length",K.push({type:"other",message:JW});else throw this.handleClaudeCodeError(S,X)}finally{if(Y.abortSignal&&U)Y.abortSignal.removeEventListener("abort",U)}if(Y.responseFormat?.type==="json"&&j)j=this.handleJsonExtraction(j,K);return{content:[{type:"text",text:j}],usage:A,finishReason:V,warnings:K,response:{id:U9(),timestamp:new Date,modelId:this.modelId},request:{body:X},providerMetadata:{"claude-code":{...this.sessionId!==void 0&&{sessionId:this.sessionId},...D!==void 0&&{costUsd:D},...L!==void 0&&{durationMs:L},...N!==void 0&&{rawUsage:N},...F&&{truncated:!0}}}}}async doStream(Y){this.logger.debug(`[claude-code] Starting doStream request with model: ${this.modelId}`);let J=Y.responseFormat?.type==="json"?{type:"object-json"}:{type:"regular"};this.logger.debug(`[claude-code] Stream mode: ${J.type}, response format: ${Y.responseFormat?.type??"none"}`);let{messagesPrompt:X,warnings:B,streamingContentParts:q,hasImageParts:G}=QW(Y.prompt,J,Y.responseFormat?.type==="json"?Y.responseFormat.schema:void 0);this.logger.debug(`[claude-code] Converted ${Y.prompt.length} messages for streaming, hasImageParts: ${G}`);let H=new AbortController,U;if(Y.abortSignal?.aborted)H.abort(Y.abortSignal.reason);else if(Y.abortSignal)U=()=>H.abort(Y.abortSignal?.reason),Y.abortSignal.addEventListener("abort",U,{once:!0});let z=this.createQueryOptions(H),j=this.generateAllWarnings(Y,X);if(B)B.forEach((D)=>{j.push({type:"other",message:D})});let A=this.settings.streamingInput??"auto",V=A==="always"||A==="auto"&&!!this.settings.canUseTool;if(!V&&G)j.push({type:"other",message:GW});return{stream:new ReadableStream({start:async(D)=>{let L=()=>{},N=new Promise((b)=>{L=()=>b(void 0)}),K=new Map,M=[],w=(b,k)=>{if(!k.inputClosed&&k.inputStarted)D.enqueue({type:"tool-input-end",id:b}),k.inputClosed=!0},_=(b,k)=>{if(k.callEmitted)return;w(b,k),D.enqueue({type:"tool-call",toolCallId:b,toolName:k.name,input:k.lastSerializedInput??"",providerExecuted:!0,dynamic:!0,providerMetadata:{"claude-code":{rawInput:k.lastSerializedInput??""}}}),k.callEmitted=!0},g=()=>{for(let[b,k]of K)_(b,k);K.clear()},S={inputTokens:0,outputTokens:0,totalTokens:0},C="",T;try{if(D.enqueue({type:"stream-start",warnings:j}),this.settings.canUseTool&&this.settings.permissionPromptToolName)throw Error("canUseTool requires streamingInput mode ('auto' or 'always') and cannot be used with permissionPromptToolName (SDK constraint). Set streamingInput: 'auto' (or 'always') and remove permissionPromptToolName, or remove canUseTool.");let b=V?BW(X,N,this.settings.resume??this.sessionId,q):X;this.logger.debug(`[claude-code] Starting stream query with streamingInput: ${V}, session: ${this.settings.resume??this.sessionId??"new"}`);let k=rX({prompt:b,options:z});for await(let I of k)if(this.logger.debug(`[claude-code] Stream received message type: ${I.type}`),I.type==="assistant"){if(!I.message?.content){this.logger.warn(`[claude-code] Unexpected assistant message structure: missing content field. Message type: ${I.type}. This may indicate an SDK protocol violation.`);continue}let E=I.message.content;for(let Z of this.extractToolUses(E)){let v=Z.id,y=K.get(v);if(!y)y={name:Z.name,inputStarted:!1,inputClosed:!1,callEmitted:!1},K.set(v,y),this.logger.debug(`[claude-code] New tool use detected - Tool: ${Z.name}, ID: ${v}`);if(y.name=Z.name,!y.inputStarted)this.logger.debug(`[claude-code] Tool input started - Tool: ${Z.name}, ID: ${v}`),D.enqueue({type:"tool-input-start",id:v,toolName:Z.name,providerExecuted:!0,dynamic:!0}),y.inputStarted=!0;let m=this.serializeToolInput(Z.input);if(m){let i="";if(y.lastSerializedInput===void 0){if(m.length<=Q.MAX_DELTA_CALC_SIZE)i=m}else if(m.length<=Q.MAX_DELTA_CALC_SIZE&&y.lastSerializedInput.length<=Q.MAX_DELTA_CALC_SIZE&&m.startsWith(y.lastSerializedInput))i=m.slice(y.lastSerializedInput.length);else if(m!==y.lastSerializedInput)i="";if(i)D.enqueue({type:"tool-input-delta",id:v,delta:i});y.lastSerializedInput=m}}let R=E.map((Z)=>Z.type==="text"?Z.text:"").join("");if(R){if(C+=R,Y.responseFormat?.type!=="json"){if(!T)T=U9(),D.enqueue({type:"text-start",id:T});D.enqueue({type:"text-delta",id:T,delta:R})}}}else if(I.type==="user"){if(!I.message?.content){this.logger.warn(`[claude-code] Unexpected user message structure: missing content field. Message type: ${I.type}. This may indicate an SDK protocol violation.`);continue}let E=I.message.content;for(let R of this.extractToolResults(E)){let Z=K.get(R.id),v=R.name??Z?.name??Q.UNKNOWN_TOOL_NAME;if(this.logger.debug(`[claude-code] Tool result received - Tool: ${v}, ID: ${R.id}`),!Z){if(this.logger.warn(`[claude-code] Received tool result for unknown tool ID: ${R.id}`),Z={name:v,inputStarted:!1,inputClosed:!1,callEmitted:!1},K.set(R.id,Z),!Z.inputStarted)D.enqueue({type:"tool-input-start",id:R.id,toolName:v,providerExecuted:!0,dynamic:!0}),Z.inputStarted=!0;if(!Z.inputClosed)D.enqueue({type:"tool-input-end",id:R.id}),Z.inputClosed=!0}Z.name=v;let y=this.normalizeToolResult(R.result),m=typeof R.result==="string"?R.result:(()=>{try{return JSON.stringify(R.result)}catch{return String(R.result)}})();_(R.id,Z),D.enqueue({type:"tool-result",toolCallId:R.id,toolName:v,result:y,isError:R.isError,providerExecuted:!0,dynamic:!0,providerMetadata:{"claude-code":{rawResult:m}}})}for(let R of this.extractToolErrors(E)){let Z=K.get(R.id),v=R.name??Z?.name??Q.UNKNOWN_TOOL_NAME;if(this.logger.debug(`[claude-code] Tool error received - Tool: ${v}, ID: ${R.id}`),!Z)this.logger.warn(`[claude-code] Received tool error for unknown tool ID: ${R.id}`),Z={name:v,inputStarted:!0,inputClosed:!0,callEmitted:!1},K.set(R.id,Z);_(R.id,Z);let y=typeof R.error==="string"?R.error:typeof R.error==="object"&&R.error!==null?(()=>{try{return JSON.stringify(R.error)}catch{return String(R.error)}})():String(R.error);D.enqueue({type:"tool-error",toolCallId:R.id,toolName:v,error:y,providerExecuted:!0,dynamic:!0,providerMetadata:{"claude-code":{rawError:y}}})}}else if(I.type==="result"){L(),this.logger.info(`[claude-code] Stream completed - Session: ${I.session_id}, Cost: $${I.total_cost_usd?.toFixed(4)??"N/A"}, Duration: ${I.duration_ms??"N/A"}ms`);let E;if("usage"in I)E=I.usage,S={inputTokens:(I.usage.cache_creation_input_tokens??0)+(I.usage.cache_read_input_tokens??0)+(I.usage.input_tokens??0),outputTokens:I.usage.output_tokens??0,totalTokens:(I.usage.cache_creation_input_tokens??0)+(I.usage.cache_read_input_tokens??0)+(I.usage.input_tokens??0)+(I.usage.output_tokens??0)},this.logger.debug(`[claude-code] Stream token usage - Input: ${S.inputTokens}, Output: ${S.outputTokens}, Total: ${S.totalTokens}`);let R=XW(I.subtype);if(this.logger.debug(`[claude-code] Stream finish reason: ${R}`),this.setSessionId(I.session_id),Y.responseFormat?.type==="json"&&C){let v=this.handleJsonExtraction(C,M),y=U9();D.enqueue({type:"text-start",id:y}),D.enqueue({type:"text-delta",id:y,delta:v}),D.enqueue({type:"text-end",id:y})}else if(T)D.enqueue({type:"text-end",id:T});g();let Z=this.serializeWarningsForMetadata(M);D.enqueue({type:"finish",finishReason:R,usage:S,providerMetadata:{"claude-code":{sessionId:I.session_id,...I.total_cost_usd!==void 0&&{costUsd:I.total_cost_usd},...I.duration_ms!==void 0&&{durationMs:I.duration_ms},...E!==void 0&&{rawUsage:E},...M.length>0&&{warnings:Z}}}})}else if(I.type==="system"&&I.subtype==="init")this.setSessionId(I.session_id),this.logger.info(`[claude-code] Stream session initialized: ${I.session_id}`),D.enqueue({type:"response-metadata",id:I.session_id,timestamp:new Date,modelId:this.modelId});g(),this.logger.debug("[claude-code] Stream finalized, closing stream"),D.close()}catch(b){if(L(),this.logger.debug(`[claude-code] Error during doStream: ${b instanceof Error?b.message:String(b)}`),WW(b,C)){this.logger.warn(`[claude-code] Detected truncated stream response, returning ${C.length} characters of buffered text`);let I={type:"other",message:JW};M.push(I);let E=()=>{let Z=this.handleJsonExtraction(C,M),v=U9();D.enqueue({type:"text-start",id:v}),D.enqueue({type:"text-delta",id:v,delta:Z}),D.enqueue({type:"text-end",id:v})};if(Y.responseFormat?.type==="json")E();else if(T)D.enqueue({type:"text-end",id:T});else if(C){let Z=U9();D.enqueue({type:"text-start",id:Z}),D.enqueue({type:"text-delta",id:Z,delta:C}),D.enqueue({type:"text-end",id:Z})}g();let R=this.serializeWarningsForMetadata(M);D.enqueue({type:"finish",finishReason:"length",usage:S,providerMetadata:{"claude-code":{...this.sessionId!==void 0&&{sessionId:this.sessionId},truncated:!0,...M.length>0&&{warnings:R}}}}),D.close();return}g();let k;if(tX(b))k=Y.abortSignal?.aborted?Y.abortSignal.reason:b;else k=this.handleClaudeCodeError(b,X);D.enqueue({type:"error",error:k}),D.close()}finally{if(Y.abortSignal&&U)Y.abortSignal.removeEventListener("abort",U)}},cancel:()=>{if(Y.abortSignal&&U)Y.abortSignal.removeEventListener("abort",U)}}),request:{body:X}}}serializeWarningsForMetadata(Y){return Y.map((X)=>{let B={type:X.type};if("message"in X){let q=X.message;if(q!==void 0)B.message=String(q)}if(X.type==="unsupported-setting"){let q=X.setting;if(q!==void 0)B.setting=String(q);if("details"in X){let G=X.details;if(G!==void 0)B.details=String(G)}}return B})}};function gN(Q={}){let Y=HW(Q.defaultSettings?.logger);if(Q.defaultSettings){let B=YW(Q.defaultSettings);if(!B.valid)throw Error(`Invalid default settings: ${B.errors.join(", ")}`);if(B.warnings.length>0)B.warnings.forEach((q)=>Y.warn(`Claude Code Provider: ${q}`))}let J=(B,q={})=>{let G={...Q.defaultSettings,...q},H=YW(G);if(!H.valid)throw Error(`Invalid settings: ${H.errors.join(", ")}`);return new xN({id:B,settings:G,settingsValidationWarnings:H.warnings})},X=function(B,q){if(new.target)throw Error("The Claude Code model function cannot be called with the new keyword.");return J(B,q)};return X.languageModel=J,X.chat=J,X.textEmbeddingModel=(B)=>{throw new M9({modelId:B,modelType:"textEmbeddingModel"})},X.imageModel=(B)=>{throw new M9({modelId:B,modelType:"imageModel"})},X}var zW=gN();class Q6{id="claude-code";name="Claude Code";getConfigSchema(){return[{key:"authenticated",label:"Authenticated",type:"boolean",required:!1,description:"Authentication is handled via Claude CLI"}]}isConfigured(Q){return!0}async fetchModels(Q){return[{id:"opus",name:"Claude 4.1 Opus (Most Capable)"},{id:"sonnet",name:"Claude 4.5 Sonnet (Balanced)"},{id:"haiku",name:"Claude 4.5 Haiku (Fastest)"}]}async getModelDetails(Q,Y){return{opus:{contextLength:200000,maxOutput:4096,inputPrice:0,outputPrice:0},sonnet:{contextLength:200000,maxOutput:8192,inputPrice:0,outputPrice:0},haiku:{contextLength:200000,maxOutput:4096,inputPrice:0,outputPrice:0}}[Q]||null}createClient(Q,Y){return zW(Y)}}function zQ(Q){var Y,J;return(J=(Y=Q==null?void 0:Q.providerOptions)==null?void 0:Y.openaiCompatible)!=null?J:{}}function yN(Q){let Y=[];for(let{role:J,content:X,...B}of Q){let q=zQ({...B});switch(J){case"system":{Y.push({role:"system",content:X,...q});break}case"user":{if(X.length===1&&X[0].type==="text"){Y.push({role:"user",content:X[0].text,...zQ(X[0])});break}Y.push({role:"user",content:X.map((G)=>{let H=zQ(G);switch(G.type){case"text":return{type:"text",text:G.text,...H};case"file":if(G.mediaType.startsWith("image/")){let U=G.mediaType==="image/*"?"image/jpeg":G.mediaType;return{type:"image_url",image_url:{url:G.data instanceof URL?G.data.toString():`data:${U};base64,${F1(G.data)}`},...H}}else throw new I0({functionality:`file part media type ${G.mediaType}`})}}),...q});break}case"assistant":{let G="",H=[];for(let U of X){let z=zQ(U);switch(U.type){case"text":{G+=U.text;break}case"tool-call":{H.push({id:U.toolCallId,type:"function",function:{name:U.toolName,arguments:JSON.stringify(U.input)},...z});break}}}Y.push({role:"assistant",content:G,tool_calls:H.length>0?H:void 0,...q});break}case"tool":{for(let G of X){let H=G.output,U;switch(H.type){case"text":case"error-text":U=H.value;break;case"content":case"json":case"error-json":U=JSON.stringify(H.value);break}let z=zQ(G);Y.push({role:"tool",tool_call_id:G.toolCallId,content:U,...z})}break}default:throw Error(`Unsupported role: ${J}`)}}return Y}function UW({id:Q,model:Y,created:J}){return{id:Q!=null?Q:void 0,modelId:Y!=null?Y:void 0,timestamp:J!=null?new Date(J*1000):void 0}}function LW(Q){switch(Q){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 X6=W.object({user:W.string().optional(),reasoningEffort:W.string().optional(),textVerbosity:W.string().optional()}),$N=W.object({error:W.object({message:W.string(),type:W.string().nullish(),param:W.any().nullish(),code:W.union([W.string(),W.number()]).nullish()})}),aQ={errorSchema:$N,errorToMessage:(Q)=>Q.error.message};function fN({tools:Q,toolChoice:Y}){Q=(Q==null?void 0:Q.length)?Q:void 0;let J=[];if(Q==null)return{tools:void 0,toolChoice:void 0,toolWarnings:J};let X=[];for(let q of Q)if(q.type==="provider-defined")J.push({type:"unsupported-tool",tool:q});else X.push({type:"function",function:{name:q.name,description:q.description,parameters:q.inputSchema}});if(Y==null)return{tools:X,toolChoice:void 0,toolWarnings:J};let B=Y.type;switch(B){case"auto":case"none":case"required":return{tools:X,toolChoice:B,toolWarnings:J};case"tool":return{tools:X,toolChoice:{type:"function",function:{name:Y.toolName}},toolWarnings:J};default:throw new I0({functionality:`tool choice type: ${B}`})}}var hN=class{constructor(Q,Y){this.specificationVersion="v2";var J,X;this.modelId=Q,this.config=Y;let B=(J=Y.errorStructure)!=null?J:aQ;this.chunkSchema=uN(B.errorSchema),this.failedResponseHandler=V1(B),this.supportsStructuredOutputs=(X=Y.supportsStructuredOutputs)!=null?X:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var Q,Y,J;return(J=(Y=(Q=this.config).supportedUrls)==null?void 0:Y.call(Q))!=null?J:{}}async getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,topK:B,frequencyPenalty:q,presencePenalty:G,providerOptions:H,stopSequences:U,responseFormat:z,seed:j,toolChoice:A,tools:V}){var F,D,L,N;let K=[],M=Object.assign((F=await k0({provider:"openai-compatible",providerOptions:H,schema:X6}))!=null?F:{},(D=await k0({provider:this.providerOptionsName,providerOptions:H,schema:X6}))!=null?D:{});if(B!=null)K.push({type:"unsupported-setting",setting:"topK"});if((z==null?void 0:z.type)==="json"&&z.schema!=null&&!this.supportsStructuredOutputs)K.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let{tools:w,toolChoice:_,toolWarnings:g}=fN({tools:V,toolChoice:A});return{args:{model:this.modelId,user:M.user,max_tokens:Y,temperature:J,top_p:X,frequency_penalty:q,presence_penalty:G,response_format:(z==null?void 0:z.type)==="json"?this.supportsStructuredOutputs===!0&&z.schema!=null?{type:"json_schema",json_schema:{schema:z.schema,name:(L=z.name)!=null?L:"response",description:z.description}}:{type:"json_object"}:void 0,stop:U,seed:j,...Object.fromEntries(Object.entries((N=H==null?void 0:H[this.providerOptionsName])!=null?N:{}).filter(([S])=>!Object.keys(X6.shape).includes(S))),reasoning_effort:M.reasoningEffort,verbosity:M.textVerbosity,messages:yN(Q),tools:w,tool_choice:_},warnings:[...K,...g]}}async doGenerate(Q){var Y,J,X,B,q,G,H,U,z,j,A,V,F,D,L,N,K;let{args:M,warnings:w}=await this.getArgs({...Q}),_=JSON.stringify(M),{responseHeaders:g,value:S,rawValue:C}=await T0({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:M,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:m0(mN),abortSignal:Q.abortSignal,fetch:this.config.fetch}),T=S.choices[0],b=[],k=T.message.content;if(k!=null&&k.length>0)b.push({type:"text",text:k});let I=(Y=T.message.reasoning_content)!=null?Y:T.message.reasoning;if(I!=null&&I.length>0)b.push({type:"reasoning",text:I});if(T.message.tool_calls!=null)for(let Z of T.message.tool_calls)b.push({type:"tool-call",toolCallId:(J=Z.id)!=null?J:s0(),toolName:Z.function.name,input:Z.function.arguments});let E={[this.providerOptionsName]:{},...await((B=(X=this.config.metadataExtractor)==null?void 0:X.extractMetadata)==null?void 0:B.call(X,{parsedBody:C}))},R=(q=S.usage)==null?void 0:q.completion_tokens_details;if((R==null?void 0:R.accepted_prediction_tokens)!=null)E[this.providerOptionsName].acceptedPredictionTokens=R==null?void 0:R.accepted_prediction_tokens;if((R==null?void 0:R.rejected_prediction_tokens)!=null)E[this.providerOptionsName].rejectedPredictionTokens=R==null?void 0:R.rejected_prediction_tokens;return{content:b,finishReason:LW(T.finish_reason),usage:{inputTokens:(H=(G=S.usage)==null?void 0:G.prompt_tokens)!=null?H:void 0,outputTokens:(z=(U=S.usage)==null?void 0:U.completion_tokens)!=null?z:void 0,totalTokens:(A=(j=S.usage)==null?void 0:j.total_tokens)!=null?A:void 0,reasoningTokens:(D=(F=(V=S.usage)==null?void 0:V.completion_tokens_details)==null?void 0:F.reasoning_tokens)!=null?D:void 0,cachedInputTokens:(K=(N=(L=S.usage)==null?void 0:L.prompt_tokens_details)==null?void 0:N.cached_tokens)!=null?K:void 0},providerMetadata:E,request:{body:_},response:{...UW(S),headers:g,body:C},warnings:w}}async doStream(Q){var Y;let{args:J,warnings:X}=await this.getArgs({...Q}),B={...J,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},q=(Y=this.config.metadataExtractor)==null?void 0:Y.createStreamExtractor(),{responseHeaders:G,value:H}=await T0({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:B,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:D1(this.chunkSchema),abortSignal:Q.abortSignal,fetch:this.config.fetch}),U=[],z="unknown",j={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0},A=!0,V=this.providerOptionsName,F=!1,D=!1;return{stream:H.pipeThrough(new TransformStream({start(L){L.enqueue({type:"stream-start",warnings:X})},transform(L,N){var K,M,w,_,g,S,C,T,b,k,I,E,R;if(Q.includeRawChunks)N.enqueue({type:"raw",rawValue:L.rawValue});if(!L.success){z="error",N.enqueue({type:"error",error:L.error});return}let Z=L.value;if(q==null||q.processChunk(L.rawValue),"error"in Z){z="error",N.enqueue({type:"error",error:Z.error.message});return}if(A)A=!1,N.enqueue({type:"response-metadata",...UW(Z)});if(Z.usage!=null){let{prompt_tokens:i,completion_tokens:l,total_tokens:r,prompt_tokens_details:d,completion_tokens_details:t}=Z.usage;if(j.promptTokens=i!=null?i:void 0,j.completionTokens=l!=null?l:void 0,j.totalTokens=r!=null?r:void 0,(t==null?void 0:t.reasoning_tokens)!=null)j.completionTokensDetails.reasoningTokens=t==null?void 0:t.reasoning_tokens;if((t==null?void 0:t.accepted_prediction_tokens)!=null)j.completionTokensDetails.acceptedPredictionTokens=t==null?void 0:t.accepted_prediction_tokens;if((t==null?void 0:t.rejected_prediction_tokens)!=null)j.completionTokensDetails.rejectedPredictionTokens=t==null?void 0:t.rejected_prediction_tokens;if((d==null?void 0:d.cached_tokens)!=null)j.promptTokensDetails.cachedTokens=d==null?void 0:d.cached_tokens}let v=Z.choices[0];if((v==null?void 0:v.finish_reason)!=null)z=LW(v.finish_reason);if((v==null?void 0:v.delta)==null)return;let y=v.delta,m=(K=y.reasoning_content)!=null?K:y.reasoning;if(m){if(!F)N.enqueue({type:"reasoning-start",id:"reasoning-0"}),F=!0;N.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:m})}if(y.content){if(!D)N.enqueue({type:"text-start",id:"txt-0"}),D=!0;N.enqueue({type:"text-delta",id:"txt-0",delta:y.content})}if(y.tool_calls!=null)for(let i of y.tool_calls){let l=i.index;if(U[l]==null){if(i.id==null)throw new _9({data:i,message:"Expected 'id' to be a string."});if(((M=i.function)==null?void 0:M.name)==null)throw new _9({data:i,message:"Expected 'function.name' to be a string."});N.enqueue({type:"tool-input-start",id:i.id,toolName:i.function.name}),U[l]={id:i.id,type:"function",function:{name:i.function.name,arguments:(w=i.function.arguments)!=null?w:""},hasFinished:!1};let d=U[l];if(((_=d.function)==null?void 0:_.name)!=null&&((g=d.function)==null?void 0:g.arguments)!=null){if(d.function.arguments.length>0)N.enqueue({type:"tool-input-delta",id:d.id,delta:d.function.arguments});if(W8(d.function.arguments))N.enqueue({type:"tool-input-end",id:d.id}),N.enqueue({type:"tool-call",toolCallId:(S=d.id)!=null?S:s0(),toolName:d.function.name,input:d.function.arguments}),d.hasFinished=!0}continue}let r=U[l];if(r.hasFinished)continue;if(((C=i.function)==null?void 0:C.arguments)!=null)r.function.arguments+=(b=(T=i.function)==null?void 0:T.arguments)!=null?b:"";if(N.enqueue({type:"tool-input-delta",id:r.id,delta:(k=i.function.arguments)!=null?k:""}),((I=r.function)==null?void 0:I.name)!=null&&((E=r.function)==null?void 0:E.arguments)!=null&&W8(r.function.arguments))N.enqueue({type:"tool-input-end",id:r.id}),N.enqueue({type:"tool-call",toolCallId:(R=r.id)!=null?R:s0(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0}},flush(L){var N,K,M,w,_,g;if(F)L.enqueue({type:"reasoning-end",id:"reasoning-0"});if(D)L.enqueue({type:"text-end",id:"txt-0"});for(let C of U.filter((T)=>!T.hasFinished))L.enqueue({type:"tool-input-end",id:C.id}),L.enqueue({type:"tool-call",toolCallId:(N=C.id)!=null?N:s0(),toolName:C.function.name,input:C.function.arguments});let S={[V]:{},...q==null?void 0:q.buildMetadata()};if(j.completionTokensDetails.acceptedPredictionTokens!=null)S[V].acceptedPredictionTokens=j.completionTokensDetails.acceptedPredictionTokens;if(j.completionTokensDetails.rejectedPredictionTokens!=null)S[V].rejectedPredictionTokens=j.completionTokensDetails.rejectedPredictionTokens;L.enqueue({type:"finish",finishReason:z,usage:{inputTokens:(K=j.promptTokens)!=null?K:void 0,outputTokens:(M=j.completionTokens)!=null?M:void 0,totalTokens:(w=j.totalTokens)!=null?w:void 0,reasoningTokens:(_=j.completionTokensDetails.reasoningTokens)!=null?_:void 0,cachedInputTokens:(g=j.promptTokensDetails.cachedTokens)!=null?g:void 0},providerMetadata:S})}})),request:{body:B},response:{headers:G}}}},KW=W.object({prompt_tokens:W.number().nullish(),completion_tokens:W.number().nullish(),total_tokens:W.number().nullish(),prompt_tokens_details:W.object({cached_tokens:W.number().nullish()}).nullish(),completion_tokens_details:W.object({reasoning_tokens:W.number().nullish(),accepted_prediction_tokens:W.number().nullish(),rejected_prediction_tokens:W.number().nullish()}).nullish()}).nullish(),mN=W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({message:W.object({role:W.literal("assistant").nullish(),content:W.string().nullish(),reasoning_content:W.string().nullish(),reasoning:W.string().nullish(),tool_calls:W.array(W.object({id:W.string().nullish(),function:W.object({name:W.string(),arguments:W.string()})})).nullish()}),finish_reason:W.string().nullish()})),usage:KW}),uN=(Q)=>W.union([W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({delta:W.object({role:W.enum(["assistant"]).nullish(),content:W.string().nullish(),reasoning_content:W.string().nullish(),reasoning:W.string().nullish(),tool_calls:W.array(W.object({index:W.number(),id:W.string().nullish(),function:W.object({name:W.string().nullish(),arguments:W.string().nullish()})})).nullish()}).nullish(),finish_reason:W.string().nullish()})),usage:KW}),Q]);function cN({prompt:Q,user:Y="user",assistant:J="assistant"}){let X="";if(Q[0].role==="system")X+=`${Q[0].content}
74
-
75
- `,Q=Q.slice(1);for(let{role:B,content:q}of Q)switch(B){case"system":throw new jQ({message:"Unexpected system message in prompt: ${content}",prompt:Q});case"user":{let G=q.map((H)=>{switch(H.type){case"text":return H.text}}).filter(Boolean).join("");X+=`${Y}:
76
- ${G}
77
-
78
- `;break}case"assistant":{let G=q.map((H)=>{switch(H.type){case"text":return H.text;case"tool-call":throw new I0({functionality:"tool-call messages"})}}).join("");X+=`${J}:
79
- ${G}
80
-
81
- `;break}case"tool":throw new I0({functionality:"tool messages"});default:throw Error(`Unsupported role: ${B}`)}return X+=`${J}:
82
- `,{prompt:X,stopSequences:[`
83
- ${Y}:`]}}function FW({id:Q,model:Y,created:J}){return{id:Q!=null?Q:void 0,modelId:Y!=null?Y:void 0,timestamp:J!=null?new Date(J*1000):void 0}}function NW(Q){switch(Q){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 dN=W.object({echo:W.boolean().optional(),logitBias:W.record(W.string(),W.number()).optional(),suffix:W.string().optional(),user:W.string().optional()}),lN=class{constructor(Q,Y){this.specificationVersion="v2";var J;this.modelId=Q,this.config=Y;let X=(J=Y.errorStructure)!=null?J:aQ;this.chunkSchema=nN(X.errorSchema),this.failedResponseHandler=V1(X)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var Q,Y,J;return(J=(Y=(Q=this.config).supportedUrls)==null?void 0:Y.call(Q))!=null?J:{}}async getArgs({prompt:Q,maxOutputTokens:Y,temperature:J,topP:X,topK:B,frequencyPenalty:q,presencePenalty:G,stopSequences:H,responseFormat:U,seed:z,providerOptions:j,tools:A,toolChoice:V}){var F;let D=[],L=(F=await k0({provider:this.providerOptionsName,providerOptions:j,schema:dN}))!=null?F:{};if(B!=null)D.push({type:"unsupported-setting",setting:"topK"});if(A==null?void 0:A.length)D.push({type:"unsupported-setting",setting:"tools"});if(V!=null)D.push({type:"unsupported-setting",setting:"toolChoice"});if(U!=null&&U.type!=="text")D.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:N,stopSequences:K}=cN({prompt:Q}),M=[...K!=null?K:[],...H!=null?H:[]];return{args:{model:this.modelId,echo:L.echo,logit_bias:L.logitBias,suffix:L.suffix,user:L.user,max_tokens:Y,temperature:J,top_p:X,frequency_penalty:q,presence_penalty:G,seed:z,...j==null?void 0:j[this.providerOptionsName],prompt:N,stop:M.length>0?M:void 0},warnings:D}}async doGenerate(Q){var Y,J,X,B,q,G;let{args:H,warnings:U}=await this.getArgs(Q),{responseHeaders:z,value:j,rawValue:A}=await T0({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:H,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:m0(pN),abortSignal:Q.abortSignal,fetch:this.config.fetch}),V=j.choices[0],F=[];if(V.text!=null&&V.text.length>0)F.push({type:"text",text:V.text});return{content:F,usage:{inputTokens:(J=(Y=j.usage)==null?void 0:Y.prompt_tokens)!=null?J:void 0,outputTokens:(B=(X=j.usage)==null?void 0:X.completion_tokens)!=null?B:void 0,totalTokens:(G=(q=j.usage)==null?void 0:q.total_tokens)!=null?G:void 0},finishReason:NW(V.finish_reason),request:{body:H},response:{...FW(j),headers:z,body:A},warnings:U}}async doStream(Q){let{args:Y,warnings:J}=await this.getArgs(Q),X={...Y,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:B,value:q}=await T0({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:b0(this.config.headers(),Q.headers),body:X,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:D1(this.chunkSchema),abortSignal:Q.abortSignal,fetch:this.config.fetch}),G="unknown",H={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},U=!0;return{stream:q.pipeThrough(new TransformStream({start(z){z.enqueue({type:"stream-start",warnings:J})},transform(z,j){var A,V,F;if(Q.includeRawChunks)j.enqueue({type:"raw",rawValue:z.rawValue});if(!z.success){G="error",j.enqueue({type:"error",error:z.error});return}let D=z.value;if("error"in D){G="error",j.enqueue({type:"error",error:D.error});return}if(U)U=!1,j.enqueue({type:"response-metadata",...FW(D)}),j.enqueue({type:"text-start",id:"0"});if(D.usage!=null)H.inputTokens=(A=D.usage.prompt_tokens)!=null?A:void 0,H.outputTokens=(V=D.usage.completion_tokens)!=null?V:void 0,H.totalTokens=(F=D.usage.total_tokens)!=null?F:void 0;let L=D.choices[0];if((L==null?void 0:L.finish_reason)!=null)G=NW(L.finish_reason);if((L==null?void 0:L.text)!=null)j.enqueue({type:"text-delta",id:"0",delta:L.text})},flush(z){if(!U)z.enqueue({type:"text-end",id:"0"});z.enqueue({type:"finish",finishReason:G,usage:H})}})),request:{body:X},response:{headers:B}}}},MW=W.object({prompt_tokens:W.number(),completion_tokens:W.number(),total_tokens:W.number()}),pN=W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({text:W.string(),finish_reason:W.string()})),usage:MW.nullish()}),nN=(Q)=>W.union([W.object({id:W.string().nullish(),created:W.number().nullish(),model:W.string().nullish(),choices:W.array(W.object({text:W.string(),finish_reason:W.string().nullish(),index:W.number()})),usage:MW.nullish()}),Q]),jW=W.object({dimensions:W.number().optional(),user:W.string().optional()}),iN=class{constructor(Q,Y){this.specificationVersion="v2",this.modelId=Q,this.config=Y}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var Q;return(Q=this.config.maxEmbeddingsPerCall)!=null?Q:2048}get supportsParallelCalls(){var Q;return(Q=this.config.supportsParallelCalls)!=null?Q:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:Q,headers:Y,abortSignal:J,providerOptions:X}){var B,q,G;let H=Object.assign((B=await k0({provider:"openai-compatible",providerOptions:X,schema:jW}))!=null?B:{},(q=await k0({provider:this.providerOptionsName,providerOptions:X,schema:jW}))!=null?q:{});if(Q.length>this.maxEmbeddingsPerCall)throw new s9({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Q});let{responseHeaders:U,value:z,rawValue:j}=await T0({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:b0(this.config.headers(),Y),body:{model:this.modelId,input:Q,encoding_format:"float",dimensions:H.dimensions,user:H.user},failedResponseHandler:V1((G=this.config.errorStructure)!=null?G:aQ),successfulResponseHandler:m0(aN),abortSignal:J,fetch:this.config.fetch});return{embeddings:z.data.map((A)=>A.embedding),usage:z.usage?{tokens:z.usage.prompt_tokens}:void 0,providerMetadata:z.providerMetadata,response:{headers:U,body:j}}}},aN=W.object({data:W.array(W.object({embedding:W.array(W.number())})),usage:W.object({prompt_tokens:W.number()}).nullish(),providerMetadata:W.record(W.string(),W.record(W.string(),W.any())).optional()}),sN=class{constructor(Q,Y){this.modelId=Q,this.config=Y,this.specificationVersion="v2",this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:Y,size:J,aspectRatio:X,seed:B,providerOptions:q,headers:G,abortSignal:H}){var U,z,j,A,V;let F=[];if(X!=null)F.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."});if(B!=null)F.push({type:"unsupported-setting",setting:"seed"});let D=(j=(z=(U=this.config._internal)==null?void 0:U.currentDate)==null?void 0:z.call(U))!=null?j:new Date,{value:L,responseHeaders:N}=await T0({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:b0(this.config.headers(),G),body:{model:this.modelId,prompt:Q,n:Y,size:J,...(A=q.openai)!=null?A:{},response_format:"b64_json"},failedResponseHandler:V1((V=this.config.errorStructure)!=null?V:aQ),successfulResponseHandler:m0(oN),abortSignal:H,fetch:this.config.fetch});return{images:L.data.map((K)=>K.b64_json),warnings:F,response:{timestamp:D,modelId:this.modelId,headers:N}}}},oN=W.object({data:W.array(W.object({b64_json:W.string()}))}),rN="1.0.25";function AW(Q){let Y=w9(Q.baseURL),J=Q.name,X={...Q.apiKey&&{Authorization:`Bearer ${Q.apiKey}`},...Q.headers},B=()=>i1(X,`ai-sdk/openai-compatible/${rN}`),q=(V)=>({provider:`${J}.${V}`,url:({path:F})=>{let D=new URL(`${Y}${F}`);if(Q.queryParams)D.search=new URLSearchParams(Q.queryParams).toString();return D.toString()},headers:B,fetch:Q.fetch}),G=(V)=>H(V),H=(V)=>new hN(V,{...q("chat"),includeUsage:Q.includeUsage,supportsStructuredOutputs:Q.supportsStructuredOutputs}),U=(V)=>new lN(V,{...q("completion"),includeUsage:Q.includeUsage}),z=(V)=>new iN(V,{...q("embedding")}),j=(V)=>new sN(V,q("image")),A=(V)=>G(V);return A.languageModel=G,A.chatModel=H,A.completionModel=U,A.textEmbeddingModel=z,A.imageModel=j,A}class Y6{id="zai";name="Z.ai";getConfigSchema(){return[{key:"api-key",label:"API Key",type:"string",required:!0,secret:!0,description:"Get your API key from Z.ai",placeholder:"zai-..."},{key:"coding-plan",label:"Coding Plan",type:"boolean",required:!1,description:"Enable Coding Plan mode (uses different API endpoint)"}]}isConfigured(Q){return!!Q["api-key"]}async fetchModels(Q){let Y=Q["api-key"],J=Q["coding-plan"];if(!Y)throw Error("API key is required to fetch Z.ai models");let B=await fetch(`${J?"https://api.z.ai/api/coding/paas/v4":"https://api.z.ai/api/paas/v4"}/models`,{headers:{Authorization:`Bearer ${Y}`},signal:AbortSignal.timeout(1e4)});if(!B.ok)throw Error(`Z.ai API returned ${B.status}: ${B.statusText}`);let q=await B.json();if(!q.data||q.data.length===0)throw Error("No models returned from Z.ai API");return q.data.map((G)=>({id:G.id,name:G.name||G.id}))}async getModelDetails(Q,Y){return{"glm-4.6":{contextLength:128000,maxOutput:4096,inputPrice:0,outputPrice:0},"glm-4-flash":{contextLength:128000,maxOutput:4096,inputPrice:0,outputPrice:0},"glm-4-plus":{contextLength:128000,maxOutput:4096,inputPrice:0,outputPrice:0},"glm-4-air":{contextLength:128000,maxOutput:4096,inputPrice:0,outputPrice:0}}[Q]||null}createClient(Q,Y){let J=Q["api-key"],B=Q["coding-plan"]?"https://api.z.ai/api/coding/paas/v4/":"https://api.z.ai/api/paas/v4/";return AW({baseURL:B,apiKey:J,name:"zai"})(Y)}}var J6={anthropic:new AX,openai:new DX,google:new OX,openrouter:new _X,"claude-code":new Q6,zai:new Y6};function Pw(Q){let Y=J6[Q];if(!Y)throw Error(`Unknown provider: ${Q}`);return Y}function Sw(){return Object.keys(J6)}function Iw(){let Q={};for(let[Y,J]of Object.entries(J6))Q[Y]={id:Y,name:J.name};return Q}export{Pw as getProvider,Iw as getAllProviders,Sw as getAllProviderIds,J6 as PROVIDER_REGISTRY};
84
- export{Q1 as L,a0 as M,P6 as N,jQ as O,M9 as P,b0 as Q,ZK as R,T4 as S,s0 as T,PK as U,a8 as V,LY as W,i1 as X,CK as Y,bK as Z,PQ as _,d0 as $,q1 as aa,NX as ba,jY as ca,T0 as da,AY as ea,H9 as fa,V1 as ga,D1 as ha,m0 as ia,p as ja,uK as ka,ZY as la,f2 as ma,w9 as na,cK as oa,Pw as pa,Iw as qa};
85
-
86
- //# debugId=9DC65A20F8D83B8064756E2164756E21