binja 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,26 +1,166 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import*as X from"fs";import*as Y from"path";var P={and:"AND",or:"OR",not:"NOT",true:"NAME",false:"NAME",True:"NAME",False:"NAME",None:"NAME",none:"NAME",is:"NAME",in:"NAME"};var x={red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m"},p=process.stdout?.isTTY!==!1;function q(A,B){return p?`${x[A]}${B}${x.reset}`:B}class I extends Error{line;column;source;templateName;suggestion;constructor(A,B){let R=v("TemplateSyntaxError",A,B);super(R);this.name="TemplateSyntaxError",this.line=B.line,this.column=B.column,this.source=B.source,this.templateName=B.templateName,this.suggestion=B.suggestion}}function v(A,B,R){let O=[],K=R.templateName?`${R.templateName}:${R.line}:${R.column}`:`line ${R.line}, column ${R.column}`;if(O.push(`${q("red",q("bold",A))}: ${B} at ${q("cyan",K)}`),R.source)O.push(""),O.push(d(R.source,R.line,R.column));if(R.suggestion)O.push(""),O.push(`${q("yellow","Did you mean")}: ${q("cyan",R.suggestion)}?`);if(R.availableOptions&&R.availableOptions.length>0){O.push("");let Q=R.availableOptions.slice(0,8),M=R.availableOptions.length>8?` ${q("gray",`... and ${R.availableOptions.length-8} more`)}`:"";O.push(`${q("gray","Available")}: ${Q.join(", ")}${M}`)}return O.join(`
4
- `)}function d(A,B,R){let O=A.split(`
5
- `),K=[],Q=Math.max(1,B-2),M=Math.min(O.length,B+1),$=String(M).length;for(let Z=Q;Z<=M;Z++){let U=O[Z-1]||"",G=String(Z).padStart($," ");if(Z===B){K.push(`${q("red"," \u2192")} ${q("gray",G)} ${q("dim","\u2502")} ${U}`);let H=" ".repeat($+4+Math.max(0,R-1)),z=q("red","^");K.push(`${H}${z}`)}else K.push(` ${q("gray",G)} ${q("dim","\u2502")} ${q("gray",U)}`)}return K.join(`
6
- `)}class D{state;variableStart;variableEnd;blockStart;blockEnd;commentStart;commentEnd;constructor(A,B={}){this.state={source:A,pos:0,line:1,column:1,tokens:[]},this.variableStart=B.variableStart??"{{",this.variableEnd=B.variableEnd??"}}",this.blockStart=B.blockStart??"{%",this.blockEnd=B.blockEnd??"%}",this.commentStart=B.commentStart??"{#",this.commentEnd=B.commentEnd??"#}"}tokenize(){while(!this.isAtEnd())this.scanToken();return this.addToken("EOF",""),this.state.tokens}scanToken(){if(this.match(this.variableStart)){this.addToken("VARIABLE_START",this.variableStart),this.scanExpression(this.variableEnd,"VARIABLE_END");return}if(this.match(this.blockStart)){let A=this.peek()==="-";if(A)this.advance();let B=this.state.pos;if(this.skipWhitespace(),this.checkWord("raw")||this.checkWord("verbatim")){let R=this.checkWord("raw")?"raw":"verbatim";this.scanRawBlock(R,A);return}this.state.pos=B,this.addToken("BLOCK_START",this.blockStart+(A?"-":"")),this.scanExpression(this.blockEnd,"BLOCK_END");return}if(this.match(this.commentStart)){this.scanComment();return}this.scanText()}checkWord(A){let B=this.state.pos;for(let O=0;O<A.length;O++)if(this.state.source[B+O]?.toLowerCase()!==A[O])return!1;let R=this.state.source[B+A.length];return!R||!this.isAlphaNumeric(R)}scanRawBlock(A,B){let R=this.state.line,O=this.state.column;for(let M=0;M<A.length;M++)this.advance();if(this.skipWhitespace(),this.peek()==="-")this.advance();if(!this.match(this.blockEnd))throw new I(`Expected '${this.blockEnd}' after '${A}'`,{line:this.state.line,column:this.state.column,source:this.state.source});let K=`end${A}`,Q=this.state.pos;while(!this.isAtEnd()){if(this.check(this.blockStart)){let M=this.state.pos,$=this.state.line,Z=this.state.column;if(this.match(this.blockStart),this.peek()==="-")this.advance();if(this.skipWhitespace(),this.checkWord(K)){let U=this.state.source.slice(Q,M);if(U.length>0)this.state.tokens.push({type:"TEXT",value:U,line:R,column:O});for(let G=0;G<K.length;G++)this.advance();if(this.skipWhitespace(),this.peek()==="-")this.advance();if(!this.match(this.blockEnd))throw new I(`Expected '${this.blockEnd}' after '${K}'`,{line:this.state.line,column:this.state.column,source:this.state.source});return}this.state.pos=M,this.state.line=$,this.state.column=Z}if(this.peek()===`
7
- `)this.state.line++,this.state.column=0;this.advance()}throw new I(`Unclosed '${A}' block`,{line:R,column:O,source:this.state.source,suggestion:`Add {% end${A} %} to close the block`})}scanText(){let A=this.state.pos,B=this.state.line,R=this.state.column;while(!this.isAtEnd()){if(this.check(this.variableStart)||this.check(this.blockStart)||this.check(this.commentStart))break;if(this.peek()===`
8
- `)this.state.line++,this.state.column=0;this.advance()}if(this.state.pos>A){let O=this.state.source.slice(A,this.state.pos);this.state.tokens.push({type:"TEXT",value:O,line:B,column:R})}}scanExpression(A,B){this.skipWhitespace();while(!this.isAtEnd()){if(this.skipWhitespace(),this.peek()==="-"&&this.check(A,1))this.advance();if(this.match(A)){this.addToken(B,A);return}this.scanExpressionToken()}throw new I("Unclosed template tag",{line:this.state.line,column:this.state.column,source:this.state.source,suggestion:`Add closing delimiter '${A}'`})}scanExpressionToken(){if(this.skipWhitespace(),this.isAtEnd())return;let A=this.peek();if(A==='"'||A==="'"){this.scanString(A);return}if(this.isDigit(A)){this.scanNumber();return}if(this.isAlpha(A)||A==="_"){this.scanIdentifier();return}this.scanOperator()}scanString(A){this.advance();let B=this.state.pos;while(!this.isAtEnd()&&this.peek()!==A){if(this.peek()==="\\"&&this.peekNext()===A)this.advance();if(this.peek()===`
9
- `)this.state.line++,this.state.column=0;this.advance()}if(this.isAtEnd())throw new I("Unterminated string literal",{line:this.state.line,column:this.state.column,source:this.state.source,suggestion:`Add closing quote '${A}'`});let R=this.state.source.slice(B,this.state.pos);this.advance(),this.addToken("STRING",R)}scanNumber(){let A=this.state.pos;while(this.isDigit(this.peek()))this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext())){this.advance();while(this.isDigit(this.peek()))this.advance()}let B=this.state.source.slice(A,this.state.pos);this.addToken("NUMBER",B)}scanIdentifier(){let A=this.state.pos;while(this.isAlphaNumeric(this.peek())||this.peek()==="_")this.advance();let B=this.state.source.slice(A,this.state.pos),R=P[B]??"NAME";this.addToken(R,B)}scanOperator(){let A=this.advance();switch(A){case".":this.addToken("DOT",A);break;case",":this.addToken("COMMA",A);break;case":":this.addToken("COLON",A);break;case"|":this.addToken("PIPE",A);break;case"(":this.addToken("LPAREN",A);break;case")":this.addToken("RPAREN",A);break;case"[":this.addToken("LBRACKET",A);break;case"]":this.addToken("RBRACKET",A);break;case"{":this.addToken("LBRACE",A);break;case"}":this.addToken("RBRACE",A);break;case"+":this.addToken("ADD",A);break;case"-":this.addToken("SUB",A);break;case"*":this.addToken("MUL",A);break;case"/":this.addToken("DIV",A);break;case"%":this.addToken("MOD",A);break;case"~":this.addToken("TILDE",A);break;case"=":if(this.match("="))this.addToken("EQ","==");else this.addToken("ASSIGN","=");break;case"!":if(this.match("="))this.addToken("NE","!=");else throw new I("Unexpected character '!'",{line:this.state.line,column:this.state.column-1,source:this.state.source,suggestion:"Use '!=' for not-equal comparison or 'not' for negation"});break;case"<":if(this.match("="))this.addToken("LE","<=");else this.addToken("LT","<");break;case">":if(this.match("="))this.addToken("GE",">=");else this.addToken("GT",">");break;case"?":if(this.match("?"))this.addToken("NULLCOALESCE","??");else this.addToken("QUESTION","?");break;default:if(!this.isWhitespace(A))throw new I(`Unexpected character '${A}'`,{line:this.state.line,column:this.state.column-1,source:this.state.source})}}scanComment(){while(!this.isAtEnd()&&!this.check(this.commentEnd)){if(this.peek()===`
10
- `)this.state.line++,this.state.column=0;this.advance()}if(!this.isAtEnd())this.match(this.commentEnd)}isAtEnd(){return this.state.pos>=this.state.source.length}peek(){if(this.isAtEnd())return"\x00";return this.state.source[this.state.pos]}peekNext(){if(this.state.pos+1>=this.state.source.length)return"\x00";return this.state.source[this.state.pos+1]}advance(){let A=this.state.source[this.state.pos];return this.state.pos++,this.state.column++,A}match(A,B=0){let R=this.state.source,O=this.state.pos+B,K=A.length;if(O+K>R.length)return!1;for(let Q=0;Q<K;Q++)if(R[O+Q]!==A[Q])return!1;if(B===0)this.state.pos+=K,this.state.column+=K;return!0}check(A,B=0){let R=this.state.source,O=this.state.pos+B,K=A.length;if(O+K>R.length)return!1;for(let Q=0;Q<K;Q++)if(R[O+Q]!==A[Q])return!1;return!0}skipWhitespace(){while(!this.isAtEnd()&&this.isWhitespace(this.peek())){if(this.peek()===`
11
- `)this.state.line++,this.state.column=0;this.advance()}}isWhitespace(A){return A===" "||A==="\t"||A===`
12
- `||A==="\r"}isDigit(A){let B=A.charCodeAt(0);return B>=48&&B<=57}isAlpha(A){let B=A.charCodeAt(0);return B>=97&&B<=122||B>=65&&B<=90}isAlphaNumeric(A){let B=A.charCodeAt(0);return B>=48&&B<=57||B>=97&&B<=122||B>=65&&B<=90}addToken(A,B){this.state.tokens.push({type:A,value:B,line:this.state.line,column:this.state.column-B.length})}}class S{tokens;current=0;source;constructor(A,B){this.tokens=A,this.source=B}parse(){let A=[];while(!this.isAtEnd()){let B=this.parseStatement();if(B)A.push(B)}return{type:"Template",body:A,line:1,column:1}}parseStatement(){switch(this.peek().type){case"TEXT":return this.parseText();case"VARIABLE_START":return this.parseOutput();case"BLOCK_START":return this.parseBlock();case"EOF":return null;default:return this.advance(),null}}parseText(){let A=this.advance();return{type:"Text",value:A.value,line:A.line,column:A.column}}parseOutput(){let A=this.advance(),B=this.parseExpression();return this.expect("VARIABLE_END"),{type:"Output",expression:B,line:A.line,column:A.column}}parseBlock(){let A=this.advance(),B=this.expect("NAME");switch(B.value){case"if":return this.parseIf(A);case"for":return this.parseFor(A);case"block":return this.parseBlockTag(A);case"extends":return this.parseExtends(A);case"include":return this.parseInclude(A);case"set":return this.parseSet(A);case"with":return this.parseWith(A);case"load":return this.parseLoad(A);case"url":return this.parseUrl(A);case"static":return this.parseStatic(A);case"now":return this.parseNow(A);case"comment":return this.parseComment(A);case"spaceless":case"autoescape":case"verbatim":return this.parseSimpleBlock(A,B.value);case"cycle":return this.parseCycle(A);case"firstof":return this.parseFirstof(A);case"ifchanged":return this.parseIfchanged(A);case"regroup":return this.parseRegroup(A);case"widthratio":return this.parseWidthratio(A);case"lorem":return this.parseLorem(A);case"csrf_token":return this.parseCsrfToken(A);case"debug":return this.parseDebug(A);case"templatetag":return this.parseTemplatetag(A);case"ifequal":return this.parseIfequal(A,!1);case"ifnotequal":return this.parseIfequal(A,!0);default:return this.skipToBlockEnd(),null}}parseIf(A){let B=this.parseExpression();this.expect("BLOCK_END");let R=[],O=[],K=[];while(!this.isAtEnd()){if(this.checkBlockTag("elif")||this.checkBlockTag("else")||this.checkBlockTag("endif"))break;let Q=this.parseStatement();if(Q)R.push(Q)}while(this.checkBlockTag("elif")){this.advance(),this.advance();let Q=this.parseExpression();this.expect("BLOCK_END");let M=[];while(!this.isAtEnd()){if(this.checkBlockTag("elif")||this.checkBlockTag("else")||this.checkBlockTag("endif"))break;let $=this.parseStatement();if($)M.push($)}O.push({test:Q,body:M})}if(this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endif"))break;let Q=this.parseStatement();if(Q)K.push(Q)}}return this.expectBlockTag("endif"),{type:"If",test:B,body:R,elifs:O,else_:K,line:A.line,column:A.column}}parseFor(A){let B,R=this.expect("NAME").value;if(this.check("COMMA")){let Z=[R];while(this.match("COMMA"))Z.push(this.expect("NAME").value);B=Z}else B=R;let O=this.expect("NAME");if(O.value!=="in")throw this.error(`Expected 'in' in for loop, got '${O.value}'`);let K=this.parseExpression(),Q=this.check("NAME")&&this.peek().value==="recursive";if(Q)this.advance();this.expect("BLOCK_END");let M=[],$=[];while(!this.isAtEnd()){if(this.checkBlockTag("empty")||this.checkBlockTag("else")||this.checkBlockTag("endfor"))break;let Z=this.parseStatement();if(Z)M.push(Z)}if(this.checkBlockTag("empty")||this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endfor"))break;let Z=this.parseStatement();if(Z)$.push(Z)}}return this.expectBlockTag("endfor"),{type:"For",target:B,iter:K,body:M,else_:$,recursive:Q,line:A.line,column:A.column}}parseBlockTag(A){let B=this.expect("NAME").value,R=this.check("NAME")&&this.peek().value==="scoped";if(R)this.advance();this.expect("BLOCK_END");let O=[];while(!this.isAtEnd()){if(this.checkBlockTag("endblock"))break;let K=this.parseStatement();if(K)O.push(K)}if(this.advance(),this.advance(),this.check("NAME"))this.advance();return this.expect("BLOCK_END"),{type:"Block",name:B,body:O,scoped:R,line:A.line,column:A.column}}parseExtends(A){let B=this.parseExpression();return this.expect("BLOCK_END"),{type:"Extends",template:B,line:A.line,column:A.column}}parseInclude(A){let B=this.parseExpression(),R=null,O=!1,K=!1;while(this.check("NAME")){let Q=this.peek().value;if(Q==="ignore"&&this.peekNext()?.value==="missing")this.advance(),this.advance(),K=!0;else if(Q==="with")this.advance(),R=this.parseKeywordArgs();else if(Q==="only")this.advance(),O=!0;else if(Q==="without"){if(this.advance(),this.check("NAME")&&this.peek().value==="context")this.advance(),O=!0}else break}return this.expect("BLOCK_END"),{type:"Include",template:B,context:R,only:O,ignoreMissing:K,line:A.line,column:A.column}}parseSet(A){let B=this.expect("NAME").value;this.expect("ASSIGN");let R=this.parseExpression();return this.expect("BLOCK_END"),{type:"Set",target:B,value:R,line:A.line,column:A.column}}parseWith(A){let B=[];do{let O=this.expect("NAME").value;this.expect("ASSIGN");let K=this.parseExpression();B.push({target:O,value:K})}while(this.match("COMMA")||this.check("NAME")&&this.peekNext()?.type==="ASSIGN");this.expect("BLOCK_END");let R=[];while(!this.isAtEnd()){if(this.checkBlockTag("endwith"))break;let O=this.parseStatement();if(O)R.push(O)}return this.expectBlockTag("endwith"),{type:"With",assignments:B,body:R,line:A.line,column:A.column}}parseLoad(A){let B=[];while(this.check("NAME"))B.push(this.advance().value);return this.expect("BLOCK_END"),{type:"Load",names:B,line:A.line,column:A.column}}parseUrl(A){let B=this.parseExpression(),R=[],O={},K=null;while(!this.check("BLOCK_END")){if(this.check("NAME")&&this.peek().value==="as"){this.advance(),K=this.expect("NAME").value;break}if(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let Q=this.advance().value;this.advance(),O[Q]=this.parseExpression()}else R.push(this.parseExpression())}return this.expect("BLOCK_END"),{type:"Url",name:B,args:R,kwargs:O,asVar:K,line:A.line,column:A.column}}parseStatic(A){let B=this.parseExpression(),R=null;if(this.check("NAME")&&this.peek().value==="as")this.advance(),R=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Static",path:B,asVar:R,line:A.line,column:A.column}}parseNow(A){let B=this.parseExpression(),R=null;if(this.check("NAME")&&this.peek().value==="as")this.advance(),R=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Now",format:B,asVar:R,line:A.line,column:A.column}}parseComment(A){this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endcomment"))break;this.advance()}return this.expectBlockTag("endcomment"),null}parseSimpleBlock(A,B){this.skipToBlockEnd();let R=`end${B}`;while(!this.isAtEnd()){if(this.checkBlockTag(R))break;this.advance()}if(this.checkBlockTag(R))this.advance(),this.advance(),this.expect("BLOCK_END");return null}parseCycle(A){let B=[],R=null,O=!1;while(!this.check("BLOCK_END")){if(this.check("NAME")&&this.peek().value==="as"){if(this.advance(),R=this.expect("NAME").value,this.check("NAME")&&this.peek().value==="silent")this.advance(),O=!0;break}B.push(this.parseExpression())}return this.expect("BLOCK_END"),{type:"Cycle",values:B,asVar:R,silent:O,line:A.line,column:A.column}}parseFirstof(A){let B=[],R=null,O=null;while(!this.check("BLOCK_END")){if(this.check("NAME")&&this.peek().value==="as"){this.advance(),O=this.expect("NAME").value;break}B.push(this.parseExpression())}if(B.length>0){let K=B[B.length-1];if(K.type==="Literal"&&typeof K.value==="string")R=B.pop()}return this.expect("BLOCK_END"),{type:"Firstof",values:B,fallback:R,asVar:O,line:A.line,column:A.column}}parseIfchanged(A){let B=[];while(!this.check("BLOCK_END"))B.push(this.parseExpression());this.expect("BLOCK_END");let R=[],O=[];while(!this.isAtEnd()){if(this.checkBlockTag("else")||this.checkBlockTag("endifchanged"))break;let K=this.parseStatement();if(K)R.push(K)}if(this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endifchanged"))break;let K=this.parseStatement();if(K)O.push(K)}}return this.expectBlockTag("endifchanged"),{type:"Ifchanged",values:B,body:R,else_:O,line:A.line,column:A.column}}parseRegroup(A){let B=this.parseExpression();this.expectName("by");let R=this.expect("NAME").value;this.expectName("as");let O=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Regroup",target:B,key:R,asVar:O,line:A.line,column:A.column}}parseWidthratio(A){let B=this.parseExpression(),R=this.parseExpression(),O=this.parseExpression(),K=null;if(this.check("NAME")&&this.peek().value==="as")this.advance(),K=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Widthratio",value:B,maxValue:R,maxWidth:O,asVar:K,line:A.line,column:A.column}}parseLorem(A){let B=null,R="p",O=!1;if(this.check("NUMBER"))B={type:"Literal",value:parseInt(this.advance().value,10),line:A.line,column:A.column};if(this.check("NAME")){let K=this.peek().value.toLowerCase();if(K==="w"||K==="p"||K==="b")R=K,this.advance()}if(this.check("NAME")&&this.peek().value==="random")O=!0,this.advance();return this.expect("BLOCK_END"),{type:"Lorem",count:B,method:R,random:O,line:A.line,column:A.column}}parseCsrfToken(A){return this.expect("BLOCK_END"),{type:"CsrfToken",line:A.line,column:A.column}}parseDebug(A){return this.expect("BLOCK_END"),{type:"Debug",line:A.line,column:A.column}}parseTemplatetag(A){let B=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Templatetag",tagType:B,line:A.line,column:A.column}}parseIfequal(A,B){let R=this.parseExpression(),O=this.parseExpression();this.expect("BLOCK_END");let K={type:"Compare",left:R,ops:[{operator:B?"!=":"==",right:O}],line:A.line,column:A.column},Q=[],M=[],$=B?"endifnotequal":"endifequal";while(!this.isAtEnd()){if(this.checkBlockTag("else")||this.checkBlockTag($))break;let Z=this.parseStatement();if(Z)Q.push(Z)}if(this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag($))break;let Z=this.parseStatement();if(Z)M.push(Z)}}return this.expectBlockTag($),{type:"If",test:K,body:Q,elifs:[],else_:M,line:A.line,column:A.column}}parseExpression(){return this.parseConditional()}parseConditional(){let A=this.parseOr();if(this.check("NAME")&&this.peek().value==="if"){this.advance();let B=this.parseOr();this.expectName("else");let R=this.parseConditional();A={type:"Conditional",test:B,trueExpr:A,falseExpr:R,line:A.line,column:A.column}}return A}parseOr(){let A=this.parseAnd();while(this.check("OR")||this.check("NAME")&&this.peek().value==="or"){this.advance();let B=this.parseAnd();A={type:"BinaryOp",operator:"or",left:A,right:B,line:A.line,column:A.column}}return A}parseAnd(){let A=this.parseNot();while(this.check("AND")||this.check("NAME")&&this.peek().value==="and"){this.advance();let B=this.parseNot();A={type:"BinaryOp",operator:"and",left:A,right:B,line:A.line,column:A.column}}return A}parseNot(){if(this.check("NOT")||this.check("NAME")&&this.peek().value==="not"){let A=this.advance();return{type:"UnaryOp",operator:"not",operand:this.parseNot(),line:A.line,column:A.column}}return this.parseCompare()}parseCompare(){let A=this.parseAddSub(),B=[];while(!0){let R=null;if(this.match("EQ"))R="==";else if(this.match("NE"))R="!=";else if(this.match("LT"))R="<";else if(this.match("GT"))R=">";else if(this.match("LE"))R="<=";else if(this.match("GE"))R=">=";else if(this.check("NAME")){let K=this.peek().value;if(K==="in")this.advance(),R="in";else if(K==="not"&&this.peekNext()?.value==="in")this.advance(),this.advance(),R="not in";else if(K==="is"){this.advance();let Q=this.check("NOT");if(Q)this.advance();let $=this.expect("NAME").value,Z=[];if(this.match("LPAREN")){while(!this.check("RPAREN"))if(Z.push(this.parseExpression()),!this.check("RPAREN"))this.expect("COMMA");this.expect("RPAREN")}A={type:"TestExpr",node:A,test:$,args:Z,negated:Q,line:A.line,column:A.column};continue}}if(!R)break;let O=this.parseAddSub();B.push({operator:R,right:O})}if(B.length===0)return A;return{type:"Compare",left:A,ops:B,line:A.line,column:A.column}}parseAddSub(){let A=this.parseMulDiv();while(this.check("ADD")||this.check("SUB")||this.check("TILDE")){let B=this.advance(),R=this.parseMulDiv();A={type:"BinaryOp",operator:B.value,left:A,right:R,line:A.line,column:A.column}}return A}parseMulDiv(){let A=this.parseUnary();while(this.check("MUL")||this.check("DIV")||this.check("MOD")){let B=this.advance(),R=this.parseUnary();A={type:"BinaryOp",operator:B.value,left:A,right:R,line:A.line,column:A.column}}return A}parseUnary(){if(this.check("SUB")||this.check("ADD")){let A=this.advance(),B=this.parseUnary();return{type:"UnaryOp",operator:A.value,operand:B,line:A.line,column:A.column}}return this.parseFilter()}parseFilter(){let A=this.parsePostfix();while(this.match("PIPE")){let B=this.expect("NAME").value,R=[],O={};if(this.match("COLON"))if(this.check("SUB")||this.check("ADD")){let K=this.advance(),Q=this.parsePostfix();R.push({type:"UnaryOp",operator:K.value,operand:Q,line:K.line,column:K.column})}else R.push(this.parsePostfix());else if(this.match("LPAREN")){while(!this.check("RPAREN")){if(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let K=this.advance().value;this.advance(),O[K]=this.parseExpression()}else R.push(this.parseExpression());if(!this.check("RPAREN"))this.expect("COMMA")}this.expect("RPAREN")}A={type:"FilterExpr",node:A,filter:B,args:R,kwargs:O,line:A.line,column:A.column}}return A}parsePostfix(){let A=this.parsePrimary();while(!0)if(this.match("DOT")){let B;if(this.check("NUMBER"))B=this.advance().value;else B=this.expect("NAME").value;A={type:"GetAttr",object:A,attribute:B,line:A.line,column:A.column}}else if(this.match("LBRACKET")){let B=this.parseExpression();this.expect("RBRACKET"),A={type:"GetItem",object:A,index:B,line:A.line,column:A.column}}else if(this.match("LPAREN")){let B=[],R={};while(!this.check("RPAREN")){if(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let O=this.advance().value;this.advance(),R[O]=this.parseExpression()}else B.push(this.parseExpression());if(!this.check("RPAREN"))this.expect("COMMA")}this.expect("RPAREN"),A={type:"FunctionCall",callee:A,args:B,kwargs:R,line:A.line,column:A.column}}else break;return A}parsePrimary(){let A=this.peek();if(this.match("STRING"))return{type:"Literal",value:A.value,line:A.line,column:A.column};if(this.match("NUMBER"))return{type:"Literal",value:A.value.includes(".")?parseFloat(A.value):parseInt(A.value,10),line:A.line,column:A.column};if(this.check("NAME")){let B=this.advance().value;if(B==="true"||B==="True")return{type:"Literal",value:!0,line:A.line,column:A.column};if(B==="false"||B==="False")return{type:"Literal",value:!1,line:A.line,column:A.column};if(B==="none"||B==="None"||B==="null")return{type:"Literal",value:null,line:A.line,column:A.column};return{type:"Name",name:B,line:A.line,column:A.column}}if(this.match("LPAREN")){let B=this.parseExpression();return this.expect("RPAREN"),B}if(this.match("LBRACKET")){let B=[];while(!this.check("RBRACKET"))if(B.push(this.parseExpression()),!this.check("RBRACKET"))this.expect("COMMA");return this.expect("RBRACKET"),{type:"Array",elements:B,line:A.line,column:A.column}}if(this.match("LBRACE")){let B=[];while(!this.check("RBRACE")){let R=this.parseExpression();this.expect("COLON");let O=this.parseExpression();if(B.push({key:R,value:O}),!this.check("RBRACE"))this.expect("COMMA")}return this.expect("RBRACE"),{type:"Object",pairs:B,line:A.line,column:A.column}}throw this.error(`Unexpected token: ${A.type} (${A.value})`)}parseKeywordArgs(){let A={};while(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let B=this.advance().value;this.advance(),A[B]=this.parseExpression()}return A}checkBlockTag(A){if(this.peek().type!=="BLOCK_START")return!1;let B=this.current+1;if(B>=this.tokens.length)return!1;let R=this.tokens[B];return R.type==="NAME"&&R.value===A}expectBlockTag(A){this.advance();let B=this.expect("NAME");if(B.value!==A)throw this.error(`Expected '${A}', got '${B.value}'`);this.expect("BLOCK_END")}expectName(A){let B=this.expect("NAME");if(B.value!==A)throw this.error(`Expected '${A}', got '${B.value}'`)}skipToBlockEnd(){while(!this.isAtEnd()&&!this.check("BLOCK_END"))this.advance();if(this.check("BLOCK_END"))this.advance()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}peekNext(){if(this.current+1>=this.tokens.length)return null;return this.tokens[this.current+1]}advance(){if(!this.isAtEnd())this.current++;return this.tokens[this.current-1]}check(A){if(this.isAtEnd())return!1;return this.peek().type===A}match(A){if(this.check(A))return this.advance(),!0;return!1}expect(A){if(this.check(A))return this.advance();let B=this.peek();throw this.error(`Expected ${A}, got ${B.type} (${B.value})`)}error(A){let B=this.peek();return new I(A,{line:B.line,column:B.column,source:this.source})}}function f(A,B={}){return new y(B).compile(A)}class y{options;indent=0;varCounter=0;loopStack=[];localVars=[];constructor(A={}){this.options={functionName:A.functionName??"render",inlineHelpers:A.inlineHelpers??!0,minify:A.minify??!1,autoescape:A.autoescape??!0}}pushScope(){this.localVars.push(new Set)}popScope(){this.localVars.pop()}addLocalVar(A){if(this.localVars.length>0)this.localVars[this.localVars.length-1].add(A)}isLocalVar(A){for(let B=this.localVars.length-1;B>=0;B--)if(this.localVars[B].has(A))return!0;return!1}compile(A){let B=this.compileNodes(A.body),R=this.options.minify?"":`
13
- `;return`function ${this.options.functionName}(__ctx) {${R} let __out = '';${R}`+B+` return __out;${R}}`}compileNodes(A){return A.map((B)=>this.compileNode(B)).join("")}compileNode(A){switch(A.type){case"Text":return this.compileText(A);case"Output":return this.compileOutput(A);case"If":return this.compileIf(A);case"For":return this.compileFor(A);case"Set":return this.compileSet(A);case"With":return this.compileWith(A);case"Comment":return"";case"Extends":case"Block":case"Include":throw Error(`AOT compilation does not support '${A.type}' - use Environment.render() for templates with inheritance`);case"Url":case"Static":throw Error(`AOT compilation does not support '${A.type}' tag - use Environment.render() with urlResolver/staticResolver`);default:throw Error(`Unknown node type in AOT compiler: ${A.type}`)}}compileText(A){return` __out += ${JSON.stringify(A.value)};${this.nl()}`}compileOutput(A){let B=this.compileExpr(A.expression);if(this.options.autoescape&&!this.isMarkedSafe(A.expression))return` __out += escape(${B});${this.nl()}`;return` __out += (${B}) ?? '';${this.nl()}`}compileIf(A){let B="",R=this.compileExpr(A.test);B+=` if (isTruthy(${R})) {${this.nl()}`,B+=this.compileNodes(A.body),B+=" }";for(let O of A.elifs){let K=this.compileExpr(O.test);B+=` else if (isTruthy(${K})) {${this.nl()}`,B+=this.compileNodes(O.body),B+=" }"}if(A.else_.length>0)B+=` else {${this.nl()}`,B+=this.compileNodes(A.else_),B+=" }";return B+=this.nl(),B}compileFor(A){let B=this.genVar("iter"),R=this.genVar("i"),O=this.genVar("len"),K=this.genVar("loop"),Q=Array.isArray(A.target)?A.target[0]:A.target,M=Array.isArray(A.target)&&A.target[1]?A.target[1]:null,$=this.loopStack.length>0?this.loopStack[this.loopStack.length-1]:null,Z=this.compileExpr(A.iter),U="";if(U+=` const ${B} = toArray(${Z});${this.nl()}`,U+=` const ${O} = ${B}.length;${this.nl()}`,A.else_.length>0)U+=` if (${O} === 0) {${this.nl()}`,U+=this.compileNodes(A.else_),U+=` } else {${this.nl()}`;if(U+=` for (let ${R} = 0; ${R} < ${O}; ${R}++) {${this.nl()}`,M)U+=` const ${Q} = ${B}[${R}][0];${this.nl()}`,U+=` const ${M} = ${B}[${R}][1];${this.nl()}`;else U+=` const ${Q} = ${B}[${R}];${this.nl()}`;if(U+=` const ${K} = {${this.nl()}`,U+=` counter: ${R} + 1,${this.nl()}`,U+=` counter0: ${R},${this.nl()}`,U+=` revcounter: ${O} - ${R},${this.nl()}`,U+=` revcounter0: ${O} - ${R} - 1,${this.nl()}`,U+=` first: ${R} === 0,${this.nl()}`,U+=` last: ${R} === ${O} - 1,${this.nl()}`,U+=` length: ${O},${this.nl()}`,U+=` index: ${R} + 1,${this.nl()}`,U+=` index0: ${R},${this.nl()}`,$)U+=` parentloop: ${$},${this.nl()}`,U+=` parent: ${$}${this.nl()}`;else U+=` parentloop: null,${this.nl()}`,U+=` parent: null${this.nl()}`;U+=` };${this.nl()}`,U+=` const forloop = ${K};${this.nl()}`,U+=` const loop = ${K};${this.nl()}`,this.loopStack.push(K);let G=this.compileNodes(A.body);if(U+=G.replace(new RegExp(`__ctx\\.${Q}`,"g"),Q),this.loopStack.pop(),U+=` }${this.nl()}`,A.else_.length>0)U+=` }${this.nl()}`;return U}compileSet(A){let B=this.compileExpr(A.value);return` const ${A.target} = ${B};${this.nl()}`}compileWith(A){let B=` {${this.nl()}`;this.pushScope();for(let{target:R,value:O}of A.assignments){let K=this.compileExpr(O);B+=` const ${R} = ${K};${this.nl()}`,this.addLocalVar(R)}return B+=this.compileNodes(A.body),B+=` }${this.nl()}`,this.popScope(),B}compileExpr(A){switch(A.type){case"Name":return this.compileName(A);case"Literal":return this.compileLiteral(A);case"Array":return this.compileArray(A);case"Object":return this.compileObject(A);case"BinaryOp":return this.compileBinaryOp(A);case"UnaryOp":return this.compileUnaryOp(A);case"Compare":return this.compileCompare(A);case"GetAttr":return this.compileGetAttr(A);case"GetItem":return this.compileGetItem(A);case"FilterExpr":return this.compileFilter(A);case"TestExpr":return this.compileTest(A);case"Conditional":return this.compileConditional(A);default:return"undefined"}}compileName(A){if(A.name==="true"||A.name==="True")return"true";if(A.name==="false"||A.name==="False")return"false";if(A.name==="none"||A.name==="None"||A.name==="null")return"null";if(A.name==="forloop"||A.name==="loop")return A.name;if(this.isLocalVar(A.name))return A.name;return`__ctx.${A.name}`}compileLiteral(A){if(typeof A.value==="string")return JSON.stringify(A.value);return String(A.value)}compileArray(A){return`[${A.elements.map((R)=>this.compileExpr(R)).join(", ")}]`}compileObject(A){return`{${A.pairs.map(({key:R,value:O})=>{let K=this.compileExpr(R),Q=this.compileExpr(O);return`[${K}]: ${Q}`}).join(", ")}}`}compileBinaryOp(A){let B=this.compileExpr(A.left),R=this.compileExpr(A.right);switch(A.operator){case"and":return`(${B} && ${R})`;case"or":return`(${B} || ${R})`;case"~":return`(String(${B}) + String(${R}))`;case"in":return`(Array.isArray(${R}) ? ${R}.includes(${B}) : String(${R}).includes(String(${B})))`;case"not in":return`!(Array.isArray(${R}) ? ${R}.includes(${B}) : String(${R}).includes(String(${B})))`;default:return`(${B} ${A.operator} ${R})`}}compileUnaryOp(A){let B=this.compileExpr(A.operand);switch(A.operator){case"not":return`!isTruthy(${B})`;case"-":return`-(${B})`;case"+":return`+(${B})`;default:return B}}compileCompare(A){let B=this.compileExpr(A.left);for(let{operator:R,right:O}of A.ops){let K=this.compileExpr(O);switch(R){case"==":case"===":B=`(${B} === ${K})`;break;case"!=":case"!==":B=`(${B} !== ${K})`;break;default:B=`(${B} ${R} ${K})`}}return B}compileGetAttr(A){return`${this.compileExpr(A.object)}?.${A.attribute}`}compileGetItem(A){let B=this.compileExpr(A.object),R=this.compileExpr(A.index);return`${B}?.[${R}]`}compileFilter(A){let B=this.compileExpr(A.node),R=A.args.map((O)=>this.compileExpr(O));switch(A.filter){case"upper":return`String(${B}).toUpperCase()`;case"lower":return`String(${B}).toLowerCase()`;case"title":return`String(${B}).replace(/\\b\\w/g, c => c.toUpperCase())`;case"trim":return`String(${B}).trim()`;case"length":return`(${B}?.length ?? Object.keys(${B} ?? {}).length)`;case"first":return`(${B})?.[0]`;case"last":return`(${B})?.[(${B})?.length - 1]`;case"default":return`((${B}) ?? ${R[0]??'""'})`;case"safe":return`{ __safe: true, value: String(${B}) }`;case"escape":case"e":return`escape(${B})`;case"join":return`(${B} ?? []).join(${R[0]??'""'})`;case"abs":return`Math.abs(${B})`;case"round":return R.length?`Number(${B}).toFixed(${R[0]})`:`Math.round(${B})`;case"int":return`parseInt(${B}, 10)`;case"float":return`parseFloat(${B})`;case"floatformat":return`Number(${B}).toFixed(${R[0]??1})`;case"filesizeformat":return`applyFilter('filesizeformat', ${B})`;default:let O=R.length?", "+R.join(", "):"";return`applyFilter('${A.filter}', ${B}${O})`}}compileTest(A){let B=this.compileExpr(A.node),R=A.args.map((K)=>this.compileExpr(K)),O=A.negated?"!":"";switch(A.test){case"defined":return`${O}(${B} !== undefined)`;case"undefined":return`${O}(${B} === undefined)`;case"none":return`${O}(${B} === null)`;case"even":return`${O}(${B} % 2 === 0)`;case"odd":return`${O}(${B} % 2 !== 0)`;case"divisibleby":return`${O}(${B} % ${R[0]} === 0)`;case"empty":return`${O}((${B} == null) || (${B}.length === 0) || (Object.keys(${B}).length === 0))`;case"iterable":return`${O}(Array.isArray(${B}) || typeof ${B} === 'string')`;case"number":return`${O}(typeof ${B} === 'number' && !isNaN(${B}))`;case"string":return`${O}(typeof ${B} === 'string')`;default:let K=R.length?", "+R.join(", "):"";return`${O}applyTest('${A.test}', ${B}${K})`}}compileConditional(A){let B=this.compileExpr(A.test),R=this.compileExpr(A.trueExpr),O=this.compileExpr(A.falseExpr);return`(isTruthy(${B}) ? ${R} : ${O})`}isMarkedSafe(A){if(A.type==="FilterExpr")return A.filter==="safe";return!1}genVar(A){return`__${A}${this.varCounter++}`}nl(){return this.options.minify?"":`
14
- `}}function k(A,B){return new g(B).flatten(A)}function N(A){return new m().check(A)}class g{loader;maxDepth;blocks=new Map;depth=0;constructor(A){this.loader=A.loader,this.maxDepth=A.maxDepth??10}flatten(A){return this.blocks.clear(),this.depth=0,this.processTemplate(A)}processTemplate(A,B=!0){if(this.depth>this.maxDepth)throw Error(`Maximum template inheritance depth (${this.maxDepth}) exceeded`);this.collectBlocks(A.body,B);let R=this.findExtends(A.body);if(R){let O=this.getStaticTemplateName(R.template),K=this.loader.load(O),Q=this.loader.parse(K);this.depth++;let M=this.processTemplate(Q,!1);return this.depth--,{type:"Template",body:this.replaceBlocks(M.body),line:A.line,column:A.column}}return{type:"Template",body:this.processNodes(A.body),line:A.line,column:A.column}}collectBlocks(A,B=!0){for(let R of A){if(R.type==="Block"){let O=R;if(B||!this.blocks.has(O.name))this.blocks.set(O.name,O)}this.collectBlocksFromNode(R,B)}}collectBlocksFromNode(A,B=!0){switch(A.type){case"If":{let R=A;this.collectBlocks(R.body,B);for(let O of R.elifs)this.collectBlocks(O.body,B);this.collectBlocks(R.else_,B);break}case"For":{let R=A;this.collectBlocks(R.body,B),this.collectBlocks(R.else_,B);break}case"With":{let R=A;this.collectBlocks(R.body,B);break}case"Block":{let R=A;this.collectBlocks(R.body,B);break}}}findExtends(A){for(let B of A)if(B.type==="Extends")return B;return null}processNodes(A){let B=[];for(let R of A){if(R.type==="Extends")continue;if(R.type==="Include"){let K=R,Q=this.inlineInclude(K);B.push(...Q);continue}if(R.type==="Block"){let K=R,Q=this.blocks.get(K.name);if(Q&&Q!==K)B.push(...this.processNodes(Q.body));else B.push(...this.processNodes(K.body));continue}let O=this.processNode(R);if(O)B.push(O)}return B}processNode(A){switch(A.type){case"If":{let B=A;return{...B,body:this.processNodes(B.body),elifs:B.elifs.map((R)=>({test:R.test,body:this.processNodes(R.body)})),else_:this.processNodes(B.else_)}}case"For":{let B=A;return{...B,body:this.processNodes(B.body),else_:this.processNodes(B.else_)}}case"With":{let B=A;return{...B,body:this.processNodes(B.body)}}default:return A}}replaceBlocks(A){return this.processNodes(A)}inlineInclude(A){let B=this.getStaticTemplateName(A.template);try{let R=this.loader.load(B),O=this.loader.parse(R);this.depth++;let K=this.processTemplate(O);if(this.depth--,A.context&&Object.keys(A.context).length>0)return[{type:"With",assignments:Object.entries(A.context).map(([M,$])=>({target:M,value:$})),body:K.body,line:A.line,column:A.column}];return K.body}catch(R){if(A.ignoreMissing)return[];throw R}}getStaticTemplateName(A){if(A.type==="Literal"){let B=A;if(typeof B.value==="string")return B.value}throw Error(`AOT compilation requires static template names. Found dynamic expression at line ${A.line}. Use Environment.render() for dynamic template names.`)}}class m{check(A){return this.checkNodes(A.body)}checkNodes(A){for(let B of A){let R=this.checkNode(B);if(!R.canFlatten)return R}return{canFlatten:!0}}checkNode(A){switch(A.type){case"Extends":{let B=A;if(!this.isStaticName(B.template))return{canFlatten:!1,reason:`Dynamic extends at line ${A.line} - use static string literal`};break}case"Include":{let B=A;if(!this.isStaticName(B.template))return{canFlatten:!1,reason:`Dynamic include at line ${A.line} - use static string literal`};break}case"If":{let B=A,R=this.checkNodes(B.body);if(!R.canFlatten)return R;for(let O of B.elifs)if(R=this.checkNodes(O.body),!R.canFlatten)return R;if(R=this.checkNodes(B.else_),!R.canFlatten)return R;break}case"For":{let B=A,R=this.checkNodes(B.body);if(!R.canFlatten)return R;if(R=this.checkNodes(B.else_),!R.canFlatten)return R;break}case"With":{let B=A,R=this.checkNodes(B.body);if(!R.canFlatten)return R;break}case"Block":{let B=A,R=this.checkNodes(B.body);if(!R.canFlatten)return R;break}}return{canFlatten:!0}}isStaticName(A){return A.type==="Literal"&&typeof A.value==="string"}}var i="0.1.1",J={reset:"\x1B[0m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",dim:"\x1B[2m"};function E(A){console.log(A)}function L(A){console.log(`${J.green}\u2713${J.reset} ${A}`)}function _(A){console.log(`${J.yellow}\u26A0${J.reset} ${A}`)}function F(A){console.error(`${J.red}\u2717${J.reset} ${A}`)}function w(){console.log(`
15
- ${J.cyan}binja${J.reset} - High-performance template compiler
16
-
17
- ${J.yellow}Usage:${J.reset}
3
+ var nZ=Object.defineProperty;var K2=($,Y)=>{for(var Z in Y)nZ($,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:(X)=>Y[Z]=()=>X})};var H=($,Y)=>()=>($&&(Y=$($=0)),Y);var W2;var z2=H(()=>{W2={and:"AND",or:"OR",not:"NOT",true:"NAME",false:"NAME",True:"NAME",False:"NAME",None:"NAME",none:"NAME",is:"NAME",in:"NAME"}});function K0($,Y){return aZ?`${TY[$]}${Y}${TY.reset}`:Y}function rZ($,Y,Z){let X=[],G=Z.templateName?`${Z.templateName}:${Z.line}:${Z.column}`:`line ${Z.line}, column ${Z.column}`;if(X.push(`${K0("red",K0("bold",$))}: ${Y} at ${K0("cyan",G)}`),Z.source)X.push(""),X.push(sZ(Z.source,Z.line,Z.column));if(Z.suggestion)X.push(""),X.push(`${K0("yellow","Did you mean")}: ${K0("cyan",Z.suggestion)}?`);if(Z.availableOptions&&Z.availableOptions.length>0){X.push("");let K=Z.availableOptions.slice(0,8),W=Z.availableOptions.length>8?` ${K0("gray",`... and ${Z.availableOptions.length-8} more`)}`:"";X.push(`${K0("gray","Available")}: ${K.join(", ")}${W}`)}return X.join(`
4
+ `)}function sZ($,Y,Z){let X=$.split(`
5
+ `),G=[],K=Math.max(1,Y-2),W=Math.min(X.length,Y+1),z=String(W).length;for(let Q=K;Q<=W;Q++){let J=X[Q-1]||"",U=String(Q).padStart(z," ");if(Q===Y){G.push(`${K0("red"," \u2192")} ${K0("gray",U)} ${K0("dim","\u2502")} ${J}`);let D=" ".repeat(z+4+Math.max(0,Z-1)),O=K0("red","^");G.push(`${D}${O}`)}else G.push(` ${K0("gray",U)} ${K0("dim","\u2502")} ${K0("gray",J)}`)}return G.join(`
6
+ `)}var TY,aZ,q0;var Q2=H(()=>{TY={red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m"},aZ=process.stdout?.isTTY!==!1;q0=class q0 extends Error{line;column;source;templateName;suggestion;constructor($,Y){let Z=rZ("TemplateSyntaxError",$,Y);super(Z);this.name="TemplateSyntaxError",this.line=Y.line,this.column=Y.column,this.source=Y.source,this.templateName=Y.templateName,this.suggestion=Y.suggestion}}});class Q1{state;variableStart;variableEnd;blockStart;blockEnd;commentStart;commentEnd;constructor($,Y={}){this.state={source:$,pos:0,line:1,column:1,tokens:[]},this.variableStart=Y.variableStart??"{{",this.variableEnd=Y.variableEnd??"}}",this.blockStart=Y.blockStart??"{%",this.blockEnd=Y.blockEnd??"%}",this.commentStart=Y.commentStart??"{#",this.commentEnd=Y.commentEnd??"#}"}tokenize(){while(!this.isAtEnd())this.scanToken();return this.addToken("EOF",""),this.state.tokens}scanToken(){if(this.match(this.variableStart)){this.addToken("VARIABLE_START",this.variableStart),this.scanExpression(this.variableEnd,"VARIABLE_END");return}if(this.match(this.blockStart)){let $=this.peek()==="-";if($)this.advance();let Y=this.state.pos;if(this.skipWhitespace(),this.checkWord("raw")||this.checkWord("verbatim")){let Z=this.checkWord("raw")?"raw":"verbatim";this.scanRawBlock(Z,$);return}this.state.pos=Y,this.addToken("BLOCK_START",this.blockStart+($?"-":"")),this.scanExpression(this.blockEnd,"BLOCK_END");return}if(this.match(this.commentStart)){this.scanComment();return}this.scanText()}checkWord($){let Y=this.state.pos;for(let X=0;X<$.length;X++)if(this.state.source[Y+X]?.toLowerCase()!==$[X])return!1;let Z=this.state.source[Y+$.length];return!Z||!this.isAlphaNumeric(Z)}scanRawBlock($,Y){let Z=this.state.line,X=this.state.column;for(let W=0;W<$.length;W++)this.advance();if(this.skipWhitespace(),this.peek()==="-")this.advance();if(!this.match(this.blockEnd))throw new q0(`Expected '${this.blockEnd}' after '${$}'`,{line:this.state.line,column:this.state.column,source:this.state.source});let G=`end${$}`,K=this.state.pos;while(!this.isAtEnd()){if(this.check(this.blockStart)){let W=this.state.pos,z=this.state.line,Q=this.state.column;if(this.match(this.blockStart),this.peek()==="-")this.advance();if(this.skipWhitespace(),this.checkWord(G)){let J=this.state.source.slice(K,W);if(J.length>0)this.state.tokens.push({type:"TEXT",value:J,line:Z,column:X});for(let U=0;U<G.length;U++)this.advance();if(this.skipWhitespace(),this.peek()==="-")this.advance();if(!this.match(this.blockEnd))throw new q0(`Expected '${this.blockEnd}' after '${G}'`,{line:this.state.line,column:this.state.column,source:this.state.source});return}this.state.pos=W,this.state.line=z,this.state.column=Q}if(this.peek()===`
7
+ `)this.state.line++,this.state.column=0;this.advance()}throw new q0(`Unclosed '${$}' block`,{line:Z,column:X,source:this.state.source,suggestion:`Add {% end${$} %} to close the block`})}scanText(){let $=this.state.pos,Y=this.state.line,Z=this.state.column,X=this.state.source;while(!this.isAtEnd()){let G=X.indexOf("{",this.state.pos);if(G===-1){this.advanceToEnd();break}if(G>this.state.pos)this.advanceTo(G);if(this.check(this.variableStart)||this.check(this.blockStart)||this.check(this.commentStart))break;if(this.peek()===`
8
+ `)this.state.line++,this.state.column=0;this.state.pos++,this.state.column++}if(this.state.pos>$){let G=X.slice($,this.state.pos);this.state.tokens.push({type:"TEXT",value:G,line:Y,column:Z})}}advanceTo($){let Y=this.state.source;while(this.state.pos<$){if(Y[this.state.pos]===`
9
+ `)this.state.line++,this.state.column=0;this.state.pos++,this.state.column++}}advanceToEnd(){let $=this.state.source,Y=$.length;while(this.state.pos<Y){if($[this.state.pos]===`
10
+ `)this.state.line++,this.state.column=0;this.state.pos++,this.state.column++}}scanExpression($,Y){this.skipWhitespace();while(!this.isAtEnd()){if(this.skipWhitespace(),this.peek()==="-"&&this.check($,1))this.advance();if(this.match($)){this.addToken(Y,$);return}this.scanExpressionToken()}throw new q0("Unclosed template tag",{line:this.state.line,column:this.state.column,source:this.state.source,suggestion:`Add closing delimiter '${$}'`})}scanExpressionToken(){if(this.skipWhitespace(),this.isAtEnd())return;let $=this.peek();if($==='"'||$==="'"){this.scanString($);return}if(this.isDigit($)){this.scanNumber();return}if(this.isAlpha($)||$==="_"){this.scanIdentifier();return}this.scanOperator()}scanString($){this.advance();let Y=this.state.pos;while(!this.isAtEnd()&&this.peek()!==$){if(this.peek()==="\\"&&this.peekNext()===$)this.advance();if(this.peek()===`
11
+ `)this.state.line++,this.state.column=0;this.advance()}if(this.isAtEnd())throw new q0("Unterminated string literal",{line:this.state.line,column:this.state.column,source:this.state.source,suggestion:`Add closing quote '${$}'`});let Z=this.state.source.slice(Y,this.state.pos);this.advance(),this.addToken("STRING",Z)}scanNumber(){let $=this.state.pos;while(this.isDigit(this.peek()))this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext())){this.advance();while(this.isDigit(this.peek()))this.advance()}let Y=this.state.source.slice($,this.state.pos);this.addToken("NUMBER",Y)}scanIdentifier(){let $=this.state.pos;while(this.isAlphaNumeric(this.peek())||this.peek()==="_")this.advance();let Y=this.state.source.slice($,this.state.pos),Z=W2[Y]??"NAME";this.addToken(Z,Y)}scanOperator(){let $=this.advance();switch($){case".":this.addToken("DOT",$);break;case",":this.addToken("COMMA",$);break;case":":this.addToken("COLON",$);break;case"|":this.addToken("PIPE",$);break;case"(":this.addToken("LPAREN",$);break;case")":this.addToken("RPAREN",$);break;case"[":this.addToken("LBRACKET",$);break;case"]":this.addToken("RBRACKET",$);break;case"{":this.addToken("LBRACE",$);break;case"}":this.addToken("RBRACE",$);break;case"+":this.addToken("ADD",$);break;case"-":this.addToken("SUB",$);break;case"*":this.addToken("MUL",$);break;case"/":this.addToken("DIV",$);break;case"%":this.addToken("MOD",$);break;case"~":this.addToken("TILDE",$);break;case"=":if(this.match("="))this.addToken("EQ","==");else this.addToken("ASSIGN","=");break;case"!":if(this.match("="))this.addToken("NE","!=");else throw new q0("Unexpected character '!'",{line:this.state.line,column:this.state.column-1,source:this.state.source,suggestion:"Use '!=' for not-equal comparison or 'not' for negation"});break;case"<":if(this.match("="))this.addToken("LE","<=");else this.addToken("LT","<");break;case">":if(this.match("="))this.addToken("GE",">=");else this.addToken("GT",">");break;case"?":if(this.match("?"))this.addToken("NULLCOALESCE","??");else this.addToken("QUESTION","?");break;default:if(!this.isWhitespace($))throw new q0(`Unexpected character '${$}'`,{line:this.state.line,column:this.state.column-1,source:this.state.source})}}scanComment(){while(!this.isAtEnd()&&!this.check(this.commentEnd)){if(this.peek()===`
12
+ `)this.state.line++,this.state.column=0;this.advance()}if(!this.isAtEnd())this.match(this.commentEnd)}isAtEnd(){return this.state.pos>=this.state.source.length}peek(){if(this.isAtEnd())return"\x00";return this.state.source[this.state.pos]}peekNext(){if(this.state.pos+1>=this.state.source.length)return"\x00";return this.state.source[this.state.pos+1]}advance(){let $=this.state.source[this.state.pos];return this.state.pos++,this.state.column++,$}match($,Y=0){let Z=this.state.source,X=this.state.pos+Y,G=$.length;if(X+G>Z.length)return!1;for(let K=0;K<G;K++)if(Z[X+K]!==$[K])return!1;if(Y===0)this.state.pos+=G,this.state.column+=G;return!0}check($,Y=0){let Z=this.state.source,X=this.state.pos+Y,G=$.length;if(X+G>Z.length)return!1;for(let K=0;K<G;K++)if(Z[X+K]!==$[K])return!1;return!0}skipWhitespace(){while(!this.isAtEnd()&&this.isWhitespace(this.peek())){if(this.peek()===`
13
+ `)this.state.line++,this.state.column=0;this.advance()}}isWhitespace($){return $===" "||$==="\t"||$===`
14
+ `||$==="\r"}isDigit($){let Y=$.charCodeAt(0);return Y>=48&&Y<=57}isAlpha($){let Y=$.charCodeAt(0);return Y>=97&&Y<=122||Y>=65&&Y<=90}isAlphaNumeric($){let Y=$.charCodeAt(0);return Y>=48&&Y<=57||Y>=97&&Y<=122||Y>=65&&Y<=90}addToken($,Y){this.state.tokens.push({type:$,value:Y,line:this.state.line,column:this.state.column-Y.length})}}var $6=H(()=>{z2();Q2();z2()});class J1{tokens;current=0;source;constructor($,Y){this.tokens=$,this.source=Y}parse(){let $=[];while(!this.isAtEnd()){let Y=this.parseStatement();if(Y)$.push(Y)}return{type:"Template",body:$,line:1,column:1}}parseStatement(){switch(this.peek().type){case"TEXT":return this.parseText();case"VARIABLE_START":return this.parseOutput();case"BLOCK_START":return this.parseBlock();case"EOF":return null;default:return this.advance(),null}}parseText(){let $=this.advance();return{type:"Text",value:$.value,line:$.line,column:$.column}}parseOutput(){let $=this.advance(),Y=this.parseExpression();return this.expect("VARIABLE_END"),{type:"Output",expression:Y,line:$.line,column:$.column}}parseBlock(){let $=this.advance(),Y=this.expect("NAME");switch(Y.value){case"if":return this.parseIf($);case"for":return this.parseFor($);case"block":return this.parseBlockTag($);case"extends":return this.parseExtends($);case"include":return this.parseInclude($);case"set":return this.parseSet($);case"with":return this.parseWith($);case"load":return this.parseLoad($);case"url":return this.parseUrl($);case"static":return this.parseStatic($);case"now":return this.parseNow($);case"comment":return this.parseComment($);case"spaceless":case"autoescape":case"verbatim":return this.parseSimpleBlock($,Y.value);case"cycle":return this.parseCycle($);case"firstof":return this.parseFirstof($);case"ifchanged":return this.parseIfchanged($);case"regroup":return this.parseRegroup($);case"widthratio":return this.parseWidthratio($);case"lorem":return this.parseLorem($);case"csrf_token":return this.parseCsrfToken($);case"debug":return this.parseDebug($);case"templatetag":return this.parseTemplatetag($);case"ifequal":return this.parseIfequal($,!1);case"ifnotequal":return this.parseIfequal($,!0);default:return this.skipToBlockEnd(),null}}parseIf($){let Y=this.parseExpression();this.expect("BLOCK_END");let Z=[],X=[],G=[];while(!this.isAtEnd()){if(this.checkBlockTag("elif")||this.checkBlockTag("else")||this.checkBlockTag("endif"))break;let K=this.parseStatement();if(K)Z.push(K)}while(this.checkBlockTag("elif")){this.advance(),this.advance();let K=this.parseExpression();this.expect("BLOCK_END");let W=[];while(!this.isAtEnd()){if(this.checkBlockTag("elif")||this.checkBlockTag("else")||this.checkBlockTag("endif"))break;let z=this.parseStatement();if(z)W.push(z)}X.push({test:K,body:W})}if(this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endif"))break;let K=this.parseStatement();if(K)G.push(K)}}return this.expectBlockTag("endif"),{type:"If",test:Y,body:Z,elifs:X,else_:G,line:$.line,column:$.column}}parseFor($){let Y,Z=this.expect("NAME").value;if(this.check("COMMA")){let Q=[Z];while(this.match("COMMA"))Q.push(this.expect("NAME").value);Y=Q}else Y=Z;let X=this.expect("NAME");if(X.value!=="in")throw this.error(`Expected 'in' in for loop, got '${X.value}'`);let G=this.parseExpression(),K=this.check("NAME")&&this.peek().value==="recursive";if(K)this.advance();this.expect("BLOCK_END");let W=[],z=[];while(!this.isAtEnd()){if(this.checkBlockTag("empty")||this.checkBlockTag("else")||this.checkBlockTag("endfor"))break;let Q=this.parseStatement();if(Q)W.push(Q)}if(this.checkBlockTag("empty")||this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endfor"))break;let Q=this.parseStatement();if(Q)z.push(Q)}}return this.expectBlockTag("endfor"),{type:"For",target:Y,iter:G,body:W,else_:z,recursive:K,line:$.line,column:$.column}}parseBlockTag($){let Y=this.expect("NAME").value,Z=this.check("NAME")&&this.peek().value==="scoped";if(Z)this.advance();this.expect("BLOCK_END");let X=[];while(!this.isAtEnd()){if(this.checkBlockTag("endblock"))break;let G=this.parseStatement();if(G)X.push(G)}if(this.advance(),this.advance(),this.check("NAME"))this.advance();return this.expect("BLOCK_END"),{type:"Block",name:Y,body:X,scoped:Z,line:$.line,column:$.column}}parseExtends($){let Y=this.parseExpression();return this.expect("BLOCK_END"),{type:"Extends",template:Y,line:$.line,column:$.column}}parseInclude($){let Y=this.parseExpression(),Z=null,X=!1,G=!1;while(this.check("NAME")){let K=this.peek().value;if(K==="ignore"&&this.peekNext()?.value==="missing")this.advance(),this.advance(),G=!0;else if(K==="with")this.advance(),Z=this.parseKeywordArgs();else if(K==="only")this.advance(),X=!0;else if(K==="without"){if(this.advance(),this.check("NAME")&&this.peek().value==="context")this.advance(),X=!0}else break}return this.expect("BLOCK_END"),{type:"Include",template:Y,context:Z,only:X,ignoreMissing:G,line:$.line,column:$.column}}parseSet($){let Y=this.expect("NAME").value;this.expect("ASSIGN");let Z=this.parseExpression();return this.expect("BLOCK_END"),{type:"Set",target:Y,value:Z,line:$.line,column:$.column}}parseWith($){let Y=[];do{let X=this.expect("NAME").value;this.expect("ASSIGN");let G=this.parseExpression();Y.push({target:X,value:G})}while(this.match("COMMA")||this.check("NAME")&&this.peekNext()?.type==="ASSIGN");this.expect("BLOCK_END");let Z=[];while(!this.isAtEnd()){if(this.checkBlockTag("endwith"))break;let X=this.parseStatement();if(X)Z.push(X)}return this.expectBlockTag("endwith"),{type:"With",assignments:Y,body:Z,line:$.line,column:$.column}}parseLoad($){let Y=[];while(this.check("NAME"))Y.push(this.advance().value);return this.expect("BLOCK_END"),{type:"Load",names:Y,line:$.line,column:$.column}}parseUrl($){let Y=this.parseExpression(),Z=[],X={},G=null;while(!this.check("BLOCK_END")){if(this.check("NAME")&&this.peek().value==="as"){this.advance(),G=this.expect("NAME").value;break}if(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let K=this.advance().value;this.advance(),X[K]=this.parseExpression()}else Z.push(this.parseExpression())}return this.expect("BLOCK_END"),{type:"Url",name:Y,args:Z,kwargs:X,asVar:G,line:$.line,column:$.column}}parseStatic($){let Y=this.parseExpression(),Z=null;if(this.check("NAME")&&this.peek().value==="as")this.advance(),Z=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Static",path:Y,asVar:Z,line:$.line,column:$.column}}parseNow($){let Y=this.parseExpression(),Z=null;if(this.check("NAME")&&this.peek().value==="as")this.advance(),Z=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Now",format:Y,asVar:Z,line:$.line,column:$.column}}parseComment($){this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endcomment"))break;this.advance()}return this.expectBlockTag("endcomment"),null}parseSimpleBlock($,Y){this.skipToBlockEnd();let Z=`end${Y}`;while(!this.isAtEnd()){if(this.checkBlockTag(Z))break;this.advance()}if(this.checkBlockTag(Z))this.advance(),this.advance(),this.expect("BLOCK_END");return null}parseCycle($){let Y=[],Z=null,X=!1;while(!this.check("BLOCK_END")){if(this.check("NAME")&&this.peek().value==="as"){if(this.advance(),Z=this.expect("NAME").value,this.check("NAME")&&this.peek().value==="silent")this.advance(),X=!0;break}Y.push(this.parseExpression())}return this.expect("BLOCK_END"),{type:"Cycle",values:Y,asVar:Z,silent:X,line:$.line,column:$.column}}parseFirstof($){let Y=[],Z=null,X=null;while(!this.check("BLOCK_END")){if(this.check("NAME")&&this.peek().value==="as"){this.advance(),X=this.expect("NAME").value;break}Y.push(this.parseExpression())}if(Y.length>0){let G=Y[Y.length-1];if(G.type==="Literal"&&typeof G.value==="string")Z=Y.pop()}return this.expect("BLOCK_END"),{type:"Firstof",values:Y,fallback:Z,asVar:X,line:$.line,column:$.column}}parseIfchanged($){let Y=[];while(!this.check("BLOCK_END"))Y.push(this.parseExpression());this.expect("BLOCK_END");let Z=[],X=[];while(!this.isAtEnd()){if(this.checkBlockTag("else")||this.checkBlockTag("endifchanged"))break;let G=this.parseStatement();if(G)Z.push(G)}if(this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag("endifchanged"))break;let G=this.parseStatement();if(G)X.push(G)}}return this.expectBlockTag("endifchanged"),{type:"Ifchanged",values:Y,body:Z,else_:X,line:$.line,column:$.column}}parseRegroup($){let Y=this.parseExpression();this.expectName("by");let Z=this.expect("NAME").value;this.expectName("as");let X=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Regroup",target:Y,key:Z,asVar:X,line:$.line,column:$.column}}parseWidthratio($){let Y=this.parseExpression(),Z=this.parseExpression(),X=this.parseExpression(),G=null;if(this.check("NAME")&&this.peek().value==="as")this.advance(),G=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Widthratio",value:Y,maxValue:Z,maxWidth:X,asVar:G,line:$.line,column:$.column}}parseLorem($){let Y=null,Z="p",X=!1;if(this.check("NUMBER"))Y={type:"Literal",value:parseInt(this.advance().value,10),line:$.line,column:$.column};if(this.check("NAME")){let G=this.peek().value.toLowerCase();if(G==="w"||G==="p"||G==="b")Z=G,this.advance()}if(this.check("NAME")&&this.peek().value==="random")X=!0,this.advance();return this.expect("BLOCK_END"),{type:"Lorem",count:Y,method:Z,random:X,line:$.line,column:$.column}}parseCsrfToken($){return this.expect("BLOCK_END"),{type:"CsrfToken",line:$.line,column:$.column}}parseDebug($){return this.expect("BLOCK_END"),{type:"Debug",line:$.line,column:$.column}}parseTemplatetag($){let Y=this.expect("NAME").value;return this.expect("BLOCK_END"),{type:"Templatetag",tagType:Y,line:$.line,column:$.column}}parseIfequal($,Y){let Z=this.parseExpression(),X=this.parseExpression();this.expect("BLOCK_END");let G={type:"Compare",left:Z,ops:[{operator:Y?"!=":"==",right:X}],line:$.line,column:$.column},K=[],W=[],z=Y?"endifnotequal":"endifequal";while(!this.isAtEnd()){if(this.checkBlockTag("else")||this.checkBlockTag(z))break;let Q=this.parseStatement();if(Q)K.push(Q)}if(this.checkBlockTag("else")){this.advance(),this.advance(),this.expect("BLOCK_END");while(!this.isAtEnd()){if(this.checkBlockTag(z))break;let Q=this.parseStatement();if(Q)W.push(Q)}}return this.expectBlockTag(z),{type:"If",test:G,body:K,elifs:[],else_:W,line:$.line,column:$.column}}parseExpression(){return this.parseConditional()}parseConditional(){let $=this.parseOr();if(this.check("NAME")&&this.peek().value==="if"){this.advance();let Y=this.parseOr();this.expectName("else");let Z=this.parseConditional();$={type:"Conditional",test:Y,trueExpr:$,falseExpr:Z,line:$.line,column:$.column}}return $}parseOr(){let $=this.parseAnd();while(this.check("OR")||this.check("NAME")&&this.peek().value==="or"){this.advance();let Y=this.parseAnd();$={type:"BinaryOp",operator:"or",left:$,right:Y,line:$.line,column:$.column}}return $}parseAnd(){let $=this.parseNot();while(this.check("AND")||this.check("NAME")&&this.peek().value==="and"){this.advance();let Y=this.parseNot();$={type:"BinaryOp",operator:"and",left:$,right:Y,line:$.line,column:$.column}}return $}parseNot(){if(this.check("NOT")||this.check("NAME")&&this.peek().value==="not"){let $=this.advance();return{type:"UnaryOp",operator:"not",operand:this.parseNot(),line:$.line,column:$.column}}return this.parseCompare()}parseCompare(){let $=this.parseAddSub(),Y=[];while(!0){let Z=null;if(this.match("EQ"))Z="==";else if(this.match("NE"))Z="!=";else if(this.match("LT"))Z="<";else if(this.match("GT"))Z=">";else if(this.match("LE"))Z="<=";else if(this.match("GE"))Z=">=";else if(this.check("NAME")){let G=this.peek().value;if(G==="in")this.advance(),Z="in";else if(G==="not"&&this.peekNext()?.value==="in")this.advance(),this.advance(),Z="not in";else if(G==="is"){this.advance();let K=this.check("NOT");if(K)this.advance();let z=this.expect("NAME").value,Q=[];if(this.match("LPAREN")){while(!this.check("RPAREN"))if(Q.push(this.parseExpression()),!this.check("RPAREN"))this.expect("COMMA");this.expect("RPAREN")}$={type:"TestExpr",node:$,test:z,args:Q,negated:K,line:$.line,column:$.column};continue}}if(!Z)break;let X=this.parseAddSub();Y.push({operator:Z,right:X})}if(Y.length===0)return $;return{type:"Compare",left:$,ops:Y,line:$.line,column:$.column}}parseAddSub(){let $=this.parseMulDiv();while(this.check("ADD")||this.check("SUB")||this.check("TILDE")){let Y=this.advance(),Z=this.parseMulDiv();$={type:"BinaryOp",operator:Y.value,left:$,right:Z,line:$.line,column:$.column}}return $}parseMulDiv(){let $=this.parseUnary();while(this.check("MUL")||this.check("DIV")||this.check("MOD")){let Y=this.advance(),Z=this.parseUnary();$={type:"BinaryOp",operator:Y.value,left:$,right:Z,line:$.line,column:$.column}}return $}parseUnary(){if(this.check("SUB")||this.check("ADD")){let $=this.advance(),Y=this.parseUnary();return{type:"UnaryOp",operator:$.value,operand:Y,line:$.line,column:$.column}}return this.parseFilter()}parseFilter(){let $=this.parsePostfix();while(this.match("PIPE")){let Y=this.expect("NAME").value,Z=[],X={};if(this.match("COLON"))if(this.check("SUB")||this.check("ADD")){let G=this.advance(),K=this.parsePostfix();Z.push({type:"UnaryOp",operator:G.value,operand:K,line:G.line,column:G.column})}else Z.push(this.parsePostfix());else if(this.match("LPAREN")){while(!this.check("RPAREN")){if(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let G=this.advance().value;this.advance(),X[G]=this.parseExpression()}else Z.push(this.parseExpression());if(!this.check("RPAREN"))this.expect("COMMA")}this.expect("RPAREN")}$={type:"FilterExpr",node:$,filter:Y,args:Z,kwargs:X,line:$.line,column:$.column}}return $}parsePostfix(){let $=this.parsePrimary();while(!0)if(this.match("DOT")){let Y;if(this.check("NUMBER"))Y=this.advance().value;else Y=this.expect("NAME").value;$={type:"GetAttr",object:$,attribute:Y,line:$.line,column:$.column}}else if(this.match("LBRACKET")){let Y=this.parseExpression();this.expect("RBRACKET"),$={type:"GetItem",object:$,index:Y,line:$.line,column:$.column}}else if(this.match("LPAREN")){let Y=[],Z={};while(!this.check("RPAREN")){if(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let X=this.advance().value;this.advance(),Z[X]=this.parseExpression()}else Y.push(this.parseExpression());if(!this.check("RPAREN"))this.expect("COMMA")}this.expect("RPAREN"),$={type:"FunctionCall",callee:$,args:Y,kwargs:Z,line:$.line,column:$.column}}else break;return $}parsePrimary(){let $=this.peek();if(this.match("STRING"))return{type:"Literal",value:$.value,line:$.line,column:$.column};if(this.match("NUMBER"))return{type:"Literal",value:$.value.includes(".")?parseFloat($.value):parseInt($.value,10),line:$.line,column:$.column};if(this.check("NAME")){let Y=this.advance().value;if(Y==="true"||Y==="True")return{type:"Literal",value:!0,line:$.line,column:$.column};if(Y==="false"||Y==="False")return{type:"Literal",value:!1,line:$.line,column:$.column};if(Y==="none"||Y==="None"||Y==="null")return{type:"Literal",value:null,line:$.line,column:$.column};return{type:"Name",name:Y,line:$.line,column:$.column}}if(this.match("LPAREN")){let Y=this.parseExpression();return this.expect("RPAREN"),Y}if(this.match("LBRACKET")){let Y=[];while(!this.check("RBRACKET"))if(Y.push(this.parseExpression()),!this.check("RBRACKET"))this.expect("COMMA");return this.expect("RBRACKET"),{type:"Array",elements:Y,line:$.line,column:$.column}}if(this.match("LBRACE")){let Y=[];while(!this.check("RBRACE")){let Z=this.parseExpression();this.expect("COLON");let X=this.parseExpression();if(Y.push({key:Z,value:X}),!this.check("RBRACE"))this.expect("COMMA")}return this.expect("RBRACE"),{type:"Object",pairs:Y,line:$.line,column:$.column}}throw this.error(`Unexpected token: ${$.type} (${$.value})`)}parseKeywordArgs(){let $={};while(this.check("NAME")&&this.peekNext()?.type==="ASSIGN"){let Y=this.advance().value;this.advance(),$[Y]=this.parseExpression()}return $}checkBlockTag($){if(this.peek().type!=="BLOCK_START")return!1;let Y=this.current+1;if(Y>=this.tokens.length)return!1;let Z=this.tokens[Y];return Z.type==="NAME"&&Z.value===$}expectBlockTag($){this.advance();let Y=this.expect("NAME");if(Y.value!==$)throw this.error(`Expected '${$}', got '${Y.value}'`);this.expect("BLOCK_END")}expectName($){let Y=this.expect("NAME");if(Y.value!==$)throw this.error(`Expected '${$}', got '${Y.value}'`)}skipToBlockEnd(){while(!this.isAtEnd()&&!this.check("BLOCK_END"))this.advance();if(this.check("BLOCK_END"))this.advance()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}peekNext(){if(this.current+1>=this.tokens.length)return null;return this.tokens[this.current+1]}advance(){if(!this.isAtEnd())this.current++;return this.tokens[this.current-1]}check($){if(this.isAtEnd())return!1;return this.peek().type===$}match($){if(this.check($))return this.advance(),!0;return!1}expect($){if(this.check($))return this.advance();let Y=this.peek();throw this.error(`Expected ${$}, got ${Y.type} (${Y.value})`)}error($){let Y=this.peek();return new q0($,{line:Y.line,column:Y.column,source:this.source})}}var J2=H(()=>{$6();Q2()});var N1="0.39.0";function cY($,Y={auto:!1}){if(hY)throw Error(`you must \`import '@anthropic-ai/sdk/shims/${$.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(H1)throw Error(`can't \`import '@anthropic-ai/sdk/shims/${$.kind}'\` after \`import '@anthropic-ai/sdk/shims/${H1}'\``);hY=Y.auto,H1=$.kind,N2=$.fetch,oZ=$.Request,tZ=$.Response,eZ=$.Headers,gY=$.FormData,$3=$.Blob,Z6=$.File,H2=$.ReadableStream,vY=$.getMultipartRequestOptions,U2=$.getDefaultAgent,v1=$.fileFromPath,mY=$.isFsReadStream}var hY=!1,H1=void 0,N2=void 0,oZ=void 0,tZ=void 0,eZ=void 0,gY=void 0,$3=void 0,Z6=void 0,H2=void 0,vY=void 0,U2=void 0,v1=void 0,mY=void 0;var B2;var dY=H(()=>{B2=class B2{constructor($){this.body=$}get[Symbol.toStringTag](){return"MultipartBody"}}});function uY({manuallyImported:$}={}){let Y=$?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",Z,X,G,K;try{Z=fetch,X=Request,G=Response,K=Headers}catch(W){throw Error(`this environment is missing the following Web Fetch API type: ${W.message}. ${Y}`)}return{kind:"web",fetch:Z,Request:X,Response:G,Headers:K,FormData:typeof FormData<"u"?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${Y}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${Y}`)}},File:typeof File<"u"?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${Y}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${Y}`)}},getMultipartRequestOptions:async(W,z)=>({...z,body:new B2(W)}),getDefaultAgent:(W)=>{return},fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:(W)=>!1}}var pY=H(()=>{dY()});import{ReadStream as Z3}from"fs";function lY(){let $=uY();function Y(Z){return Z instanceof Z3}return{...$,isFsReadStream:Y}}var iY=H(()=>{pY()});var nY=H(()=>{iY()});var p4=H(()=>{nY();if(!H1)cY(lY(),{auto:!0})});var M,c,a,T0,U1,m1,c1,d1,u1,p1,l1,i1,n1;var F0=H(()=>{j0();M=class M extends Error{};c=class c extends M{constructor($,Y,Z,X){super(`${c.makeMessage($,Y,Z)}`);this.status=$,this.headers=X,this.request_id=X?.["request-id"],this.error=Y}static makeMessage($,Y,Z){let X=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):Z;if($&&X)return`${$} ${X}`;if($)return`${$} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate($,Y,Z,X){if(!$||!X)return new T0({message:Z,cause:X6(Y)});let G=Y;if($===400)return new m1($,G,Z,X);if($===401)return new c1($,G,Z,X);if($===403)return new d1($,G,Z,X);if($===404)return new u1($,G,Z,X);if($===409)return new p1($,G,Z,X);if($===422)return new l1($,G,Z,X);if($===429)return new i1($,G,Z,X);if($>=500)return new n1($,G,Z,X);return new c($,G,Z,X)}};a=class a extends c{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}};T0=class T0 extends c{constructor({message:$,cause:Y}){super(void 0,void 0,$||"Connection error.",void 0);if(Y)this.cause=Y}};U1=class U1 extends T0{constructor({message:$}={}){super({message:$??"Request timed out."})}};m1=class m1 extends c{};c1=class c1 extends c{};d1=class d1 extends c{};u1=class u1 extends c{};p1=class p1 extends c{};l1=class l1 extends c{};i1=class i1 extends c{};n1=class n1 extends c{}});class s0{constructor(){J0.set(this,void 0),this.buffer=new Uint8Array,G6(this,J0,null,"f")}decode($){if($==null)return[];let Y=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,Z=new Uint8Array(this.buffer.length+Y.length);Z.set(this.buffer),Z.set(Y,this.buffer.length),this.buffer=Z;let X=[],G;while((G=K3(this.buffer,B1(this,J0,"f")))!=null){if(G.carriage&&B1(this,J0,"f")==null){G6(this,J0,G.index,"f");continue}if(B1(this,J0,"f")!=null&&(G.index!==B1(this,J0,"f")+1||G.carriage)){X.push(this.decodeText(this.buffer.slice(0,B1(this,J0,"f")-1))),this.buffer=this.buffer.slice(B1(this,J0,"f")),G6(this,J0,null,"f");continue}let K=B1(this,J0,"f")!==null?G.preceding-1:G.preceding,W=this.decodeText(this.buffer.slice(0,K));X.push(W),this.buffer=this.buffer.slice(G.index),G6(this,J0,null,"f")}return X}decodeText($){if($==null)return"";if(typeof $==="string")return $;if(typeof Buffer<"u"){if($ instanceof Buffer)return $.toString();if($ instanceof Uint8Array)return Buffer.from($).toString();throw new M(`Unexpected: received non-Uint8Array (${$.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if($ instanceof Uint8Array||$ instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode($);throw new M(`Unexpected: received non-Uint8Array/ArrayBuffer (${$.constructor.name}) in a web platform. Please report this error.`)}throw new M("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
15
+ `)}}function K3($,Y){for(let G=Y??0;G<$.length;G++){if($[G]===10)return{preceding:G,index:G+1,carriage:!1};if($[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function aY($){for(let X=0;X<$.length-1;X++){if($[X]===10&&$[X+1]===10)return X+2;if($[X]===13&&$[X+1]===13)return X+2;if($[X]===13&&$[X+1]===10&&X+3<$.length&&$[X+2]===13&&$[X+3]===10)return X+4}return-1}var G6=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},B1=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},J0;var D2=H(()=>{F0();J0=new WeakMap;s0.NEWLINE_CHARS=new Set([`
16
+ `,"\r"]);s0.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function l4($){if($[Symbol.asyncIterator])return $;let Y=$.getReader();return{async next(){try{let Z=await Y.read();if(Z?.done)Y.releaseLock();return Z}catch(Z){throw Y.releaseLock(),Z}},async return(){let Z=Y.cancel();return Y.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function*W3($,Y){if(!$.body)throw Y.abort(),new M("Attempted to iterate over a response with no body");let Z=new rY,X=new s0,G=l4($.body);for await(let K of z3(G))for(let W of X.decode(K)){let z=Z.decode(W);if(z)yield z}for(let K of X.flush()){let W=Z.decode(K);if(W)yield W}}async function*z3($){let Y=new Uint8Array;for await(let Z of $){if(Z==null)continue;let X=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?new TextEncoder().encode(Z):Z,G=new Uint8Array(Y.length+X.length);G.set(Y),G.set(X,Y.length),Y=G;let K;while((K=aY(Y))!==-1)yield Y.slice(0,K),Y=Y.slice(K)}if(Y.length>0)yield Y}class rY{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
17
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push($),$.startsWith(":"))return null;let[Y,Z,X]=Q3($,":");if(X.startsWith(" "))X=X.substring(1);if(Y==="event")this.event=X;else if(Y==="data")this.data.push(X);return null}}function Q3($,Y){let Z=$.indexOf(Y);if(Z!==-1)return[$.substring(0,Z),Y,$.substring(Z+Y.length)];return[$,"",""]}var N0;var K6=H(()=>{p4();F0();D2();j0();F0();N0=class N0{constructor($,Y){this.iterator=$,this.controller=Y}static fromSSEResponse($,Y){let Z=!1;async function*X(){if(Z)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let K of W3($,Y)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(W){throw console.error("Could not parse message into JSON:",K.data),console.error("From chunk:",K.raw),W}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(W){throw console.error("Could not parse message into JSON:",K.data),console.error("From chunk:",K.raw),W}if(K.event==="ping")continue;if(K.event==="error")throw c.generate(void 0,`SSE Error: ${K.data}`,K.data,V2($.headers))}G=!0}catch(K){if(K instanceof Error&&K.name==="AbortError")return;throw K}finally{if(!G)Y.abort()}}return new N0(X,Y)}static fromReadableStream($,Y){let Z=!1;async function*X(){let K=new s0,W=l4($);for await(let z of W)for(let Q of K.decode(z))yield Q;for(let z of K.flush())yield z}async function*G(){if(Z)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let K=!1;try{for await(let W of X()){if(K)continue;if(W)yield JSON.parse(W)}K=!0}catch(W){if(W instanceof Error&&W.name==="AbortError")return;throw W}finally{if(!K)Y.abort()}}return new N0(G,Y)}[Symbol.asyncIterator](){return this.iterator()}tee(){let $=[],Y=[],Z=this.iterator(),X=(G)=>{return{next:()=>{if(G.length===0){let K=Z.next();$.push(K),Y.push(K)}return G.shift()}}};return[new N0(()=>X($),this.controller),new N0(()=>X(Y),this.controller)]}toReadableStream(){let $=this,Y,Z=new TextEncoder;return new H2({async start(){Y=$[Symbol.asyncIterator]()},async pull(X){try{let{value:G,done:K}=await Y.next();if(K)return X.close();let W=Z.encode(JSON.stringify(G)+`
18
+ `);X.enqueue(W)}catch(G){X.error(G)}},async cancel(){await Y.return?.()}})}}});async function W6($,Y,Z){if($=await $,N3($))return $;if(J3($)){let G=await $.blob();Y||(Y=new URL($.url).pathname.split(/[\\/]/).pop()??"unknown_file");let K=i4(G)?[await G.arrayBuffer()]:[G];return new Z6(K,Y,Z)}let X=await H3($);if(Y||(Y=B3($)??"unknown_file"),!Z?.type){let G=X[0]?.type;if(typeof G==="string")Z={...Z,type:G}}return new Z6(X,Y,Z)}async function H3($){let Y=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Y.push($);else if(i4($))Y.push(await $.arrayBuffer());else if(D3($))for await(let Z of $)Y.push(Z);else throw Error(`Unexpected data type: ${typeof $}; constructor: ${$?.constructor?.name}; props: ${U3($)}`);return Y}function U3($){return`[${Object.getOwnPropertyNames($).map((Z)=>`"${Z}"`).join(", ")}]`}function B3($){return F2($.name)||F2($.filename)||F2($.path)?.split(/[\\/]/).pop()}var J3=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function",N3=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&i4($),i4=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",F2=($)=>{if(typeof $==="string")return $;if(typeof Buffer<"u"&&$ instanceof Buffer)return String($);return},D3=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",w2=($)=>$&&typeof $==="object"&&$.body&&$[Symbol.toStringTag]==="MultipartBody";var z6=H(()=>{p4();p4()});async function $9($){let{response:Y}=$;if($.options.stream){if(a1("response",Y.status,Y.url,Y.headers,Y.body),$.options.__streamClass)return $.options.__streamClass.fromSSEResponse(Y,$.controller);return N0.fromSSEResponse(Y,$.controller)}if(Y.status===204)return null;if($.options.__binaryResponse)return Y;let Z=Y.headers.get("content-type");if(Z?.includes("application/json")||Z?.includes("application/vnd.api+json")){let K=await Y.json();return a1("response",Y.status,Y.url,Y.headers,K),Y9(K,Y)}let G=await Y.text();return a1("response",Y.status,Y.url,Y.headers,G),G}function Y9($,Y){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Y.headers.get("request-id"),enumerable:!1})}class O2{constructor({baseURL:$,maxRetries:Y=2,timeout:Z=600000,httpAgent:X,fetch:G}){this.baseURL=$,this.maxRetries=L2("maxRetries",Y),this.timeout=L2("timeout",Z),this.httpAgent=X,this.fetch=G??N2}authHeaders($){return{}}defaultHeaders($){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...E3(),...this.authHeaders($)}}validateHeaders($,Y){}defaultIdempotencyKey(){return`stainless-node-retry-${x3()}`}get($,Y){return this.methodRequest("get",$,Y)}post($,Y){return this.methodRequest("post",$,Y)}patch($,Y){return this.methodRequest("patch",$,Y)}put($,Y){return this.methodRequest("put",$,Y)}delete($,Y){return this.methodRequest("delete",$,Y)}methodRequest($,Y,Z){return this.request(Promise.resolve(Z).then(async(X)=>{let G=X&&i4(X?.body)?new DataView(await X.body.arrayBuffer()):X?.body instanceof DataView?X.body:X?.body instanceof ArrayBuffer?new DataView(X.body):X&&ArrayBuffer.isView(X?.body)?new DataView(X.body.buffer):X?.body;return{method:$,path:Y,...X,body:G}}))}getAPIList($,Y,Z){return this.requestAPIList(Y,{method:"get",path:$,...Z})}calculateContentLength($){if(typeof $==="string"){if(typeof Buffer<"u")return Buffer.byteLength($,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode($).length.toString()}else if(ArrayBuffer.isView($))return $.byteLength.toString();return null}buildRequest($,{retryCount:Y=0}={}){$={...$};let{method:Z,path:X,query:G,headers:K={}}=$,W=ArrayBuffer.isView($.body)||$.__binaryRequest&&typeof $.body==="string"?$.body:w2($.body)?$.body.body:$.body?JSON.stringify($.body,null,2):null,z=this.calculateContentLength(W),Q=this.buildURL(X,G);if("timeout"in $)L2("timeout",$.timeout);$.timeout=$.timeout??this.timeout;let J=$.httpAgent??this.httpAgent??U2(Q),U=$.timeout+1000;if(typeof J?.options?.timeout==="number"&&U>(J.options.timeout??0))J.options.timeout=U;if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();K[this.idempotencyHeader]=$.idempotencyKey}let N=this.buildHeaders({options:$,headers:K,contentLength:z,retryCount:Y});return{req:{method:Z,...W&&{body:W},headers:N,...J&&{agent:J},signal:$.signal??null},url:Q,timeout:$.timeout}}buildHeaders({options:$,headers:Y,contentLength:Z,retryCount:X}){let G={};if(Z)G["content-length"]=Z;let K=this.defaultHeaders($);if(eY(G,K),eY(G,Y),w2($.body)&&H1!=="node")delete G["content-type"];if(J6(K,"x-stainless-retry-count")===void 0&&J6(Y,"x-stainless-retry-count")===void 0)G["x-stainless-retry-count"]=String(X);if(J6(K,"x-stainless-timeout")===void 0&&J6(Y,"x-stainless-timeout")===void 0&&$.timeout)G["x-stainless-timeout"]=String($.timeout);return this.validateHeaders(G,Y),G}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new M("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Y,options:Z}){}parseHeaders($){return!$?{}:(Symbol.iterator in $)?Object.fromEntries(Array.from($).map((Y)=>[...Y])):{...$}}makeStatusError($,Y,Z,X){return c.generate($,Y,Z,X)}request($,Y=null){return new N6(this.makeRequest($,Y))}async makeRequest($,Y){let Z=await $,X=Z.maxRetries??this.maxRetries;if(Y==null)Y=X;await this.prepareOptions(Z);let{req:G,url:K,timeout:W}=this.buildRequest(Z,{retryCount:X-Y});if(await this.prepareRequest(G,{url:K,options:Z}),a1("request",K,Z,G.headers),Z.signal?.aborted)throw new a;let z=new AbortController,Q=await this.fetchWithTimeout(K,G,W,z).catch(X6);if(Q instanceof Error){if(Z.signal?.aborted)throw new a;if(Y)return this.retryRequest(Z,Y);if(Q.name==="AbortError")throw new U1;throw new T0({cause:Q})}let J=V2(Q.headers);if(!Q.ok){if(Y&&this.shouldRetry(Q)){let R=`retrying, ${Y} attempts remaining`;return a1(`response (error; ${R})`,Q.status,K,J),this.retryRequest(Z,Y,J)}let U=await Q.text().catch((R)=>X6(R).message),N=q3(U),D=N?void 0:U;throw a1(`response (error; ${Y?"(error; no more retries left)":"(error; not retryable)"})`,Q.status,K,J,D),this.makeStatusError(Q.status,N,D,J)}return{response:Q,options:Z,controller:z}}requestAPIList($,Y){let Z=this.makeRequest(Y,null);return new Z9(this,Z,$)}buildURL($,Y){let Z=_3($)?new URL($):new URL(this.baseURL+(this.baseURL.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery();if(!n4(X))Y={...X,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))Z.search=this.stringifyQuery(Y);return Z.toString()}stringifyQuery($){return Object.entries($).filter(([Y,Z])=>typeof Z<"u").map(([Y,Z])=>{if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`;if(Z===null)return`${encodeURIComponent(Y)}=`;throw new M(`Cannot stringify type ${typeof Z}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout($,Y,Z,X){let{signal:G,...K}=Y||{};if(G)G.addEventListener("abort",()=>X.abort());let W=setTimeout(()=>X.abort(),Z),z={signal:X.signal,...K};if(z.method)z.method=z.method.toUpperCase();let Q=60000,J=setTimeout(()=>{if(z&&z?.agent?.sockets){for(let U of Object.values(z?.agent?.sockets).flat())if(U?.setKeepAlive)U.setKeepAlive(!0,Q)}},Q);return this.fetch.call(void 0,$,z).finally(()=>{clearTimeout(W),clearTimeout(J)})}shouldRetry($){let Y=$.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Y,Z){let X,G=Z?.["retry-after-ms"];if(G){let W=parseFloat(G);if(!Number.isNaN(W))X=W}let K=Z?.["retry-after"];if(K&&!X){let W=parseFloat(K);if(!Number.isNaN(W))X=W*1000;else X=Date.parse(K)-Date.now()}if(!(X&&0<=X&&X<60000)){let W=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(Y,W)}return await A3(X),this.makeRequest($,Y-1)}calculateDefaultRetryTimeoutMillis($,Y){let G=Y-$,K=Math.min(0.5*Math.pow(2,G),8),W=1-Math.random()*0.25;return K*W*1000}getUserAgent(){return`${this.constructor.name}/JS ${N1}`}}function M3(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Y,pattern:Z}of $){let X=Z.exec(navigator.userAgent);if(X){let G=X[1]||0,K=X[2]||0,W=X[3]||0;return{browser:Y,version:`${G}.${K}.${W}`}}}return null}function n4($){if(!$)return!0;for(let Y in $)return!1;return!0}function X9($,Y){return Object.prototype.hasOwnProperty.call($,Y)}function eY($,Y){for(let Z in Y){if(!X9(Y,Z))continue;let X=Z.toLowerCase();if(!X)continue;let G=Y[Z];if(G===null)delete $[X];else if(G!==void 0)$[X]=G}}function a1($,...Y){if(typeof process<"u"&&process?.env?.DEBUG==="true")console.log(`Anthropic:DEBUG:${$}`,...Y)}var F3=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},w3=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},Q6,N6,M2,Z9,V2=($)=>{return new Proxy(Object.fromEntries($.entries()),{get(Y,Z){let X=Z.toString();return Y[X.toLowerCase()]||Y[X]}})},L3,w0=($)=>{return typeof $==="object"&&$!==null&&!n4($)&&Object.keys($).every((Y)=>X9(L3,Y))},O3=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N1,"X-Stainless-OS":oY(Deno.build.os),"X-Stainless-Arch":sY(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N1,"X-Stainless-OS":oY(process.platform),"X-Stainless-Arch":sY(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let $=M3();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},sY=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},oY=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},tY,E3=()=>{return tY??(tY=O3())},q3=($)=>{try{return JSON.parse($)}catch(Y){return}},C3,_3=($)=>{return C3.test($)},A3=($)=>new Promise((Y)=>setTimeout(Y,$)),L2=($,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new M(`${$} must be an integer`);if(Y<0)throw new M(`${$} must be a positive integer`);return Y},X6=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null)try{return Error(JSON.stringify($))}catch{}return Error(String($))},H6=($)=>{if(typeof process<"u")return process.env?.[$]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.($)?.trim();return},x3=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let Y=Math.random()*16|0;return($==="x"?Y:Y&3|8).toString(16)})},G9=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},P3=($)=>{return typeof $?.get==="function"},J6=($,Y)=>{let Z=Y.toLowerCase();if(P3($)){let X=Y[0]?.toUpperCase()+Y.substring(1).replace(/([^\w])(\w)/g,(G,K,W)=>K+W.toUpperCase());for(let G of[Y,Z,Y.toUpperCase(),X]){let K=$.get(G);if(K)return K}}for(let[X,G]of Object.entries($))if(X.toLowerCase()===Z){if(Array.isArray(G)){if(G.length<=1)return G[0];return console.warn(`Received ${G.length} entries for the ${Y} header, using the first entry.`),G[0]}return G}return};var j0=H(()=>{K6();F0();p4();z6();N6=class N6 extends Promise{constructor($,Y=$9){super((Z)=>{Z(null)});this.responsePromise=$,this.parseResponse=Y}_thenUnwrap($){return new N6(this.responsePromise,async(Y)=>Y9($(await this.parseResponse(Y),Y),Y.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Y]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Y,request_id:Y.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then($,Y){return this.parse().then($,Y)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}};M2=class M2{constructor($,Y,Z,X){Q6.set(this,void 0),F3(this,Q6,$,"f"),this.options=X,this.response=Y,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let $=this.nextPageInfo();if(!$)throw new M("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let Y={...this.options};if("params"in $&&typeof Y.query==="object")Y.query={...Y.query,...$.params};else if("url"in $){let Z=[...Object.entries(Y.query||{}),...$.url.searchParams.entries()];for(let[X,G]of Z)$.url.searchParams.set(X,G);Y.query=void 0,Y.path=$.url.toString()}return await w3(this,Q6,"f").requestAPIList(this.constructor,Y)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(Q6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Y of $.getPaginatedItems())yield Y}};Z9=class Z9 extends N6{constructor($,Y,Z){super(Y,async(X)=>new Z($,X.response,await $9(X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Y of $)yield Y}};L3={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0};C3=/^[a-z][a-z0-9+.-]*:/i});var I0;var a4=H(()=>{j0();I0=class I0 extends M2{constructor($,Y,Z,X){super($,Y,Z,X);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.first_id=Z.first_id||null,this.last_id=Z.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let $=this.nextPageInfo();if(!$)return null;if("params"in $)return $.params;let Y=Object.fromEntries($.url.searchParams);if(!Object.keys(Y).length)return null;return Y}nextPageInfo(){if(this.options.query?.before_id){let Y=this.first_id;if(!Y)return null;return{params:{before_id:Y}}}let $=this.last_id;if(!$)return null;return{params:{after_id:$}}}}});var K9=()=>{};class s{constructor($){this._client=$}}var r1,r4;var E2=H(()=>{j0();a4();r1=class r1 extends s{retrieve($,Y){return this._client.get(`/v1/models/${$}?beta=true`,Y)}list($={},Y){if(w0($))return this.list({},$);return this._client.getAPIList("/v1/models?beta=true",r4,{query:$,...Y})}};r4=class r4 extends I0{};r1.BetaModelInfosPage=r4});var s1;var q2=H(()=>{F0();D2();s1=class s1{constructor($,Y){this.iterator=$,this.controller=Y}async*decoder(){let $=new s0;for await(let Y of this.iterator)for(let Z of $.decode(Y))yield JSON.parse(Z);for(let Y of $.flush())yield JSON.parse(Y)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Y){if(!$.body)throw Y.abort(),new M("Attempted to iterate over a response with no body");return new s1(l4($.body),Y)}}});var o1,s4;var C2=H(()=>{j0();a4();q2();F0();o1=class o1 extends s{create($,Y){let{betas:Z,...X}=$;return this._client.post("/v1/messages/batches?beta=true",{body:X,...Y,headers:{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString(),...Y?.headers}})}retrieve($,Y={},Z){if(w0(Y))return this.retrieve($,{},Y);let{betas:X}=Y;return this._client.get(`/v1/messages/batches/${$}?beta=true`,{...Z,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...Z?.headers}})}list($={},Y){if(w0($))return this.list({},$);let{betas:Z,...X}=$;return this._client.getAPIList("/v1/messages/batches?beta=true",s4,{query:X,...Y,headers:{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString(),...Y?.headers}})}delete($,Y={},Z){if(w0(Y))return this.delete($,{},Y);let{betas:X}=Y;return this._client.delete(`/v1/messages/batches/${$}?beta=true`,{...Z,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...Z?.headers}})}cancel($,Y={},Z){if(w0(Y))return this.cancel($,{},Y);let{betas:X}=Y;return this._client.post(`/v1/messages/batches/${$}/cancel?beta=true`,{...Z,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...Z?.headers}})}async results($,Y={},Z){if(w0(Y))return this.results($,{},Y);let X=await this.retrieve($);if(!X.results_url)throw new M(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);let{betas:G}=Y;return this._client.get(X.results_url,{...Z,headers:{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...Z?.headers},__binaryResponse:!0})._thenUnwrap((K,W)=>s1.fromResponse(W.response,W.controller))}};s4=class s4 extends I0{};o1.BetaMessageBatchesPage=s4});var j3=($)=>{let Y=0,Z=[];while(Y<$.length){let X=$[Y];if(X==="\\"){Y++;continue}if(X==="{"){Z.push({type:"brace",value:"{"}),Y++;continue}if(X==="}"){Z.push({type:"brace",value:"}"}),Y++;continue}if(X==="["){Z.push({type:"paren",value:"["}),Y++;continue}if(X==="]"){Z.push({type:"paren",value:"]"}),Y++;continue}if(X===":"){Z.push({type:"separator",value:":"}),Y++;continue}if(X===","){Z.push({type:"delimiter",value:","}),Y++;continue}if(X==='"'){let z="",Q=!1;X=$[++Y];while(X!=='"'){if(Y===$.length){Q=!0;break}if(X==="\\"){if(Y++,Y===$.length){Q=!0;break}z+=X+$[Y],X=$[++Y]}else z+=X,X=$[++Y]}if(X=$[++Y],!Q)Z.push({type:"string",value:z});continue}if(X&&/\s/.test(X)){Y++;continue}let K=/[0-9]/;if(X&&K.test(X)||X==="-"||X==="."){let z="";if(X==="-")z+=X,X=$[++Y];while(X&&K.test(X)||X===".")z+=X,X=$[++Y];Z.push({type:"number",value:z});continue}let W=/[a-z]/i;if(X&&W.test(X)){let z="";while(X&&W.test(X)){if(Y===$.length)break;z+=X,X=$[++Y]}if(z=="true"||z=="false"||z==="null")Z.push({type:"name",value:z});else{Y++;continue}continue}Y++}return Z},t1=($)=>{if($.length===0)return $;let Y=$[$.length-1];switch(Y.type){case"separator":return $=$.slice(0,$.length-1),t1($);break;case"number":let Z=Y.value[Y.value.length-1];if(Z==="."||Z==="-")return $=$.slice(0,$.length-1),t1($);case"string":let X=$[$.length-2];if(X?.type==="delimiter")return $=$.slice(0,$.length-1),t1($);else if(X?.type==="brace"&&X.value==="{")return $=$.slice(0,$.length-1),t1($);break;case"delimiter":return $=$.slice(0,$.length-1),t1($);break}return $},I3=($)=>{let Y=[];if($.map((Z)=>{if(Z.type==="brace")if(Z.value==="{")Y.push("}");else Y.splice(Y.lastIndexOf("}"),1);if(Z.type==="paren")if(Z.value==="[")Y.push("]");else Y.splice(Y.lastIndexOf("]"),1)}),Y.length>0)Y.reverse().map((Z)=>{if(Z==="}")$.push({type:"brace",value:"}"});else if(Z==="]")$.push({type:"paren",value:"]"})});return $},k3=($)=>{let Y="";return $.map((Z)=>{switch(Z.type){case"string":Y+='"'+Z.value+'"';break;default:Y+=Z.value;break}}),Y},U6=($)=>JSON.parse(k3(I3(t1(j3($)))));var _2=()=>{};function J9($){}var t=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},_=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},L0,o0,o4,B6,t4,e4,D6,$$,k0,Y$,V6,F6,e1,w6,L6,A2,W9,x2,P2,R2,S2,z9,Q9="__json_buf",Z$;var N9=H(()=>{F0();K6();_2();Z$=class Z${constructor(){L0.add(this),this.messages=[],this.receivedMessages=[],o0.set(this,void 0),this.controller=new AbortController,o4.set(this,void 0),B6.set(this,()=>{}),t4.set(this,()=>{}),e4.set(this,void 0),D6.set(this,()=>{}),$$.set(this,()=>{}),k0.set(this,{}),Y$.set(this,!1),V6.set(this,!1),F6.set(this,!1),e1.set(this,!1),w6.set(this,void 0),L6.set(this,void 0),x2.set(this,($)=>{if(t(this,V6,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new a;if($ instanceof a)return t(this,F6,!0,"f"),this._emit("abort",$);if($ instanceof M)return this._emit("error",$);if($ instanceof Error){let Y=new M($.message);return Y.cause=$,this._emit("error",Y)}return this._emit("error",new M(String($)))}),t(this,o4,new Promise(($,Y)=>{t(this,B6,$,"f"),t(this,t4,Y,"f")}),"f"),t(this,e4,new Promise(($,Y)=>{t(this,D6,$,"f"),t(this,$$,Y,"f")}),"f"),_(this,o4,"f").catch(()=>{}),_(this,e4,"f").catch(()=>{})}get response(){return _(this,w6,"f")}get request_id(){return _(this,L6,"f")}async withResponse(){let $=await _(this,o4,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Y=new Z$;return Y._run(()=>Y._fromReadableStream($)),Y}static createMessage($,Y,Z){let X=new Z$;for(let G of Y.messages)X._addMessageParam(G);return X._run(()=>X._createMessage($,{...Y,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},_(this,x2,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Y=!0){if(this.receivedMessages.push($),Y)this._emit("message",$)}async _createMessage($,Y,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}_(this,L0,"m",P2).call(this);let{response:G,data:K}=await $.create({...Y,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(G);for await(let W of K)_(this,L0,"m",R2).call(this,W);if(K.controller.signal?.aborted)throw new a;_(this,L0,"m",S2).call(this)}_connected($){if(this.ended)return;t(this,w6,$,"f"),t(this,L6,$?.headers.get("request-id"),"f"),_(this,B6,"f").call(this,$),this._emit("connect")}get ended(){return _(this,Y$,"f")}get errored(){return _(this,V6,"f")}get aborted(){return _(this,F6,"f")}abort(){this.controller.abort()}on($,Y){return(_(this,k0,"f")[$]||(_(this,k0,"f")[$]=[])).push({listener:Y}),this}off($,Y){let Z=_(this,k0,"f")[$];if(!Z)return this;let X=Z.findIndex((G)=>G.listener===Y);if(X>=0)Z.splice(X,1);return this}once($,Y){return(_(this,k0,"f")[$]||(_(this,k0,"f")[$]=[])).push({listener:Y,once:!0}),this}emitted($){return new Promise((Y,Z)=>{if(t(this,e1,!0,"f"),$!=="error")this.once("error",Z);this.once($,Y)})}async done(){t(this,e1,!0,"f"),await _(this,e4,"f")}get currentMessage(){return _(this,o0,"f")}async finalMessage(){return await this.done(),_(this,L0,"m",A2).call(this)}async finalText(){return await this.done(),_(this,L0,"m",W9).call(this)}_emit($,...Y){if(_(this,Y$,"f"))return;if($==="end")t(this,Y$,!0,"f"),_(this,D6,"f").call(this);let Z=_(this,k0,"f")[$];if(Z)_(this,k0,"f")[$]=Z.filter((X)=>!X.once),Z.forEach(({listener:X})=>X(...Y));if($==="abort"){let X=Y[0];if(!_(this,e1,"f")&&!Z?.length)Promise.reject(X);_(this,t4,"f").call(this,X),_(this,$$,"f").call(this,X),this._emit("end");return}if($==="error"){let X=Y[0];if(!_(this,e1,"f")&&!Z?.length)Promise.reject(X);_(this,t4,"f").call(this,X),_(this,$$,"f").call(this,X),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",_(this,L0,"m",A2).call(this))}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}_(this,L0,"m",P2).call(this),this._connected(null);let X=N0.fromReadableStream($,this.controller);for await(let G of X)_(this,L0,"m",R2).call(this,G);if(X.controller.signal?.aborted)throw new a;_(this,L0,"m",S2).call(this)}[(o0=new WeakMap,o4=new WeakMap,B6=new WeakMap,t4=new WeakMap,e4=new WeakMap,D6=new WeakMap,$$=new WeakMap,k0=new WeakMap,Y$=new WeakMap,V6=new WeakMap,F6=new WeakMap,e1=new WeakMap,w6=new WeakMap,L6=new WeakMap,x2=new WeakMap,L0=new WeakSet,A2=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},W9=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(Y.length===0)throw new M("stream ended without producing a content block with type=text");return Y.join(" ")},P2=function(){if(this.ended)return;t(this,o0,void 0,"f")},R2=function(Y){if(this.ended)return;let Z=_(this,L0,"m",z9).call(this,Y);switch(this._emit("streamEvent",Y,Z),Y.type){case"content_block_delta":{let X=Z.content.at(-1);switch(Y.delta.type){case"text_delta":{if(X.type==="text")this._emit("text",Y.delta.text,X.text||"");break}case"citations_delta":{if(X.type==="text")this._emit("citation",Y.delta.citation,X.citations??[]);break}case"input_json_delta":{if(X.type==="tool_use"&&X.input)this._emit("inputJson",Y.delta.partial_json,X.input);break}case"thinking_delta":{if(X.type==="thinking")this._emit("thinking",Y.delta.thinking,X.thinking);break}case"signature_delta":{if(X.type==="thinking")this._emit("signature",X.signature);break}default:J9(Y.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(Z,!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{t(this,o0,Z,"f");break}case"content_block_start":case"message_delta":break}},S2=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");let Y=_(this,o0,"f");if(!Y)throw new M("request ended without sending any chunks");return t(this,o0,void 0,"f"),Y},z9=function(Y){let Z=_(this,o0,"f");if(Y.type==="message_start"){if(Z)throw new M(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!Z)throw new M(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return Z;case"message_delta":return Z.stop_reason=Y.delta.stop_reason,Z.stop_sequence=Y.delta.stop_sequence,Z.usage.output_tokens=Y.usage.output_tokens,Z;case"content_block_start":return Z.content.push(Y.content_block),Z;case"content_block_delta":{let X=Z.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(X?.type==="text")X.text+=Y.delta.text;break}case"citations_delta":{if(X?.type==="text")X.citations??(X.citations=[]),X.citations.push(Y.delta.citation);break}case"input_json_delta":{if(X?.type==="tool_use"){let G=X[Q9]||"";if(G+=Y.delta.partial_json,Object.defineProperty(X,Q9,{value:G,enumerable:!1,writable:!0}),G)X.input=U6(G)}break}case"thinking_delta":{if(X?.type==="thinking")X.thinking+=Y.delta.thinking;break}case"signature_delta":{if(X?.type==="thinking")X.signature=Y.delta.signature;break}default:J9(Y.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("streamEvent",(X)=>{let G=Y.shift();if(G)G.resolve(X);else $.push(X)}),this.on("end",()=>{Z=!0;for(let X of Y)X.resolve(void 0);Y.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),this.on("error",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((G,K)=>Y.push({resolve:G,reject:K})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new N0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var H9,D1;var T2=H(()=>{C2();C2();N9();H9={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};D1=class D1 extends s{constructor(){super(...arguments);this.batches=new o1(this._client)}create($,Y){let{betas:Z,...X}=$;if(X.model in H9)console.warn(`The model '${X.model}' is deprecated and will reach end-of-life on ${H9[X.model]}
19
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages?beta=true",{body:X,timeout:this._client._options.timeout??(X.stream?600000:this._client._calculateNonstreamingTimeout(X.max_tokens)),...Y,headers:{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0,...Y?.headers},stream:$.stream??!1})}stream($,Y){return Z$.createMessage(this,$,Y)}countTokens($,Y){let{betas:Z,...X}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:X,...Y,headers:{"anthropic-beta":[...Z??[],"token-counting-2024-11-01"].toString(),...Y?.headers}})}};D1.Batches=o1;D1.BetaMessageBatchesPage=s4});var b0;var j2=H(()=>{E2();E2();T2();T2();b0=class b0 extends s{constructor(){super(...arguments);this.models=new r1(this._client),this.messages=new D1(this._client)}};b0.Models=r1;b0.BetaModelInfosPage=r4;b0.Messages=D1});var $4;var I2=H(()=>{$4=class $4 extends s{create($,Y){return this._client.post("/v1/complete",{body:$,timeout:this._client._options.timeout??600000,...Y,stream:$.stream??!1})}}});var Y4,X$;var k2=H(()=>{j0();a4();q2();F0();Y4=class Y4 extends s{create($,Y){return this._client.post("/v1/messages/batches",{body:$,...Y})}retrieve($,Y){return this._client.get(`/v1/messages/batches/${$}`,Y)}list($={},Y){if(w0($))return this.list({},$);return this._client.getAPIList("/v1/messages/batches",X$,{query:$,...Y})}delete($,Y){return this._client.delete(`/v1/messages/batches/${$}`,Y)}cancel($,Y){return this._client.post(`/v1/messages/batches/${$}/cancel`,Y)}async results($,Y){let Z=await this.retrieve($);if(!Z.results_url)throw new M(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);return this._client.get(Z.results_url,{...Y,headers:{Accept:"application/binary",...Y?.headers},__binaryResponse:!0})._thenUnwrap((X,G)=>s1.fromResponse(G.response,G.controller))}};X$=class X$ extends I0{};Y4.MessageBatchesPage=X$});function V9($){}var e=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},A=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},O0,t0,G$,O6,K$,W$,M6,z$,f0,Q$,E6,q6,Z4,C6,_6,b2,U9,f2,y2,h2,g2,B9,D9="__json_buf",J$;var F9=H(()=>{F0();K6();_2();J$=class J${constructor(){O0.add(this),this.messages=[],this.receivedMessages=[],t0.set(this,void 0),this.controller=new AbortController,G$.set(this,void 0),O6.set(this,()=>{}),K$.set(this,()=>{}),W$.set(this,void 0),M6.set(this,()=>{}),z$.set(this,()=>{}),f0.set(this,{}),Q$.set(this,!1),E6.set(this,!1),q6.set(this,!1),Z4.set(this,!1),C6.set(this,void 0),_6.set(this,void 0),f2.set(this,($)=>{if(e(this,E6,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new a;if($ instanceof a)return e(this,q6,!0,"f"),this._emit("abort",$);if($ instanceof M)return this._emit("error",$);if($ instanceof Error){let Y=new M($.message);return Y.cause=$,this._emit("error",Y)}return this._emit("error",new M(String($)))}),e(this,G$,new Promise(($,Y)=>{e(this,O6,$,"f"),e(this,K$,Y,"f")}),"f"),e(this,W$,new Promise(($,Y)=>{e(this,M6,$,"f"),e(this,z$,Y,"f")}),"f"),A(this,G$,"f").catch(()=>{}),A(this,W$,"f").catch(()=>{})}get response(){return A(this,C6,"f")}get request_id(){return A(this,_6,"f")}async withResponse(){let $=await A(this,G$,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Y=new J$;return Y._run(()=>Y._fromReadableStream($)),Y}static createMessage($,Y,Z){let X=new J$;for(let G of Y.messages)X._addMessageParam(G);return X._run(()=>X._createMessage($,{...Y,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},A(this,f2,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Y=!0){if(this.receivedMessages.push($),Y)this._emit("message",$)}async _createMessage($,Y,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}A(this,O0,"m",y2).call(this);let{response:G,data:K}=await $.create({...Y,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(G);for await(let W of K)A(this,O0,"m",h2).call(this,W);if(K.controller.signal?.aborted)throw new a;A(this,O0,"m",g2).call(this)}_connected($){if(this.ended)return;e(this,C6,$,"f"),e(this,_6,$?.headers.get("request-id"),"f"),A(this,O6,"f").call(this,$),this._emit("connect")}get ended(){return A(this,Q$,"f")}get errored(){return A(this,E6,"f")}get aborted(){return A(this,q6,"f")}abort(){this.controller.abort()}on($,Y){return(A(this,f0,"f")[$]||(A(this,f0,"f")[$]=[])).push({listener:Y}),this}off($,Y){let Z=A(this,f0,"f")[$];if(!Z)return this;let X=Z.findIndex((G)=>G.listener===Y);if(X>=0)Z.splice(X,1);return this}once($,Y){return(A(this,f0,"f")[$]||(A(this,f0,"f")[$]=[])).push({listener:Y,once:!0}),this}emitted($){return new Promise((Y,Z)=>{if(e(this,Z4,!0,"f"),$!=="error")this.once("error",Z);this.once($,Y)})}async done(){e(this,Z4,!0,"f"),await A(this,W$,"f")}get currentMessage(){return A(this,t0,"f")}async finalMessage(){return await this.done(),A(this,O0,"m",b2).call(this)}async finalText(){return await this.done(),A(this,O0,"m",U9).call(this)}_emit($,...Y){if(A(this,Q$,"f"))return;if($==="end")e(this,Q$,!0,"f"),A(this,M6,"f").call(this);let Z=A(this,f0,"f")[$];if(Z)A(this,f0,"f")[$]=Z.filter((X)=>!X.once),Z.forEach(({listener:X})=>X(...Y));if($==="abort"){let X=Y[0];if(!A(this,Z4,"f")&&!Z?.length)Promise.reject(X);A(this,K$,"f").call(this,X),A(this,z$,"f").call(this,X),this._emit("end");return}if($==="error"){let X=Y[0];if(!A(this,Z4,"f")&&!Z?.length)Promise.reject(X);A(this,K$,"f").call(this,X),A(this,z$,"f").call(this,X),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",A(this,O0,"m",b2).call(this))}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}A(this,O0,"m",y2).call(this),this._connected(null);let X=N0.fromReadableStream($,this.controller);for await(let G of X)A(this,O0,"m",h2).call(this,G);if(X.controller.signal?.aborted)throw new a;A(this,O0,"m",g2).call(this)}[(t0=new WeakMap,G$=new WeakMap,O6=new WeakMap,K$=new WeakMap,W$=new WeakMap,M6=new WeakMap,z$=new WeakMap,f0=new WeakMap,Q$=new WeakMap,E6=new WeakMap,q6=new WeakMap,Z4=new WeakMap,C6=new WeakMap,_6=new WeakMap,f2=new WeakMap,O0=new WeakSet,b2=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},U9=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");let Y=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(Y.length===0)throw new M("stream ended without producing a content block with type=text");return Y.join(" ")},y2=function(){if(this.ended)return;e(this,t0,void 0,"f")},h2=function(Y){if(this.ended)return;let Z=A(this,O0,"m",B9).call(this,Y);switch(this._emit("streamEvent",Y,Z),Y.type){case"content_block_delta":{let X=Z.content.at(-1);switch(Y.delta.type){case"text_delta":{if(X.type==="text")this._emit("text",Y.delta.text,X.text||"");break}case"citations_delta":{if(X.type==="text")this._emit("citation",Y.delta.citation,X.citations??[]);break}case"input_json_delta":{if(X.type==="tool_use"&&X.input)this._emit("inputJson",Y.delta.partial_json,X.input);break}case"thinking_delta":{if(X.type==="thinking")this._emit("thinking",Y.delta.thinking,X.thinking);break}case"signature_delta":{if(X.type==="thinking")this._emit("signature",X.signature);break}default:V9(Y.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(Z,!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{e(this,t0,Z,"f");break}case"content_block_start":case"message_delta":break}},g2=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");let Y=A(this,t0,"f");if(!Y)throw new M("request ended without sending any chunks");return e(this,t0,void 0,"f"),Y},B9=function(Y){let Z=A(this,t0,"f");if(Y.type==="message_start"){if(Z)throw new M(`Unexpected event order, got ${Y.type} before receiving "message_stop"`);return Y.message}if(!Z)throw new M(`Unexpected event order, got ${Y.type} before "message_start"`);switch(Y.type){case"message_stop":return Z;case"message_delta":return Z.stop_reason=Y.delta.stop_reason,Z.stop_sequence=Y.delta.stop_sequence,Z.usage.output_tokens=Y.usage.output_tokens,Z;case"content_block_start":return Z.content.push(Y.content_block),Z;case"content_block_delta":{let X=Z.content.at(Y.index);switch(Y.delta.type){case"text_delta":{if(X?.type==="text")X.text+=Y.delta.text;break}case"citations_delta":{if(X?.type==="text")X.citations??(X.citations=[]),X.citations.push(Y.delta.citation);break}case"input_json_delta":{if(X?.type==="tool_use"){let G=X[D9]||"";if(G+=Y.delta.partial_json,Object.defineProperty(X,D9,{value:G,enumerable:!1,writable:!0}),G)X.input=U6(G)}break}case"thinking_delta":{if(X?.type==="thinking")X.thinking+=Y.delta.thinking;break}case"signature_delta":{if(X?.type==="thinking")X.signature=Y.delta.signature;break}default:V9(Y.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("streamEvent",(X)=>{let G=Y.shift();if(G)G.resolve(X);else $.push(X)}),this.on("end",()=>{Z=!0;for(let X of Y)X.resolve(void 0);Y.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),this.on("error",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((G,K)=>Y.push({resolve:G,reject:K})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new N0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var e0,w9;var v2=H(()=>{k2();k2();F9();e0=class e0 extends s{constructor(){super(...arguments);this.batches=new Y4(this._client)}create($,Y){if($.model in w9)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${w9[$.model]}
20
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages",{body:$,timeout:this._client._options.timeout??($.stream?600000:this._client._calculateNonstreamingTimeout($.max_tokens)),...Y,stream:$.stream??!1})}stream($,Y){return J$.createMessage(this,$,Y)}countTokens($,Y){return this._client.post("/v1/messages/count_tokens",{body:$,...Y})}};w9={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};e0.Batches=Y4;e0.MessageBatchesPage=X$});var V1,X4;var m2=H(()=>{j0();a4();V1=class V1 extends s{retrieve($,Y){return this._client.get(`/v1/models/${$}`,Y)}list($={},Y){if(w0($))return this.list({},$);return this._client.getAPIList("/v1/models",X4,{query:$,...Y})}};X4=class X4 extends I0{};V1.ModelInfosPage=X4});var L9=H(()=>{j2();I2();v2();m2();K9()});var M9={};K2(M9,{toFile:()=>W6,fileFromPath:()=>v1,default:()=>v3,UnprocessableEntityError:()=>l1,RateLimitError:()=>i1,PermissionDeniedError:()=>d1,NotFoundError:()=>u1,InternalServerError:()=>n1,HUMAN_PROMPT:()=>h3,ConflictError:()=>p1,BadRequestError:()=>m1,AuthenticationError:()=>c1,AnthropicError:()=>M,Anthropic:()=>j,APIUserAbortError:()=>a,APIError:()=>c,APIConnectionTimeoutError:()=>U1,APIConnectionError:()=>T0,AI_PROMPT:()=>g3});var O9,j,h3,g3,v3;var E9=H(()=>{j0();F0();z6();L9();I2();m2();j2();v2();z6();F0();j=class j extends O2{constructor({baseURL:$=H6("ANTHROPIC_BASE_URL"),apiKey:Y=H6("ANTHROPIC_API_KEY")??null,authToken:Z=H6("ANTHROPIC_AUTH_TOKEN")??null,...X}={}){let G={apiKey:Y,authToken:Z,...X,baseURL:$||"https://api.anthropic.com"};if(!G.dangerouslyAllowBrowser&&G9())throw new M(`It looks like you're running in a browser-like environment.
21
+
22
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
23
+ If you understand the risks and have appropriate mitigations in place,
24
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
25
+
26
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
27
+ `);super({baseURL:G.baseURL,timeout:G.timeout??600000,httpAgent:G.httpAgent,maxRetries:G.maxRetries,fetch:G.fetch});this.completions=new $4(this),this.messages=new e0(this),this.models=new V1(this),this.beta=new b0(this),this._options=G,this.apiKey=Y,this.authToken=Z}defaultQuery(){return this._options.defaultQuery}defaultHeaders($){return{...super.defaultHeaders($),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders($,Y){if(this.apiKey&&$["x-api-key"])return;if(Y["x-api-key"]===null)return;if(this.authToken&&$.authorization)return;if(Y.authorization===null)return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders($){let Y=this.apiKeyAuth($),Z=this.bearerAuth($);if(Y!=null&&!n4(Y))return Y;if(Z!=null&&!n4(Z))return Z;return{}}apiKeyAuth($){if(this.apiKey==null)return{};return{"X-Api-Key":this.apiKey}}bearerAuth($){if(this.authToken==null)return{};return{Authorization:`Bearer ${this.authToken}`}}};O9=j;j.Anthropic=O9;j.HUMAN_PROMPT=`
28
+
29
+ Human:`;j.AI_PROMPT=`
30
+
31
+ Assistant:`;j.DEFAULT_TIMEOUT=600000;j.AnthropicError=M;j.APIError=c;j.APIConnectionError=T0;j.APIConnectionTimeoutError=U1;j.APIUserAbortError=a;j.NotFoundError=u1;j.ConflictError=p1;j.RateLimitError=i1;j.BadRequestError=m1;j.AuthenticationError=c1;j.InternalServerError=n1;j.PermissionDeniedError=d1;j.UnprocessableEntityError=l1;j.toFile=W6;j.fileFromPath=v1;j.Completions=$4;j.Messages=e0;j.Models=V1;j.ModelInfosPage=X4;j.Beta=b0;({HUMAN_PROMPT:h3,AI_PROMPT:g3}=j),v3=j});function G4($,Y){let Z=Y||process.env.ANTHROPIC_API_KEY;return{name:"anthropic",async available(){return!!Z},async analyze(X,G){let Q=(await new(await Promise.resolve().then(() => (E9(),M9))).default({apiKey:Z}).messages.create({model:$||"claude-sonnet-4-20250514",max_tokens:1500,messages:[{role:"user",content:G.replace("{{TEMPLATE}}",X)}]})).content[0];if(Q.type==="text")return Q.text;throw Error("Unexpected response type from Anthropic")}}}var A6="RFC3986",x6,q9="RFC1738";var c2=H(()=>{x6={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:($)=>String($)}});function _9($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function u2($,Y){if(m3($)){let Z=[];for(let X=0;X<$.length;X+=1)Z.push(Y($[X]));return Z}return Y($)}var m3,A0,d2=1024,C9=($,Y,Z,X,G)=>{if($.length===0)return $;let K=$;if(typeof $==="symbol")K=Symbol.prototype.toString.call($);else if(typeof $!=="string")K=String($);if(Z==="iso-8859-1")return escape(K).replace(/%u[0-9a-f]{4}/gi,function(z){return"%26%23"+parseInt(z.slice(2),16)+"%3B"});let W="";for(let z=0;z<K.length;z+=d2){let Q=K.length>=d2?K.slice(z,z+d2):K,J=[];for(let U=0;U<Q.length;++U){let N=Q.charCodeAt(U);if(N===45||N===46||N===95||N===126||N>=48&&N<=57||N>=65&&N<=90||N>=97&&N<=122||G===q9&&(N===40||N===41)){J[J.length]=Q.charAt(U);continue}if(N<128){J[J.length]=A0[N];continue}if(N<2048){J[J.length]=A0[192|N>>6]+A0[128|N&63];continue}if(N<55296||N>=57344){J[J.length]=A0[224|N>>12]+A0[128|N>>6&63]+A0[128|N&63];continue}U+=1,N=65536+((N&1023)<<10|Q.charCodeAt(U)&1023),J[J.length]=A0[240|N>>18]+A0[128|N>>12&63]+A0[128|N>>6&63]+A0[128|N&63]}W+=J.join("")}return W};var A9=H(()=>{c2();m3=Array.isArray,A0=(()=>{let $=[];for(let Y=0;Y<256;++Y)$.push("%"+((Y<16?"0":"")+Y.toString(16)).toUpperCase());return $})()});function p3($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}function R9($,Y,Z,X,G,K,W,z,Q,J,U,N,D,O,V,R,f,y){let C=$,l=y,b=0,X0=!1;while((l=l.get(p2))!==void 0&&!X0){let T=l.get($);if(b+=1,typeof T<"u")if(T===b)throw RangeError("Cyclic object value");else X0=!0;if(typeof l.get(p2)>"u")b=0}if(typeof J==="function")C=J(Y,C);else if(C instanceof Date)C=D?.(C);else if(Z==="comma"&&x0(C))C=u2(C,function(T){if(T instanceof Date)return D?.(T);return T});if(C===null){if(K)return Q&&!R?Q(Y,i.encoder,f,"key",O):Y;C=""}if(p3(C)||_9(C)){if(Q){let T=R?Y:Q(Y,i.encoder,f,"key",O);return[V?.(T)+"="+V?.(Q(C,i.encoder,f,"value",O))]}return[V?.(Y)+"="+V?.(String(C))]}let G0=[];if(typeof C>"u")return G0;let v;if(Z==="comma"&&x0(C)){if(R&&Q)C=u2(C,Q);v=[{value:C.length>0?C.join(",")||null:void 0}]}else if(x0(J))v=J;else{let T=Object.keys(C);v=U?T.sort(U):T}let Z0=z?String(Y).replace(/\./g,"%2E"):String(Y),S0=X&&x0(C)&&C.length===1?Z0+"[]":Z0;if(G&&x0(C)&&C.length===0)return S0+"[]";for(let T=0;T<v.length;++T){let r0=v[T],RY=typeof r0==="object"&&typeof r0.value<"u"?r0.value:C[r0];if(W&&RY===null)continue;let G2=N&&z?r0.replace(/\./g,"%2E"):r0,iZ=x0(C)?typeof Z==="function"?Z(S0,G2):S0:S0+(N?"."+G2:"["+G2+"]");y.set($,b);let SY=new WeakMap;SY.set(p2,y),P9(G0,R9(RY,iZ,Z,X,G,K,W,z,Z==="comma"&&R&&x0(C)?null:Q,J,U,N,D,O,V,R,f,SY))}return G0}function l3($=i){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let Y=$.charset||i.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Z=A6;if(typeof $.format<"u"){if(!c3.call(x6,$.format))throw TypeError("Unknown format option provided.");Z=$.format}let X=x6[Z],G=i.filter;if(typeof $.filter==="function"||x0($.filter))G=$.filter;let K;if($.arrayFormat&&$.arrayFormat in x9)K=$.arrayFormat;else if("indices"in $)K=$.indices?"indices":"repeat";else K=i.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let W=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:i.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:i.addQueryPrefix,allowDots:W,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:i.allowEmptyArrays,arrayFormat:K,charset:Y,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:i.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?i.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:i.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:i.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:i.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:i.encodeValuesOnly,filter:G,format:Z,formatter:X,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:i.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:i.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:i.strictNullHandling}}function l2($,Y={}){let Z=$,X=l3(Y),G,K;if(typeof X.filter==="function")K=X.filter,Z=K("",Z);else if(x0(X.filter))K=X.filter,G=K;let W=[];if(typeof Z!=="object"||Z===null)return"";let z=x9[X.arrayFormat],Q=z==="comma"&&X.commaRoundTrip;if(!G)G=Object.keys(Z);if(X.sort)G.sort(X.sort);let J=new WeakMap;for(let D=0;D<G.length;++D){let O=G[D];if(X.skipNulls&&Z[O]===null)continue;P9(W,R9(Z[O],O,z,Q,X.allowEmptyArrays,X.strictNullHandling,X.skipNulls,X.encodeDotInKeys,X.encode?X.encoder:null,X.filter,X.sort,X.allowDots,X.serializeDate,X.format,X.formatter,X.encodeValuesOnly,X.charset,J))}let U=W.join(X.delimiter),N=X.addQueryPrefix===!0?"?":"";if(X.charsetSentinel)if(X.charset==="iso-8859-1")N+="utf8=%26%2310003%3B&";else N+="utf8=%E2%9C%93&";return U.length>0?N+U:""}var c3,x9,x0,d3,P9=function($,Y){d3.apply($,x0(Y)?Y:[Y])},u3,i,p2;var S9=H(()=>{A9();c2();c3=Object.prototype.hasOwnProperty,x9={brackets($){return String($)+"[]"},comma:"comma",indices($,Y){return String($)+"["+Y+"]"},repeat($){return String($)}},x0=Array.isArray,d3=Array.prototype.push,u3=Date.prototype.toISOString,i={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:C9,encodeValuesOnly:!1,format:A6,formatter:x6[A6],indices:!1,serializeDate($){return u3.call($)},skipNulls:!1,strictNullHandling:!1};p2={}});var T9=H(()=>{S9()});var F1="4.104.0";function I9($,Y={auto:!1}){if(j9)throw Error(`you must \`import 'openai/shims/${$.kind}'\` before importing anything else from openai`);if(w1)throw Error(`can't \`import 'openai/shims/${$.kind}'\` after \`import 'openai/shims/${w1}'\``);j9=Y.auto,w1=$.kind,i2=$.fetch,n3=$.Request,a3=$.Response,r3=$.Headers,n2=$.FormData,s3=$.Blob,P6=$.File,a2=$.ReadableStream,r2=$.getMultipartRequestOptions,s2=$.getDefaultAgent,K4=$.fileFromPath,o2=$.isFsReadStream}var j9=!1,w1=void 0,i2=void 0,n3=void 0,a3=void 0,r3=void 0,n2=void 0,s3=void 0,P6=void 0,a2=void 0,r2=void 0,s2=void 0,K4=void 0,o2=void 0;var t2;var k9=H(()=>{t2=class t2{constructor($){this.body=$}get[Symbol.toStringTag](){return"MultipartBody"}}});function b9({manuallyImported:$}={}){let Y=$?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",Z,X,G,K;try{Z=fetch,X=Request,G=Response,K=Headers}catch(W){throw Error(`this environment is missing the following Web Fetch API type: ${W.message}. ${Y}`)}return{kind:"web",fetch:Z,Request:X,Response:G,Headers:K,FormData:typeof FormData<"u"?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${Y}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${Y}`)}},File:typeof File<"u"?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${Y}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${Y}`)}},getMultipartRequestOptions:async(W,z)=>({...z,body:new t2(W)}),getDefaultAgent:(W)=>{return},fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:(W)=>!1}}var f9=H(()=>{k9()});import{ReadStream as t3}from"fs";function y9(){let $=b9();function Y(Z){return Z instanceof t3}return{...$,isFsReadStream:Y}}var h9=H(()=>{f9()});var g9=H(()=>{h9()});var e2=()=>{if(!w1)I9(y9(),{auto:!0})};var N$=H(()=>{g9();e2()});var F,m,d,y0,h0,W4,z4,Q4,J4,N4,H4,U4,B4,H$,U$;var W0=H(()=>{x();F=class F extends Error{};m=class m extends F{constructor($,Y,Z,X){super(`${m.makeMessage($,Y,Z)}`);this.status=$,this.headers=X,this.request_id=X?.["x-request-id"],this.error=Y;let G=Y;this.code=G?.code,this.param=G?.param,this.type=G?.type}static makeMessage($,Y,Z){let X=Y?.message?typeof Y.message==="string"?Y.message:JSON.stringify(Y.message):Y?JSON.stringify(Y):Z;if($&&X)return`${$} ${X}`;if($)return`${$} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate($,Y,Z,X){if(!$||!X)return new y0({message:Z,cause:R6(Y)});let G=Y?.error;if($===400)return new W4($,G,Z,X);if($===401)return new z4($,G,Z,X);if($===403)return new Q4($,G,Z,X);if($===404)return new J4($,G,Z,X);if($===409)return new N4($,G,Z,X);if($===422)return new H4($,G,Z,X);if($===429)return new U4($,G,Z,X);if($>=500)return new B4($,G,Z,X);return new m($,G,Z,X)}};d=class d extends m{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}};y0=class y0 extends m{constructor({message:$,cause:Y}){super(void 0,void 0,$||"Connection error.",void 0);if(Y)this.cause=Y}};h0=class h0 extends y0{constructor({message:$}={}){super({message:$??"Request timed out."})}};W4=class W4 extends m{};z4=class z4 extends m{};Q4=class Q4 extends m{};J4=class J4 extends m{};N4=class N4 extends m{};H4=class H4 extends m{};U4=class U4 extends m{};B4=class B4 extends m{};H$=class H$ extends F{constructor(){super("Could not parse response content as the length limit was reached")}};U$=class U$ extends F{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}});class D4{constructor(){H0.set(this,void 0),this.buffer=new Uint8Array,S6(this,H0,null,"f")}decode($){if($==null)return[];let Y=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,Z=new Uint8Array(this.buffer.length+Y.length);Z.set(this.buffer),Z.set(Y,this.buffer.length),this.buffer=Z;let X=[],G;while((G=Y5(this.buffer,L1(this,H0,"f")))!=null){if(G.carriage&&L1(this,H0,"f")==null){S6(this,H0,G.index,"f");continue}if(L1(this,H0,"f")!=null&&(G.index!==L1(this,H0,"f")+1||G.carriage)){X.push(this.decodeText(this.buffer.slice(0,L1(this,H0,"f")-1))),this.buffer=this.buffer.slice(L1(this,H0,"f")),S6(this,H0,null,"f");continue}let K=L1(this,H0,"f")!==null?G.preceding-1:G.preceding,W=this.decodeText(this.buffer.slice(0,K));X.push(W),this.buffer=this.buffer.slice(G.index),S6(this,H0,null,"f")}return X}decodeText($){if($==null)return"";if(typeof $==="string")return $;if(typeof Buffer<"u"){if($ instanceof Buffer)return $.toString();if($ instanceof Uint8Array)return Buffer.from($).toString();throw new F(`Unexpected: received non-Uint8Array (${$.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if($ instanceof Uint8Array||$ instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode($);throw new F(`Unexpected: received non-Uint8Array/ArrayBuffer (${$.constructor.name}) in a web platform. Please report this error.`)}throw new F("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
32
+ `)}}function Y5($,Y){for(let G=Y??0;G<$.length;G++){if($[G]===10)return{preceding:G,index:G+1,carriage:!1};if($[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function v9($){for(let X=0;X<$.length-1;X++){if($[X]===10&&$[X+1]===10)return X+2;if($[X]===13&&$[X+1]===13)return X+2;if($[X]===13&&$[X+1]===10&&X+3<$.length&&$[X+2]===13&&$[X+3]===10)return X+4}return-1}var S6=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},L1=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},H0;var m9=H(()=>{W0();H0=new WeakMap;D4.NEWLINE_CHARS=new Set([`
33
+ `,"\r"]);D4.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function $8($){if($[Symbol.asyncIterator])return $;let Y=$.getReader();return{async next(){try{let Z=await Y.read();if(Z?.done)Y.releaseLock();return Z}catch(Z){throw Y.releaseLock(),Z}},async return(){let Z=Y.cancel();return Y.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function*Z5($,Y){if(!$.body)throw Y.abort(),new F("Attempted to iterate over a response with no body");let Z=new c9,X=new D4,G=$8($.body);for await(let K of X5(G))for(let W of X.decode(K)){let z=Z.decode(W);if(z)yield z}for(let K of X.flush()){let W=Z.decode(K);if(W)yield W}}async function*X5($){let Y=new Uint8Array;for await(let Z of $){if(Z==null)continue;let X=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?new TextEncoder().encode(Z):Z,G=new Uint8Array(Y.length+X.length);G.set(Y),G.set(X,Y.length),Y=G;let K;while((K=v9(Y))!==-1)yield Y.slice(0,K),Y=Y.slice(K)}if(Y.length>0)yield Y}class c9{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
34
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push($),$.startsWith(":"))return null;let[Y,Z,X]=G5($,":");if(X.startsWith(" "))X=X.substring(1);if(Y==="event")this.event=X;else if(Y==="data")this.data.push(X);return null}}function G5($,Y){let Z=$.indexOf(Y);if(Z!==-1)return[$.substring(0,Z),Y,$.substring(Z+Y.length)];return[$,"",""]}var U0;var T6=H(()=>{N$();W0();m9();x();W0();U0=class U0{constructor($,Y){this.iterator=$,this.controller=Y}static fromSSEResponse($,Y){let Z=!1;async function*X(){if(Z)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let G=!1;try{for await(let K of Z5($,Y)){if(G)continue;if(K.data.startsWith("[DONE]")){G=!0;continue}if(K.event===null||K.event.startsWith("response.")||K.event.startsWith("transcript.")){let W;try{W=JSON.parse(K.data)}catch(z){throw console.error("Could not parse message into JSON:",K.data),console.error("From chunk:",K.raw),z}if(W&&W.error)throw new m(void 0,W.error,void 0,Y8($.headers));yield W}else{let W;try{W=JSON.parse(K.data)}catch(z){throw console.error("Could not parse message into JSON:",K.data),console.error("From chunk:",K.raw),z}if(K.event=="error")throw new m(void 0,W.error,W.message,void 0);yield{event:K.event,data:W}}}G=!0}catch(K){if(K instanceof Error&&K.name==="AbortError")return;throw K}finally{if(!G)Y.abort()}}return new U0(X,Y)}static fromReadableStream($,Y){let Z=!1;async function*X(){let K=new D4,W=$8($);for await(let z of W)for(let Q of K.decode(z))yield Q;for(let z of K.flush())yield z}async function*G(){if(Z)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Z=!0;let K=!1;try{for await(let W of X()){if(K)continue;if(W)yield JSON.parse(W)}K=!0}catch(W){if(W instanceof Error&&W.name==="AbortError")return;throw W}finally{if(!K)Y.abort()}}return new U0(G,Y)}[Symbol.asyncIterator](){return this.iterator()}tee(){let $=[],Y=[],Z=this.iterator(),X=(G)=>{return{next:()=>{if(G.length===0){let K=Z.next();$.push(K),Y.push(K)}return G.shift()}}};return[new U0(()=>X($),this.controller),new U0(()=>X(Y),this.controller)]}toReadableStream(){let $=this,Y,Z=new TextEncoder;return new a2({async start(){Y=$[Symbol.asyncIterator]()},async pull(X){try{let{value:G,done:K}=await Y.next();if(K)return X.close();let W=Z.encode(JSON.stringify(G)+`
35
+ `);X.enqueue(W)}catch(G){X.error(G)}},async cancel(){await Y.return?.()}})}}});async function D$($,Y,Z){if($=await $,u9($))return $;if(d9($)){let G=await $.blob();Y||(Y=new URL($.url).pathname.split(/[\\/]/).pop()??"unknown_file");let K=B$(G)?[await G.arrayBuffer()]:[G];return new P6(K,Y,Z)}let X=await W5($);if(Y||(Y=Q5($)??"unknown_file"),!Z?.type){let G=X[0]?.type;if(typeof G==="string")Z={...Z,type:G}}return new P6(X,Y,Z)}async function W5($){let Y=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Y.push($);else if(B$($))Y.push(await $.arrayBuffer());else if(J5($))for await(let Z of $)Y.push(Z);else throw Error(`Unexpected data type: ${typeof $}; constructor: ${$?.constructor?.name}; props: ${z5($)}`);return Y}function z5($){return`[${Object.getOwnPropertyNames($).map((Z)=>`"${Z}"`).join(", ")}]`}function Q5($){return Z8($.name)||Z8($.filename)||Z8($.path)?.split(/[\\/]/).pop()}var d9=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function",u9=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&B$($),B$=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",K5=($)=>{return u9($)||d9($)||o2($)},Z8=($)=>{if(typeof $==="string")return $;if(typeof Buffer<"u"&&$ instanceof Buffer)return String($);return},J5=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",G8=($)=>$&&typeof $==="object"&&$.body&&$[Symbol.toStringTag]==="MultipartBody",z0=async($)=>{let Y=await p9($.body);return r2(Y,$)},p9=async($)=>{let Y=new n2;return await Promise.all(Object.entries($||{}).map(([Z,X])=>X8(Y,Z,X))),Y},X8=async($,Y,Z)=>{if(Z===void 0)return;if(Z==null)throw TypeError(`Received null for "${Y}"; to pass null in FormData, you must use the string 'null'`);if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")$.append(Y,String(Z));else if(K5(Z)){let X=await D$(Z);$.append(Y,X)}else if(Array.isArray(Z))await Promise.all(Z.map((X)=>X8($,Y+"[]",X)));else if(typeof Z==="object")await Promise.all(Object.entries(Z).map(([X,G])=>X8($,`${Y}[${X}]`,G)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Z} instead`)};var V$=H(()=>{N$();N$()});async function s9($){let{response:Y}=$;if($.options.stream){if(g0("response",Y.status,Y.url,Y.headers,Y.body),$.options.__streamClass)return $.options.__streamClass.fromSSEResponse(Y,$.controller);return U0.fromSSEResponse(Y,$.controller)}if(Y.status===204)return null;if($.options.__binaryResponse)return Y;let X=Y.headers.get("content-type")?.split(";")[0]?.trim();if(X?.includes("application/json")||X?.endsWith("+json")){let W=await Y.json();return g0("response",Y.status,Y.url,Y.headers,W),o9(W,Y)}let K=await Y.text();return g0("response",Y.status,Y.url,Y.headers,K),K}function o9($,Y){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Y.headers.get("x-request-id"),enumerable:!1})}class W8{constructor({baseURL:$,maxRetries:Y=2,timeout:Z=600000,httpAgent:X,fetch:G}){this.baseURL=$,this.maxRetries=K8("maxRetries",Y),this.timeout=K8("timeout",Z),this.httpAgent=X,this.fetch=G??i2}authHeaders($){return{}}defaultHeaders($){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...F5(),...this.authHeaders($)}}validateHeaders($,Y){}defaultIdempotencyKey(){return`stainless-node-retry-${M5()}`}get($,Y){return this.methodRequest("get",$,Y)}post($,Y){return this.methodRequest("post",$,Y)}patch($,Y){return this.methodRequest("patch",$,Y)}put($,Y){return this.methodRequest("put",$,Y)}delete($,Y){return this.methodRequest("delete",$,Y)}methodRequest($,Y,Z){return this.request(Promise.resolve(Z).then(async(X)=>{let G=X&&B$(X?.body)?new DataView(await X.body.arrayBuffer()):X?.body instanceof DataView?X.body:X?.body instanceof ArrayBuffer?new DataView(X.body):X&&ArrayBuffer.isView(X?.body)?new DataView(X.body.buffer):X?.body;return{method:$,path:Y,...X,body:G}}))}getAPIList($,Y,Z){return this.requestAPIList(Y,{method:"get",path:$,...Z})}calculateContentLength($){if(typeof $==="string"){if(typeof Buffer<"u")return Buffer.byteLength($,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode($).length.toString()}else if(ArrayBuffer.isView($))return $.byteLength.toString();return null}buildRequest($,{retryCount:Y=0}={}){let Z={...$},{method:X,path:G,query:K,headers:W={}}=Z,z=ArrayBuffer.isView(Z.body)||Z.__binaryRequest&&typeof Z.body==="string"?Z.body:G8(Z.body)?Z.body.body:Z.body?JSON.stringify(Z.body,null,2):null,Q=this.calculateContentLength(z),J=this.buildURL(G,K);if("timeout"in Z)K8("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let U=Z.httpAgent??this.httpAgent??s2(J),N=Z.timeout+1000;if(typeof U?.options?.timeout==="number"&&N>(U.options.timeout??0))U.options.timeout=N;if(this.idempotencyHeader&&X!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();W[this.idempotencyHeader]=$.idempotencyKey}let D=this.buildHeaders({options:Z,headers:W,contentLength:Q,retryCount:Y});return{req:{method:X,...z&&{body:z},headers:D,...U&&{agent:U},signal:Z.signal??null},url:J,timeout:Z.timeout}}buildHeaders({options:$,headers:Y,contentLength:Z,retryCount:X}){let G={};if(Z)G["content-length"]=Z;let K=this.defaultHeaders($);if(a9(G,K),a9(G,Y),G8($.body)&&w1!=="node")delete G["content-type"];if(I6(K,"x-stainless-retry-count")===void 0&&I6(Y,"x-stainless-retry-count")===void 0)G["x-stainless-retry-count"]=String(X);if(I6(K,"x-stainless-timeout")===void 0&&I6(Y,"x-stainless-timeout")===void 0&&$.timeout)G["x-stainless-timeout"]=String(Math.trunc($.timeout/1000));return this.validateHeaders(G,Y),G}async prepareOptions($){}async prepareRequest($,{url:Y,options:Z}){}parseHeaders($){return!$?{}:(Symbol.iterator in $)?Object.fromEntries(Array.from($).map((Y)=>[...Y])):{...$}}makeStatusError($,Y,Z,X){return m.generate($,Y,Z,X)}request($,Y=null){return new k6(this.makeRequest($,Y))}async makeRequest($,Y){let Z=await $,X=Z.maxRetries??this.maxRetries;if(Y==null)Y=X;await this.prepareOptions(Z);let{req:G,url:K,timeout:W}=this.buildRequest(Z,{retryCount:X-Y});if(await this.prepareRequest(G,{url:K,options:Z}),g0("request",K,Z,G.headers),Z.signal?.aborted)throw new d;let z=new AbortController,Q=await this.fetchWithTimeout(K,G,W,z).catch(R6);if(Q instanceof Error){if(Z.signal?.aborted)throw new d;if(Y)return this.retryRequest(Z,Y);if(Q.name==="AbortError")throw new h0;throw new y0({cause:Q})}let J=Y8(Q.headers);if(!Q.ok){if(Y&&this.shouldRetry(Q)){let R=`retrying, ${Y} attempts remaining`;return g0(`response (error; ${R})`,Q.status,K,J),this.retryRequest(Z,Y,J)}let U=await Q.text().catch((R)=>R6(R).message),N=w5(U),D=N?void 0:U;throw g0(`response (error; ${Y?"(error; no more retries left)":"(error; not retryable)"})`,Q.status,K,J,D),this.makeStatusError(Q.status,N,D,J)}return{response:Q,options:Z,controller:z}}requestAPIList($,Y){let Z=this.makeRequest(Y,null);return new t9(this,Z,$)}buildURL($,Y){let Z=O5($)?new URL($):new URL(this.baseURL+(this.baseURL.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery();if(!e9(X))Y={...X,...Y};if(typeof Y==="object"&&Y&&!Array.isArray(Y))Z.search=this.stringifyQuery(Y);return Z.toString()}stringifyQuery($){return Object.entries($).filter(([Y,Z])=>typeof Z<"u").map(([Y,Z])=>{if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`;if(Z===null)return`${encodeURIComponent(Y)}=`;throw new F(`Cannot stringify type ${typeof Z}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout($,Y,Z,X){let{signal:G,...K}=Y||{};if(G)G.addEventListener("abort",()=>X.abort());let W=setTimeout(()=>X.abort(),Z),z={signal:X.signal,...K};if(z.method)z.method=z.method.toUpperCase();return this.fetch.call(void 0,$,z).finally(()=>{clearTimeout(W)})}shouldRetry($){let Y=$.headers.get("x-should-retry");if(Y==="true")return!0;if(Y==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Y,Z){let X,G=Z?.["retry-after-ms"];if(G){let W=parseFloat(G);if(!Number.isNaN(W))X=W}let K=Z?.["retry-after"];if(K&&!X){let W=parseFloat(K);if(!Number.isNaN(W))X=W*1000;else X=Date.parse(K)-Date.now()}if(!(X&&0<=X&&X<60000)){let W=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(Y,W)}return await v0(X),this.makeRequest($,Y-1)}calculateDefaultRetryTimeoutMillis($,Y){let G=Y-$,K=Math.min(0.5*Math.pow(2,G),8),W=1-Math.random()*0.25;return K*W*1000}getUserAgent(){return`${this.constructor.name}/JS ${F1}`}}function V5(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Y,pattern:Z}of $){let X=Z.exec(navigator.userAgent);if(X){let G=X[1]||0,K=X[2]||0,W=X[3]||0;return{browser:Y,version:`${G}.${K}.${W}`}}}return null}function e9($){if(!$)return!0;for(let Y in $)return!1;return!0}function $Z($,Y){return Object.prototype.hasOwnProperty.call($,Y)}function a9($,Y){for(let Z in Y){if(!$Z(Y,Z))continue;let X=Z.toLowerCase();if(!X)continue;let G=Y[Z];if(G===null)delete $[X];else if(G!==void 0)$[X]=G}}function g0($,...Y){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let Z=Y.map((X)=>{if(!X)return X;if(X.headers){let K={...X,headers:{...X.headers}};for(let W in X.headers)if(r9.has(W.toLowerCase()))K.headers[W]="REDACTED";return K}let G=null;for(let K in X)if(r9.has(K.toLowerCase()))G??(G={...X}),G[K]="REDACTED";return G??X});console.log(`OpenAI:DEBUG:${$}`,...Z)}}function V4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var H5=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},U5=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},j6,k6,b6,t9,Y8=($)=>{return new Proxy(Object.fromEntries($.entries()),{get(Y,Z){let X=Z.toString();return Y[X.toLowerCase()]||Y[X]}})},B5,q=($)=>{return typeof $==="object"&&$!==null&&!e9($)&&Object.keys($).every((Y)=>$Z(B5,Y))},D5=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":F1,"X-Stainless-OS":i9(Deno.build.os),"X-Stainless-Arch":l9(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":F1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":F1,"X-Stainless-OS":i9(process.platform),"X-Stainless-Arch":l9(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let $=V5();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":F1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":F1,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},l9=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},i9=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},n9,F5=()=>{return n9??(n9=D5())},w5=($)=>{try{return JSON.parse($)}catch(Y){return}},L5,O5=($)=>{return L5.test($)},v0=($)=>new Promise((Y)=>setTimeout(Y,$)),K8=($,Y)=>{if(typeof Y!=="number"||!Number.isInteger(Y))throw new F(`${$} must be an integer`);if(Y<0)throw new F(`${$} must be a positive integer`);return Y},R6=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null)try{return Error(JSON.stringify($))}catch{}return Error($)},$1=($)=>{if(typeof process<"u")return process.env?.[$]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.($)?.trim();return},r9,M5=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let Y=Math.random()*16|0;return($==="x"?Y:Y&3|8).toString(16)})},YZ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},E5=($)=>{return typeof $?.get==="function"},I6=($,Y)=>{let Z=Y.toLowerCase();if(E5($)){let X=Y[0]?.toUpperCase()+Y.substring(1).replace(/([^\w])(\w)/g,(G,K,W)=>K+W.toUpperCase());for(let G of[Y,Z,Y.toUpperCase(),X]){let K=$.get(G);if(K)return K}}for(let[X,G]of Object.entries($))if(X.toLowerCase()===Z){if(Array.isArray(G)){if(G.length<=1)return G[0];return console.warn(`Received ${G.length} entries for the ${Y} header, using the first entry.`),G[0]}return G}return},ZZ=($)=>{if(typeof Buffer<"u"){let Y=Buffer.from($,"base64");return Array.from(new Float32Array(Y.buffer,Y.byteOffset,Y.length/Float32Array.BYTES_PER_ELEMENT))}else{let Y=atob($),Z=Y.length,X=new Uint8Array(Z);for(let G=0;G<Z;G++)X[G]=Y.charCodeAt(G);return Array.from(new Float32Array(X.buffer))}};var x=H(()=>{T6();W0();N$();V$();V$();e2();k6=class k6 extends Promise{constructor($,Y=s9){super((Z)=>{Z(null)});this.responsePromise=$,this.parseResponse=Y}_thenUnwrap($){return new k6(this.responsePromise,async(Y)=>o9($(await this.parseResponse(Y),Y),Y.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Y]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Y,request_id:Y.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then($,Y){return this.parse().then($,Y)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}};b6=class b6{constructor($,Y,Z,X){j6.set(this,void 0),H5(this,j6,$,"f"),this.options=X,this.response=Y,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let $=this.nextPageInfo();if(!$)throw new F("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let Y={...this.options};if("params"in $&&typeof Y.query==="object")Y.query={...Y.query,...$.params};else if("url"in $){let Z=[...Object.entries(Y.query||{}),...$.url.searchParams.entries()];for(let[X,G]of Z)$.url.searchParams.set(X,G);Y.query=void 0,Y.path=$.url.toString()}return await U5(this,j6,"f").requestAPIList(this.constructor,Y)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(j6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Y of $.getPaginatedItems())yield Y}};t9=class t9 extends k6{constructor($,Y,Z){super(Y,async(X)=>new Z($,X.response,await s9(X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Y of $)yield Y}};B5={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0};L5=/^[a-z][a-z0-9+.-]*:/i;r9=new Set(["authorization","api-key"])});var c0,P;var p=H(()=>{x();c0=class c0 extends b6{constructor($,Y,Z,X){super($,Y,Z,X);this.data=Z.data||[],this.object=Z.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}};P=class P extends b6{constructor($,Y,Z,X){super($,Y,Z,X);this.data=Z.data||[],this.has_more=Z.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let $=this.nextPageInfo();if(!$)return null;if("params"in $)return $.params;let Y=Object.fromEntries($.url.searchParams);if(!Object.keys(Y).length)return null;return Y}nextPageInfo(){let $=this.getPaginatedItems();if(!$.length)return null;let Y=$[$.length-1]?.id;if(!Y)return null;return{params:{after:Y}}}}});class B{constructor($){this._client=$}}var F$;var z8=H(()=>{x();w$();F$=class F$ extends B{list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/chat/completions/${$}/messages`,Q8,{query:Y,...Z})}}});var O1,M1,Q8;var w$=H(()=>{x();z8();z8();p();O1=class O1 extends B{constructor(){super(...arguments);this.messages=new F$(this._client)}create($,Y){return this._client.post("/chat/completions",{body:$,...Y,stream:$.stream??!1})}retrieve($,Y){return this._client.get(`/chat/completions/${$}`,Y)}update($,Y,Z){return this._client.post(`/chat/completions/${$}`,{body:Y,...Z})}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/chat/completions",M1,{query:$,...Y})}del($,Y){return this._client.delete(`/chat/completions/${$}`,Y)}};M1=class M1 extends P{};Q8=class Q8 extends P{};O1.ChatCompletionsPage=M1;O1.Messages=F$});var Y1;var J8=H(()=>{w$();w$();Y1=class Y1 extends B{constructor(){super(...arguments);this.completions=new O1(this._client)}};Y1.Completions=O1;Y1.ChatCompletionsPage=M1});var XZ=H(()=>{J8()});var GZ=()=>{};var L$;var N8=H(()=>{L$=class L$ extends B{create($,Y){return this._client.post("/audio/speech",{body:$,...Y,headers:{Accept:"application/octet-stream",...Y?.headers},__binaryResponse:!0})}}});var O$;var H8=H(()=>{x();O$=class O$ extends B{create($,Y){return this._client.post("/audio/transcriptions",z0({body:$,...Y,stream:$.stream??!1,__metadata:{model:$.model}}))}}});var M$;var U8=H(()=>{x();M$=class M$ extends B{create($,Y){return this._client.post("/audio/translations",z0({body:$,...Y,__metadata:{model:$.model}}))}}});var d0;var B8=H(()=>{N8();N8();H8();H8();U8();U8();d0=class d0 extends B{constructor(){super(...arguments);this.transcriptions=new O$(this._client),this.translations=new M$(this._client),this.speech=new L$(this._client)}};d0.Transcriptions=O$;d0.Translations=M$;d0.Speech=L$});var E1,F4;var D8=H(()=>{x();p();E1=class E1 extends B{create($,Y){return this._client.post("/batches",{body:$,...Y})}retrieve($,Y){return this._client.get(`/batches/${$}`,Y)}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/batches",F4,{query:$,...Y})}cancel($,Y){return this._client.post(`/batches/${$}/cancel`,Y)}};F4=class F4 extends P{};E1.BatchesPage=F4});class q1{constructor(){V8.add(this),this.controller=new AbortController,f6.set(this,void 0),y6.set(this,()=>{}),E$.set(this,()=>{}),q$.set(this,void 0),h6.set(this,()=>{}),C$.set(this,()=>{}),u0.set(this,{}),_$.set(this,!1),g6.set(this,!1),v6.set(this,!1),w4.set(this,!1),C0(this,f6,new Promise(($,Y)=>{C0(this,y6,$,"f"),C0(this,E$,Y,"f")}),"f"),C0(this,q$,new Promise(($,Y)=>{C0(this,h6,$,"f"),C0(this,C$,Y,"f")}),"f"),h(this,f6,"f").catch(()=>{}),h(this,q$,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},h(this,V8,"m",KZ).bind(this))},0)}_connected(){if(this.ended)return;h(this,y6,"f").call(this),this._emit("connect")}get ended(){return h(this,_$,"f")}get errored(){return h(this,g6,"f")}get aborted(){return h(this,v6,"f")}abort(){this.controller.abort()}on($,Y){return(h(this,u0,"f")[$]||(h(this,u0,"f")[$]=[])).push({listener:Y}),this}off($,Y){let Z=h(this,u0,"f")[$];if(!Z)return this;let X=Z.findIndex((G)=>G.listener===Y);if(X>=0)Z.splice(X,1);return this}once($,Y){return(h(this,u0,"f")[$]||(h(this,u0,"f")[$]=[])).push({listener:Y,once:!0}),this}emitted($){return new Promise((Y,Z)=>{if(C0(this,w4,!0,"f"),$!=="error")this.once("error",Z);this.once($,Y)})}async done(){C0(this,w4,!0,"f"),await h(this,q$,"f")}_emit($,...Y){if(h(this,_$,"f"))return;if($==="end")C0(this,_$,!0,"f"),h(this,h6,"f").call(this);let Z=h(this,u0,"f")[$];if(Z)h(this,u0,"f")[$]=Z.filter((X)=>!X.once),Z.forEach(({listener:X})=>X(...Y));if($==="abort"){let X=Y[0];if(!h(this,w4,"f")&&!Z?.length)Promise.reject(X);h(this,E$,"f").call(this,X),h(this,C$,"f").call(this,X),this._emit("end");return}if($==="error"){let X=Y[0];if(!h(this,w4,"f")&&!Z?.length)Promise.reject(X);h(this,E$,"f").call(this,X),h(this,C$,"f").call(this,X),this._emit("end")}}_emitFinal(){}}var C0=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},h=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},V8,f6,y6,E$,q$,h6,C$,u0,_$,g6,v6,w4,KZ;var m6=H(()=>{W0();f6=new WeakMap,y6=new WeakMap,E$=new WeakMap,q$=new WeakMap,h6=new WeakMap,C$=new WeakMap,u0=new WeakMap,_$=new WeakMap,g6=new WeakMap,v6=new WeakMap,w4=new WeakMap,V8=new WeakSet,KZ=function(Y){if(C0(this,g6,!0,"f"),Y instanceof Error&&Y.name==="AbortError")Y=new d;if(Y instanceof d)return C0(this,v6,!0,"f"),this._emit("abort",Y);if(Y instanceof F)return this._emit("error",Y);if(Y instanceof Error){let Z=new F(Y.message);return Z.cause=Y,this._emit("error",Z)}return this._emit("error",new F(String(Y)))}});function P5($){}var L=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},B0=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},o,F8,P0,c6,_0,_1,L4,C1,p6,D0,d6,u6,P$,A$,x$,WZ,zZ,QZ,JZ,NZ,HZ,UZ,V0;var w8=H(()=>{x();T6();W0();m6();V0=class V0 extends q1{constructor(){super(...arguments);o.add(this),F8.set(this,[]),P0.set(this,{}),c6.set(this,{}),_0.set(this,void 0),_1.set(this,void 0),L4.set(this,void 0),C1.set(this,void 0),p6.set(this,void 0),D0.set(this,void 0),d6.set(this,void 0),u6.set(this,void 0),P$.set(this,void 0)}[(F8=new WeakMap,P0=new WeakMap,c6=new WeakMap,_0=new WeakMap,_1=new WeakMap,L4=new WeakMap,C1=new WeakMap,p6=new WeakMap,D0=new WeakMap,d6=new WeakMap,u6=new WeakMap,P$=new WeakMap,o=new WeakSet,Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("event",(X)=>{let G=Y.shift();if(G)G.resolve(X);else $.push(X)}),this.on("end",()=>{Z=!0;for(let X of Y)X.resolve(void 0);Y.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),this.on("error",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((G,K)=>Y.push({resolve:G,reject:K})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let Y=new V0;return Y._run(()=>Y._fromReadableStream($)),Y}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}this._connected();let X=U0.fromReadableStream($,this.controller);for await(let G of X)L(this,o,"m",A$).call(this,G);if(X.controller.signal?.aborted)throw new d;return this._addRun(L(this,o,"m",x$).call(this))}toReadableStream(){return new U0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,Y,Z,X,G){let K=new V0;return K._run(()=>K._runToolAssistantStream($,Y,Z,X,{...G,headers:{...G?.headers,"X-Stainless-Helper-Method":"stream"}})),K}async _createToolAssistantStream($,Y,Z,X,G){let K=G?.signal;if(K){if(K.aborted)this.controller.abort();K.addEventListener("abort",()=>this.controller.abort())}let W={...X,stream:!0},z=await $.submitToolOutputs(Y,Z,W,{...G,signal:this.controller.signal});this._connected();for await(let Q of z)L(this,o,"m",A$).call(this,Q);if(z.controller.signal?.aborted)throw new d;return this._addRun(L(this,o,"m",x$).call(this))}static createThreadAssistantStream($,Y,Z){let X=new V0;return X._run(()=>X._threadAssistantStream($,Y,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}static createAssistantStream($,Y,Z,X){let G=new V0;return G._run(()=>G._runAssistantStream($,Y,Z,{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),G}currentEvent(){return L(this,d6,"f")}currentRun(){return L(this,u6,"f")}currentMessageSnapshot(){return L(this,_0,"f")}currentRunStepSnapshot(){return L(this,P$,"f")}async finalRunSteps(){return await this.done(),Object.values(L(this,P0,"f"))}async finalMessages(){return await this.done(),Object.values(L(this,c6,"f"))}async finalRun(){if(await this.done(),!L(this,_1,"f"))throw Error("Final run was not received.");return L(this,_1,"f")}async _createThreadAssistantStream($,Y,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let G={...Y,stream:!0},K=await $.createAndRun(G,{...Z,signal:this.controller.signal});this._connected();for await(let W of K)L(this,o,"m",A$).call(this,W);if(K.controller.signal?.aborted)throw new d;return this._addRun(L(this,o,"m",x$).call(this))}async _createAssistantStream($,Y,Z,X){let G=X?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}let K={...Z,stream:!0},W=await $.create(Y,K,{...X,signal:this.controller.signal});this._connected();for await(let z of W)L(this,o,"m",A$).call(this,z);if(W.controller.signal?.aborted)throw new d;return this._addRun(L(this,o,"m",x$).call(this))}static accumulateDelta($,Y){for(let[Z,X]of Object.entries(Y)){if(!$.hasOwnProperty(Z)){$[Z]=X;continue}let G=$[Z];if(G===null||G===void 0){$[Z]=X;continue}if(Z==="index"||Z==="type"){$[Z]=X;continue}if(typeof G==="string"&&typeof X==="string")G+=X;else if(typeof G==="number"&&typeof X==="number")G+=X;else if(V4(G)&&V4(X))G=this.accumulateDelta(G,X);else if(Array.isArray(G)&&Array.isArray(X)){if(G.every((K)=>typeof K==="string"||typeof K==="number")){G.push(...X);continue}for(let K of X){if(!V4(K))throw Error(`Expected array delta entry to be an object but got: ${K}`);let W=K.index;if(W==null)throw console.error(K),Error("Expected array delta entry to have an `index` property");if(typeof W!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${W}`);let z=G[W];if(z==null)G.push(K);else G[W]=this.accumulateDelta(z,K)}continue}else throw Error(`Unhandled record type: ${Z}, deltaValue: ${X}, accValue: ${G}`);$[Z]=G}return $}_addRun($){return $}async _threadAssistantStream($,Y,Z){return await this._createThreadAssistantStream(Y,$,Z)}async _runAssistantStream($,Y,Z,X){return await this._createAssistantStream(Y,$,Z,X)}async _runToolAssistantStream($,Y,Z,X,G){return await this._createToolAssistantStream(Z,$,Y,X,G)}};A$=function(Y){if(this.ended)return;switch(B0(this,d6,Y,"f"),L(this,o,"m",QZ).call(this,Y),Y.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":L(this,o,"m",UZ).call(this,Y);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":L(this,o,"m",zZ).call(this,Y);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":L(this,o,"m",WZ).call(this,Y);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:P5(Y)}},x$=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");if(!L(this,_1,"f"))throw Error("Final run has not been received");return L(this,_1,"f")},WZ=function(Y){let[Z,X]=L(this,o,"m",NZ).call(this,Y,L(this,_0,"f"));B0(this,_0,Z,"f"),L(this,c6,"f")[Z.id]=Z;for(let G of X){let K=Z.content[G.index];if(K?.type=="text")this._emit("textCreated",K.text)}switch(Y.event){case"thread.message.created":this._emit("messageCreated",Y.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",Y.data.delta,Z),Y.data.delta.content)for(let G of Y.data.delta.content){if(G.type=="text"&&G.text){let K=G.text,W=Z.content[G.index];if(W&&W.type=="text")this._emit("textDelta",K,W.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(G.index!=L(this,L4,"f")){if(L(this,C1,"f"))switch(L(this,C1,"f").type){case"text":this._emit("textDone",L(this,C1,"f").text,L(this,_0,"f"));break;case"image_file":this._emit("imageFileDone",L(this,C1,"f").image_file,L(this,_0,"f"));break}B0(this,L4,G.index,"f")}B0(this,C1,Z.content[G.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(L(this,L4,"f")!==void 0){let G=Y.data.content[L(this,L4,"f")];if(G)switch(G.type){case"image_file":this._emit("imageFileDone",G.image_file,L(this,_0,"f"));break;case"text":this._emit("textDone",G.text,L(this,_0,"f"));break}}if(L(this,_0,"f"))this._emit("messageDone",Y.data);B0(this,_0,void 0,"f")}},zZ=function(Y){let Z=L(this,o,"m",JZ).call(this,Y);switch(B0(this,P$,Z,"f"),Y.event){case"thread.run.step.created":this._emit("runStepCreated",Y.data);break;case"thread.run.step.delta":let X=Y.data.delta;if(X.step_details&&X.step_details.type=="tool_calls"&&X.step_details.tool_calls&&Z.step_details.type=="tool_calls")for(let K of X.step_details.tool_calls)if(K.index==L(this,p6,"f"))this._emit("toolCallDelta",K,Z.step_details.tool_calls[K.index]);else{if(L(this,D0,"f"))this._emit("toolCallDone",L(this,D0,"f"));if(B0(this,p6,K.index,"f"),B0(this,D0,Z.step_details.tool_calls[K.index],"f"),L(this,D0,"f"))this._emit("toolCallCreated",L(this,D0,"f"))}this._emit("runStepDelta",Y.data.delta,Z);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(B0(this,P$,void 0,"f"),Y.data.step_details.type=="tool_calls"){if(L(this,D0,"f"))this._emit("toolCallDone",L(this,D0,"f")),B0(this,D0,void 0,"f")}this._emit("runStepDone",Y.data,Z);break;case"thread.run.step.in_progress":break}},QZ=function(Y){L(this,F8,"f").push(Y),this._emit("event",Y)},JZ=function(Y){switch(Y.event){case"thread.run.step.created":return L(this,P0,"f")[Y.data.id]=Y.data,Y.data;case"thread.run.step.delta":let Z=L(this,P0,"f")[Y.data.id];if(!Z)throw Error("Received a RunStepDelta before creation of a snapshot");let X=Y.data;if(X.delta){let G=V0.accumulateDelta(Z,X.delta);L(this,P0,"f")[Y.data.id]=G}return L(this,P0,"f")[Y.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":L(this,P0,"f")[Y.data.id]=Y.data;break}if(L(this,P0,"f")[Y.data.id])return L(this,P0,"f")[Y.data.id];throw Error("No snapshot available")},NZ=function(Y,Z){let X=[];switch(Y.event){case"thread.message.created":return[Y.data,X];case"thread.message.delta":if(!Z)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let G=Y.data;if(G.delta.content)for(let K of G.delta.content)if(K.index in Z.content){let W=Z.content[K.index];Z.content[K.index]=L(this,o,"m",HZ).call(this,K,W)}else Z.content[K.index]=K,X.push(K);return[Z,X];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(Z)return[Z,X];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},HZ=function(Y,Z){return V0.accumulateDelta(Z,Y)},UZ=function(Y){switch(B0(this,u6,Y.data,"f"),Y.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":if(B0(this,_1,Y.data,"f"),L(this,D0,"f"))this._emit("toolCallDone",L(this,D0,"f")),B0(this,D0,void 0,"f");break;case"thread.run.cancelling":break}}});var O4,R$;var L8=H(()=>{x();p();O4=class O4 extends B{create($,Y){return this._client.post("/assistants",{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}retrieve($,Y){return this._client.get(`/assistants/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}update($,Y,Z){return this._client.post(`/assistants/${$}`,{body:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/assistants",R$,{query:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}del($,Y){return this._client.delete(`/assistants/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}};R$=class R$ extends P{};O4.AssistantsPage=R$});function O8($){return typeof $.parse==="function"}var Z1=($)=>{return $?.role==="assistant"},M8=($)=>{return $?.role==="function"},E8=($)=>{return $?.role==="tool"};function S$($){return $?.$brand==="auto-parseable-response-format"}function A1($){return $?.$brand==="auto-parseable-tool"}function BZ($,Y){if(!Y||!q8(Y))return{...$,choices:$.choices.map((Z)=>({...Z,message:{...Z.message,parsed:null,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls}:void 0}}))};return T$($,Y)}function T$($,Y){let Z=$.choices.map((X)=>{if(X.finish_reason==="length")throw new H$;if(X.finish_reason==="content_filter")throw new U$;return{...X,message:{...X.message,...X.message.tool_calls?{tool_calls:X.message.tool_calls?.map((G)=>T5(Y,G))??void 0}:void 0,parsed:X.message.content&&!X.message.refusal?S5(Y,X.message.content):null}}});return{...$,choices:Z}}function S5($,Y){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(Y);return JSON.parse(Y)}return null}function T5($,Y){let Z=$.tools?.find((X)=>X.function?.name===Y.function.name);return{...Y,function:{...Y.function,parsed_arguments:A1(Z)?Z.$parseRaw(Y.function.arguments):Z?.function.strict?JSON.parse(Y.function.arguments):null}}}function DZ($,Y){if(!$)return!1;let Z=$.tools?.find((X)=>X.function?.name===Y.function.name);return A1(Z)||Z?.function.strict||!1}function q8($){if(S$($.response_format))return!0;return $.tools?.some((Y)=>A1(Y)||Y.type==="function"&&Y.function.strict===!0)??!1}function VZ($){for(let Y of $??[]){if(Y.type!=="function")throw new F(`Currently only \`function\` tool types support auto-parsing; Received \`${Y.type}\``);if(Y.function.strict!==!0)throw new F(`The \`${Y.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var j$=H(()=>{W0()});var Q0=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},$0,C8,l6,_8,A8,x8,wZ,P8,FZ=10,I$;var R8=H(()=>{W0();m6();j$();I$=class I$ extends q1{constructor(){super(...arguments);$0.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let Y=$.choices[0]?.message;if(Y)this._addMessage(Y);return $}_addMessage($,Y=!0){if(!("content"in $))$.content=null;if(this.messages.push($),Y){if(this._emit("message",$),(M8($)||E8($))&&$.content)this._emit("functionCallResult",$.content);else if(Z1($)&&$.function_call)this._emit("functionCall",$.function_call);else if(Z1($)&&$.tool_calls){for(let Z of $.tool_calls)if(Z.type==="function")this._emit("functionCall",Z.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new F("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),Q0(this,$0,"m",C8).call(this)}async finalMessage(){return await this.done(),Q0(this,$0,"m",l6).call(this)}async finalFunctionCall(){return await this.done(),Q0(this,$0,"m",_8).call(this)}async finalFunctionCallResult(){return await this.done(),Q0(this,$0,"m",A8).call(this)}async totalUsage(){return await this.done(),Q0(this,$0,"m",x8).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let Y=Q0(this,$0,"m",l6).call(this);if(Y)this._emit("finalMessage",Y);let Z=Q0(this,$0,"m",C8).call(this);if(Z)this._emit("finalContent",Z);let X=Q0(this,$0,"m",_8).call(this);if(X)this._emit("finalFunctionCall",X);let G=Q0(this,$0,"m",A8).call(this);if(G!=null)this._emit("finalFunctionCallResult",G);if(this._chatCompletions.some((K)=>K.usage))this._emit("totalUsage",Q0(this,$0,"m",x8).call(this))}async _createChatCompletion($,Y,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}Q0(this,$0,"m",wZ).call(this,Y);let G=await $.chat.completions.create({...Y,stream:!1},{...Z,signal:this.controller.signal});return this._connected(),this._addChatCompletion(T$(G,Y))}async _runChatCompletion($,Y,Z){for(let X of Y.messages)this._addMessage(X,!1);return await this._createChatCompletion($,Y,Z)}async _runFunctions($,Y,Z){let{function_call:G="auto",stream:K,...W}=Y,z=typeof G!=="string"&&G?.name,{maxChatCompletions:Q=FZ}=Z||{},J={};for(let N of Y.functions)J[N.name||N.function.name]=N;let U=Y.functions.map((N)=>({name:N.name||N.function.name,parameters:N.parameters,description:N.description}));for(let N of Y.messages)this._addMessage(N,!1);for(let N=0;N<Q;++N){let O=(await this._createChatCompletion($,{...W,function_call:G,functions:U,messages:[...this.messages]},Z)).choices[0]?.message;if(!O)throw new F("missing message in ChatCompletion response");if(!O.function_call)return;let{name:V,arguments:R}=O.function_call,f=J[V];if(!f){let b=`Invalid function_call: ${JSON.stringify(V)}. Available options are: ${U.map((X0)=>JSON.stringify(X0.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:V,content:b});continue}else if(z&&z!==V){let b=`Invalid function_call: ${JSON.stringify(V)}. ${JSON.stringify(z)} requested. Please try again`;this._addMessage({role:"function",name:V,content:b});continue}let y;try{y=O8(f)?await f.parse(R):R}catch(b){this._addMessage({role:"function",name:V,content:b instanceof Error?b.message:String(b)});continue}let C=await f.function(y,this),l=Q0(this,$0,"m",P8).call(this,C);if(this._addMessage({role:"function",name:V,content:l}),z)return}}async _runTools($,Y,Z){let{tool_choice:G="auto",stream:K,...W}=Y,z=typeof G!=="string"&&G?.function?.name,{maxChatCompletions:Q=FZ}=Z||{},J=Y.tools.map((D)=>{if(A1(D)){if(!D.$callback)throw new F("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:D.$callback,name:D.function.name,description:D.function.description||"",parameters:D.function.parameters,parse:D.$parseRaw,strict:!0}}}return D}),U={};for(let D of J)if(D.type==="function")U[D.function.name||D.function.function.name]=D.function;let N="tools"in Y?J.map((D)=>D.type==="function"?{type:"function",function:{name:D.function.name||D.function.function.name,parameters:D.function.parameters,description:D.function.description,strict:D.function.strict}}:D):void 0;for(let D of Y.messages)this._addMessage(D,!1);for(let D=0;D<Q;++D){let V=(await this._createChatCompletion($,{...W,tool_choice:G,tools:N,messages:[...this.messages]},Z)).choices[0]?.message;if(!V)throw new F("missing message in ChatCompletion response");if(!V.tool_calls?.length)return;for(let R of V.tool_calls){if(R.type!=="function")continue;let f=R.id,{name:y,arguments:C}=R.function,l=U[y];if(!l){let v=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(U).map((Z0)=>JSON.stringify(Z0)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:f,content:v});continue}else if(z&&z!==y){let v=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(z)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:f,content:v});continue}let b;try{b=O8(l)?await l.parse(C):C}catch(v){let Z0=v instanceof Error?v.message:String(v);this._addMessage({role:"tool",tool_call_id:f,content:Z0});continue}let X0=await l.function(b,this),G0=Q0(this,$0,"m",P8).call(this,X0);if(this._addMessage({role:"tool",tool_call_id:f,content:G0}),z)return}}return}};$0=new WeakSet,C8=function(){return Q0(this,$0,"m",l6).call(this).content??null},l6=function(){let Y=this.messages.length;while(Y-- >0){let Z=this.messages[Y];if(Z1(Z)){let{function_call:X,...G}=Z,K={...G,content:Z.content??null,refusal:Z.refusal??null};if(X)K.function_call=X;return K}}throw new F("stream ended without producing a ChatCompletionMessage with role=assistant")},_8=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let Z=this.messages[Y];if(Z1(Z)&&Z?.function_call)return Z.function_call;if(Z1(Z)&&Z?.tool_calls?.length)return Z.tool_calls.at(-1)?.function}return},A8=function(){for(let Y=this.messages.length-1;Y>=0;Y--){let Z=this.messages[Y];if(M8(Z)&&Z.content!=null)return Z.content;if(E8(Z)&&Z.content!=null&&typeof Z.content==="string"&&this.messages.some((X)=>X.role==="assistant"&&X.tool_calls?.some((G)=>G.type==="function"&&G.id===Z.tool_call_id)))return Z.content}return},x8=function(){let Y={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:Z}of this._chatCompletions)if(Z)Y.completion_tokens+=Z.completion_tokens,Y.prompt_tokens+=Z.prompt_tokens,Y.total_tokens+=Z.total_tokens;return Y},wZ=function(Y){if(Y.n!=null&&Y.n>1)throw new F("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},P8=function(Y){return typeof Y==="string"?Y:Y===void 0?"undefined":JSON.stringify(Y)}});var M4;var LZ=H(()=>{R8();M4=class M4 extends I${static runFunctions($,Y,Z){let X=new M4,G={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return X._run(()=>X._runFunctions($,Y,G)),X}static runTools($,Y,Z){let X=new M4,G={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return X._run(()=>X._runTools($,Y,G)),X}_addMessage($,Y=!0){if(super._addMessage($,Y),Z1($)&&$.content)this._emit("content",$.content)}}});function j5($,Y=r.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return I5($.trim(),Y)}var r,OZ,MZ,I5=($,Y)=>{let Z=$.length,X=0,G=(D)=>{throw new OZ(`${D} at position ${X}`)},K=(D)=>{throw new MZ(`${D} at position ${X}`)},W=()=>{if(N(),X>=Z)G("Unexpected end of input");if($[X]==='"')return z();if($[X]==="{")return Q();if($[X]==="[")return J();if($.substring(X,X+4)==="null"||r.NULL&Y&&Z-X<4&&"null".startsWith($.substring(X)))return X+=4,null;if($.substring(X,X+4)==="true"||r.BOOL&Y&&Z-X<4&&"true".startsWith($.substring(X)))return X+=4,!0;if($.substring(X,X+5)==="false"||r.BOOL&Y&&Z-X<5&&"false".startsWith($.substring(X)))return X+=5,!1;if($.substring(X,X+8)==="Infinity"||r.INFINITY&Y&&Z-X<8&&"Infinity".startsWith($.substring(X)))return X+=8,1/0;if($.substring(X,X+9)==="-Infinity"||r.MINUS_INFINITY&Y&&1<Z-X&&Z-X<9&&"-Infinity".startsWith($.substring(X)))return X+=9,-1/0;if($.substring(X,X+3)==="NaN"||r.NAN&Y&&Z-X<3&&"NaN".startsWith($.substring(X)))return X+=3,NaN;return U()},z=()=>{let D=X,O=!1;X++;while(X<Z&&($[X]!=='"'||O&&$[X-1]==="\\"))O=$[X]==="\\"?!O:!1,X++;if($.charAt(X)=='"')try{return JSON.parse($.substring(D,++X-Number(O)))}catch(V){K(String(V))}else if(r.STR&Y)try{return JSON.parse($.substring(D,X-Number(O))+'"')}catch(V){return JSON.parse($.substring(D,$.lastIndexOf("\\"))+'"')}G("Unterminated string literal")},Q=()=>{X++,N();let D={};try{while($[X]!=="}"){if(N(),X>=Z&&r.OBJ&Y)return D;let O=z();N(),X++;try{let V=W();Object.defineProperty(D,O,{value:V,writable:!0,enumerable:!0,configurable:!0})}catch(V){if(r.OBJ&Y)return D;else throw V}if(N(),$[X]===",")X++}}catch(O){if(r.OBJ&Y)return D;else G("Expected '}' at end of object")}return X++,D},J=()=>{X++;let D=[];try{while($[X]!=="]")if(D.push(W()),N(),$[X]===",")X++}catch(O){if(r.ARR&Y)return D;G("Expected ']' at end of array")}return X++,D},U=()=>{if(X===0){if($==="-"&&r.NUM&Y)G("Not sure what '-' is");try{return JSON.parse($)}catch(O){if(r.NUM&Y)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(V){}K(String(O))}}let D=X;if($[X]==="-")X++;while($[X]&&!",]}".includes($[X]))X++;if(X==Z&&!(r.NUM&Y))G("Unterminated number literal");try{return JSON.parse($.substring(D,X))}catch(O){if($.substring(D,X)==="-"&&r.NUM&Y)G("Not sure what '-' is");try{return JSON.parse($.substring(D,$.lastIndexOf("e")))}catch(V){K(String(V))}}},N=()=>{while(X<Z&&`
36
+ \r `.includes($[X]))X++};return W()},S8=($)=>j5($,r.ALL^r.NUM);var EZ=H(()=>{r={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};OZ=class OZ extends Error{};MZ=class MZ extends Error{}});function k5($,Y){let{id:Z,choices:X,created:G,model:K,system_fingerprint:W,...z}=$,Q={...z,id:Z,choices:X.map(({message:J,finish_reason:U,index:N,logprobs:D,...O})=>{if(!U)throw new F(`missing finish_reason for choice ${N}`);let{content:V=null,function_call:R,tool_calls:f,...y}=J,C=J.role;if(!C)throw new F(`missing role for choice ${N}`);if(R){let{arguments:l,name:b}=R;if(l==null)throw new F(`missing function_call.arguments for choice ${N}`);if(!b)throw new F(`missing function_call.name for choice ${N}`);return{...O,message:{content:V,function_call:{arguments:l,name:b},role:C,refusal:J.refusal??null},finish_reason:U,index:N,logprobs:D}}if(f)return{...O,index:N,finish_reason:U,logprobs:D,message:{...y,role:C,content:V,refusal:J.refusal??null,tool_calls:f.map((l,b)=>{let{function:X0,type:G0,id:v,...Z0}=l,{arguments:S0,name:T,...r0}=X0||{};if(v==null)throw new F(`missing choices[${N}].tool_calls[${b}].id
37
+ ${a6($)}`);if(G0==null)throw new F(`missing choices[${N}].tool_calls[${b}].type
38
+ ${a6($)}`);if(T==null)throw new F(`missing choices[${N}].tool_calls[${b}].function.name
39
+ ${a6($)}`);if(S0==null)throw new F(`missing choices[${N}].tool_calls[${b}].function.arguments
40
+ ${a6($)}`);return{...Z0,id:v,type:G0,function:{...r0,name:T,arguments:S0}}})}};return{...O,message:{...y,content:V,role:C,refusal:J.refusal??null},finish_reason:U,index:N,logprobs:D}}),created:G,model:K,object:"chat.completion",...W?{system_fingerprint:W}:{}};return BZ(Q,Y)}function a6($){return JSON.stringify($)}function CZ($){return}function _Z($){}var E4=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},k=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},n,p0,q4,X1,T8,i6,j8,I8,k8,n6,b8,qZ,x1;var f8=H(()=>{W0();R8();T6();j$();EZ();x1=class x1 extends I${constructor($){super();n.add(this),p0.set(this,void 0),q4.set(this,void 0),X1.set(this,void 0),E4(this,p0,$,"f"),E4(this,q4,[],"f")}get currentChatCompletionSnapshot(){return k(this,X1,"f")}static fromReadableStream($){let Y=new x1(null);return Y._run(()=>Y._fromReadableStream($)),Y}static createChatCompletion($,Y,Z){let X=new x1(Y);return X._run(()=>X._runChatCompletion($,{...Y,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createChatCompletion($,Y,Z){super._createChatCompletion;let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}k(this,n,"m",T8).call(this);let G=await $.chat.completions.create({...Y,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let K of G)k(this,n,"m",j8).call(this,K);if(G.controller.signal?.aborted)throw new d;return this._addChatCompletion(k(this,n,"m",n6).call(this))}async _fromReadableStream($,Y){let Z=Y?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}k(this,n,"m",T8).call(this),this._connected();let X=U0.fromReadableStream($,this.controller),G;for await(let K of X){if(G&&G!==K.id)this._addChatCompletion(k(this,n,"m",n6).call(this));k(this,n,"m",j8).call(this,K),G=K.id}if(X.controller.signal?.aborted)throw new d;return this._addChatCompletion(k(this,n,"m",n6).call(this))}[(p0=new WeakMap,q4=new WeakMap,X1=new WeakMap,n=new WeakSet,T8=function(){if(this.ended)return;E4(this,X1,void 0,"f")},i6=function(Y){let Z=k(this,q4,"f")[Y.index];if(Z)return Z;return Z={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},k(this,q4,"f")[Y.index]=Z,Z},j8=function(Y){if(this.ended)return;let Z=k(this,n,"m",qZ).call(this,Y);this._emit("chunk",Y,Z);for(let X of Y.choices){let G=Z.choices[X.index];if(X.delta.content!=null&&G.message?.role==="assistant"&&G.message?.content)this._emit("content",X.delta.content,G.message.content),this._emit("content.delta",{delta:X.delta.content,snapshot:G.message.content,parsed:G.message.parsed});if(X.delta.refusal!=null&&G.message?.role==="assistant"&&G.message?.refusal)this._emit("refusal.delta",{delta:X.delta.refusal,snapshot:G.message.refusal});if(X.logprobs?.content!=null&&G.message?.role==="assistant")this._emit("logprobs.content.delta",{content:X.logprobs?.content,snapshot:G.logprobs?.content??[]});if(X.logprobs?.refusal!=null&&G.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:X.logprobs?.refusal,snapshot:G.logprobs?.refusal??[]});let K=k(this,n,"m",i6).call(this,G);if(G.finish_reason){if(k(this,n,"m",k8).call(this,G),K.current_tool_call_index!=null)k(this,n,"m",I8).call(this,G,K.current_tool_call_index)}for(let W of X.delta.tool_calls??[]){if(K.current_tool_call_index!==W.index){if(k(this,n,"m",k8).call(this,G),K.current_tool_call_index!=null)k(this,n,"m",I8).call(this,G,K.current_tool_call_index)}K.current_tool_call_index=W.index}for(let W of X.delta.tool_calls??[]){let z=G.message.tool_calls?.[W.index];if(!z?.type)continue;if(z?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:z.function?.name,index:W.index,arguments:z.function.arguments,parsed_arguments:z.function.parsed_arguments,arguments_delta:W.function?.arguments??""});else _Z(z?.type)}}},I8=function(Y,Z){if(k(this,n,"m",i6).call(this,Y).done_tool_calls.has(Z))return;let G=Y.message.tool_calls?.[Z];if(!G)throw Error("no tool call snapshot");if(!G.type)throw Error("tool call snapshot missing `type`");if(G.type==="function"){let K=k(this,p0,"f")?.tools?.find((W)=>W.type==="function"&&W.function.name===G.function.name);this._emit("tool_calls.function.arguments.done",{name:G.function.name,index:Z,arguments:G.function.arguments,parsed_arguments:A1(K)?K.$parseRaw(G.function.arguments):K?.function.strict?JSON.parse(G.function.arguments):null})}else _Z(G.type)},k8=function(Y){let Z=k(this,n,"m",i6).call(this,Y);if(Y.message.content&&!Z.content_done){Z.content_done=!0;let X=k(this,n,"m",b8).call(this);this._emit("content.done",{content:Y.message.content,parsed:X?X.$parseRaw(Y.message.content):null})}if(Y.message.refusal&&!Z.refusal_done)Z.refusal_done=!0,this._emit("refusal.done",{refusal:Y.message.refusal});if(Y.logprobs?.content&&!Z.logprobs_content_done)Z.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:Y.logprobs.content});if(Y.logprobs?.refusal&&!Z.logprobs_refusal_done)Z.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:Y.logprobs.refusal})},n6=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");let Y=k(this,X1,"f");if(!Y)throw new F("request ended without sending any chunks");return E4(this,X1,void 0,"f"),E4(this,q4,[],"f"),k5(Y,k(this,p0,"f"))},b8=function(){let Y=k(this,p0,"f")?.response_format;if(S$(Y))return Y;return null},qZ=function(Y){var Z,X,G,K;let W=k(this,X1,"f"),{choices:z,...Q}=Y;if(!W)W=E4(this,X1,{...Q,choices:[]},"f");else Object.assign(W,Q);for(let{delta:J,finish_reason:U,index:N,logprobs:D=null,...O}of Y.choices){let V=W.choices[N];if(!V)V=W.choices[N]={finish_reason:U,index:N,message:{},logprobs:D,...O};if(D)if(!V.logprobs)V.logprobs=Object.assign({},D);else{let{content:X0,refusal:G0,...v}=D;if(CZ(v),Object.assign(V.logprobs,v),X0)(Z=V.logprobs).content??(Z.content=[]),V.logprobs.content.push(...X0);if(G0)(X=V.logprobs).refusal??(X.refusal=[]),V.logprobs.refusal.push(...G0)}if(U){if(V.finish_reason=U,k(this,p0,"f")&&q8(k(this,p0,"f"))){if(U==="length")throw new H$;if(U==="content_filter")throw new U$}}if(Object.assign(V,O),!J)continue;let{content:R,refusal:f,function_call:y,role:C,tool_calls:l,...b}=J;if(CZ(b),Object.assign(V.message,b),f)V.message.refusal=(V.message.refusal||"")+f;if(C)V.message.role=C;if(y)if(!V.message.function_call)V.message.function_call=y;else{if(y.name)V.message.function_call.name=y.name;if(y.arguments)(G=V.message.function_call).arguments??(G.arguments=""),V.message.function_call.arguments+=y.arguments}if(R){if(V.message.content=(V.message.content||"")+R,!V.message.refusal&&k(this,n,"m",b8).call(this))V.message.parsed=S8(V.message.content)}if(l){if(!V.message.tool_calls)V.message.tool_calls=[];for(let{index:X0,id:G0,type:v,function:Z0,...S0}of l){let T=(K=V.message.tool_calls)[X0]??(K[X0]={});if(Object.assign(T,S0),G0)T.id=G0;if(v)T.type=v;if(Z0)T.function??(T.function={name:Z0.name??"",arguments:""});if(Z0?.name)T.function.name=Z0.name;if(Z0?.arguments){if(T.function.arguments+=Z0.arguments,DZ(k(this,p0,"f"),T))T.function.parsed_arguments=S8(T.function.arguments)}}}}return W},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("chunk",(X)=>{let G=Y.shift();if(G)G.resolve(X);else $.push(X)}),this.on("end",()=>{Z=!0;for(let X of Y)X.resolve(void 0);Y.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),this.on("error",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((G,K)=>Y.push({resolve:G,reject:K})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new U0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var P1;var AZ=H(()=>{f8();P1=class P1 extends x1{static fromReadableStream($){let Y=new P1(null);return Y._run(()=>Y._fromReadableStream($)),Y}static runFunctions($,Y,Z){let X=new P1(null),G={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return X._run(()=>X._runFunctions($,Y,G)),X}static runTools($,Y,Z){let X=new P1(Y),G={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return X._run(()=>X._runTools($,Y,G)),X}}});var r6;var xZ=H(()=>{LZ();AZ();f8();j$();r6=class r6 extends B{parse($,Y){return VZ($.tools),this._client.chat.completions.create($,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((Z)=>T$(Z,$))}runFunctions($,Y){if($.stream)return P1.runFunctions(this._client,$,Y);return M4.runFunctions(this._client,$,Y)}runTools($,Y){if($.stream)return P1.runTools(this._client,$,Y);return M4.runTools(this._client,$,Y)}stream($,Y){return x1.createChatCompletion(this._client,$,Y)}}});var k$;var PZ=H(()=>{xZ();k$=class k$ extends B{constructor(){super(...arguments);this.completions=new r6(this._client)}};(function($){$.Completions=r6})(k$||(k$={}))});var b$;var y8=H(()=>{b$=class b$ extends B{create($,Y){return this._client.post("/realtime/sessions",{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}});var f$;var h8=H(()=>{f$=class f$ extends B{create($,Y){return this._client.post("/realtime/transcription_sessions",{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}}});var R1;var g8=H(()=>{y8();y8();h8();h8();R1=class R1 extends B{constructor(){super(...arguments);this.sessions=new b$(this._client),this.transcriptionSessions=new f$(this._client)}};R1.Sessions=b$;R1.TranscriptionSessions=f$});var C4,y$;var v8=H(()=>{x();p();C4=class C4 extends B{create($,Y,Z){return this._client.post(`/threads/${$}/messages`,{body:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}retrieve($,Y,Z){return this._client.get(`/threads/${$}/messages/${Y}`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}update($,Y,Z,X){return this._client.post(`/threads/${$}/messages/${Y}`,{body:Z,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/threads/${$}/messages`,y$,{query:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}del($,Y,Z){return this._client.delete(`/threads/${$}/messages/${Y}`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}};y$=class y$ extends P{};C4.MessagesPage=y$});var _4,h$;var m8=H(()=>{x();p();_4=class _4 extends B{retrieve($,Y,Z,X={},G){if(q(X))return this.retrieve($,Y,Z,{},X);return this._client.get(`/threads/${$}/runs/${Y}/steps/${Z}`,{query:X,...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}list($,Y,Z={},X){if(q(Z))return this.list($,Y,{},Z);return this._client.getAPIList(`/threads/${$}/runs/${Y}/steps`,h$,{query:Z,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}};h$=class h$ extends P{};_4.RunStepsPage=h$});var G1,g$;var c8=H(()=>{x();w8();x();m8();m8();p();G1=class G1 extends B{constructor(){super(...arguments);this.steps=new _4(this._client)}create($,Y,Z){let{include:X,...G}=Y;return this._client.post(`/threads/${$}/runs`,{query:{include:X},body:G,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers},stream:Y.stream??!1})}retrieve($,Y,Z){return this._client.get(`/threads/${$}/runs/${Y}`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}update($,Y,Z,X){return this._client.post(`/threads/${$}/runs/${Y}`,{body:Z,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/threads/${$}/runs`,g$,{query:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}cancel($,Y,Z){return this._client.post(`/threads/${$}/runs/${Y}/cancel`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}async createAndPoll($,Y,Z){let X=await this.create($,Y,Z);return await this.poll($,X.id,Z)}createAndStream($,Y,Z){return V0.createAssistantStream($,this._client.beta.threads.runs,Y,Z)}async poll($,Y,Z){let X={...Z?.headers,"X-Stainless-Poll-Helper":"true"};if(Z?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=Z.pollIntervalMs.toString();while(!0){let{data:G,response:K}=await this.retrieve($,Y,{...Z,headers:{...Z?.headers,...X}}).withResponse();switch(G.status){case"queued":case"in_progress":case"cancelling":let W=5000;if(Z?.pollIntervalMs)W=Z.pollIntervalMs;else{let z=K.headers.get("openai-poll-after-ms");if(z){let Q=parseInt(z);if(!isNaN(Q))W=Q}}await v0(W);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return G}}}stream($,Y,Z){return V0.createAssistantStream($,this._client.beta.threads.runs,Y,Z)}submitToolOutputs($,Y,Z,X){return this._client.post(`/threads/${$}/runs/${Y}/submit_tool_outputs`,{body:Z,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers},stream:Z.stream??!1})}async submitToolOutputsAndPoll($,Y,Z,X){let G=await this.submitToolOutputs($,Y,Z,X);return await this.poll($,G.id,X)}submitToolOutputsStream($,Y,Z,X){return V0.createToolAssistantStream($,Y,this._client.beta.threads.runs,Z,X)}};g$=class g$ extends P{};G1.RunsPage=g$;G1.Steps=_4;G1.RunStepsPage=h$});var l0;var d8=H(()=>{x();w8();v8();v8();c8();c8();l0=class l0 extends B{constructor(){super(...arguments);this.runs=new G1(this._client),this.messages=new C4(this._client)}create($={},Y){if(q($))return this.create({},$);return this._client.post("/threads",{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}retrieve($,Y){return this._client.get(`/threads/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}update($,Y,Z){return this._client.post(`/threads/${$}`,{body:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}del($,Y){return this._client.delete(`/threads/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}createAndRun($,Y){return this._client.post("/threads/runs",{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers},stream:$.stream??!1})}async createAndRunPoll($,Y){let Z=await this.createAndRun($,Y);return await this.runs.poll(Z.thread_id,Z.id,Y)}createAndRunStream($,Y){return V0.createThreadAssistantStream($,this._client.beta.threads,Y)}};l0.Runs=G1;l0.RunsPage=g$;l0.Messages=C4;l0.MessagesPage=y$});var R0;var u8=H(()=>{L8();PZ();L8();g8();g8();d8();d8();R0=class R0 extends B{constructor(){super(...arguments);this.realtime=new R1(this._client),this.chat=new k$(this._client),this.assistants=new O4(this._client),this.threads=new l0(this._client)}};R0.Realtime=R1;R0.Assistants=O4;R0.AssistantsPage=R$;R0.Threads=l0});var A4;var p8=H(()=>{A4=class A4 extends B{create($,Y){return this._client.post("/completions",{body:$,...Y,stream:$.stream??!1})}}});var v$;var l8=H(()=>{v$=class v$ extends B{retrieve($,Y,Z){return this._client.get(`/containers/${$}/files/${Y}/content`,{...Z,headers:{Accept:"application/binary",...Z?.headers},__binaryResponse:!0})}}});var S1,m$;var i8=H(()=>{x();x();l8();l8();p();S1=class S1 extends B{constructor(){super(...arguments);this.content=new v$(this._client)}create($,Y,Z){return this._client.post(`/containers/${$}/files`,z0({body:Y,...Z}))}retrieve($,Y,Z){return this._client.get(`/containers/${$}/files/${Y}`,Z)}list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/containers/${$}/files`,m$,{query:Y,...Z})}del($,Y,Z){return this._client.delete(`/containers/${$}/files/${Y}`,{...Z,headers:{Accept:"*/*",...Z?.headers}})}};m$=class m$ extends P{};S1.FileListResponsesPage=m$;S1.Content=v$});var i0,x4;var n8=H(()=>{x();i8();i8();p();i0=class i0 extends B{constructor(){super(...arguments);this.files=new S1(this._client)}create($,Y){return this._client.post("/containers",{body:$,...Y})}retrieve($,Y){return this._client.get(`/containers/${$}`,Y)}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/containers",x4,{query:$,...Y})}del($,Y){return this._client.delete(`/containers/${$}`,{...Y,headers:{Accept:"*/*",...Y?.headers}})}};x4=class x4 extends P{};i0.ContainerListResponsesPage=x4;i0.Files=S1;i0.FileListResponsesPage=m$});var P4;var a8=H(()=>{x();P4=class P4 extends B{create($,Y){let Z=!!$.encoding_format,X=Z?$.encoding_format:"base64";if(Z)g0("Request","User defined encoding_format:",$.encoding_format);let G=this._client.post("/embeddings",{body:{...$,encoding_format:X},...Y});if(Z)return G;return g0("response","Decoding base64 embeddings to float32 array"),G._thenUnwrap((K)=>{if(K&&K.data)K.data.forEach((W)=>{let z=W.embedding;W.embedding=ZZ(z)});return K})}}});var R4,c$;var r8=H(()=>{x();p();R4=class R4 extends B{retrieve($,Y,Z,X){return this._client.get(`/evals/${$}/runs/${Y}/output_items/${Z}`,X)}list($,Y,Z={},X){if(q(Z))return this.list($,Y,{},Z);return this._client.getAPIList(`/evals/${$}/runs/${Y}/output_items`,c$,{query:Z,...X})}};c$=class c$ extends P{};R4.OutputItemListResponsesPage=c$});var K1,d$;var s8=H(()=>{x();r8();r8();p();K1=class K1 extends B{constructor(){super(...arguments);this.outputItems=new R4(this._client)}create($,Y,Z){return this._client.post(`/evals/${$}/runs`,{body:Y,...Z})}retrieve($,Y,Z){return this._client.get(`/evals/${$}/runs/${Y}`,Z)}list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/evals/${$}/runs`,d$,{query:Y,...Z})}del($,Y,Z){return this._client.delete(`/evals/${$}/runs/${Y}`,Z)}cancel($,Y,Z){return this._client.post(`/evals/${$}/runs/${Y}`,Z)}};d$=class d$ extends P{};K1.RunListResponsesPage=d$;K1.OutputItems=R4;K1.OutputItemListResponsesPage=c$});var n0,S4;var o8=H(()=>{x();s8();s8();p();n0=class n0 extends B{constructor(){super(...arguments);this.runs=new K1(this._client)}create($,Y){return this._client.post("/evals",{body:$,...Y})}retrieve($,Y){return this._client.get(`/evals/${$}`,Y)}update($,Y,Z){return this._client.post(`/evals/${$}`,{body:Y,...Z})}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/evals",S4,{query:$,...Y})}del($,Y){return this._client.delete(`/evals/${$}`,Y)}};S4=class S4 extends P{};n0.EvalListResponsesPage=S4;n0.Runs=K1;n0.RunListResponsesPage=d$});var T1,T4;var t8=H(()=>{x();x();W0();x();p();T1=class T1 extends B{create($,Y){return this._client.post("/files",z0({body:$,...Y}))}retrieve($,Y){return this._client.get(`/files/${$}`,Y)}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/files",T4,{query:$,...Y})}del($,Y){return this._client.delete(`/files/${$}`,Y)}content($,Y){return this._client.get(`/files/${$}/content`,{...Y,headers:{Accept:"application/binary",...Y?.headers},__binaryResponse:!0})}retrieveContent($,Y){return this._client.get(`/files/${$}/content`,Y)}async waitForProcessing($,{pollInterval:Y=5000,maxWait:Z=1800000}={}){let X=new Set(["processed","error","deleted"]),G=Date.now(),K=await this.retrieve($);while(!K.status||!X.has(K.status))if(await v0(Y),K=await this.retrieve($),Date.now()-G>Z)throw new h0({message:`Giving up on waiting for file ${$} to finish processing after ${Z} milliseconds.`});return K}};T4=class T4 extends P{};T1.FileObjectsPage=T4});var u$;var e8=H(()=>{u$=class u$ extends B{}});var p$;var $Y=H(()=>{p$=class p$ extends B{run($,Y){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...Y})}validate($,Y){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...Y})}}});var j4;var YY=H(()=>{$Y();$Y();j4=class j4 extends B{constructor(){super(...arguments);this.graders=new p$(this._client)}};j4.Graders=p$});var I4,l$;var ZY=H(()=>{x();p();I4=class I4 extends B{create($,Y,Z){return this._client.getAPIList(`/fine_tuning/checkpoints/${$}/permissions`,l$,{body:Y,method:"post",...Z})}retrieve($,Y={},Z){if(q(Y))return this.retrieve($,{},Y);return this._client.get(`/fine_tuning/checkpoints/${$}/permissions`,{query:Y,...Z})}del($,Y,Z){return this._client.delete(`/fine_tuning/checkpoints/${$}/permissions/${Y}`,Z)}};l$=class l$ extends c0{};I4.PermissionCreateResponsesPage=l$});var j1;var XY=H(()=>{ZY();ZY();j1=class j1 extends B{constructor(){super(...arguments);this.permissions=new I4(this._client)}};j1.Permissions=I4;j1.PermissionCreateResponsesPage=l$});var k4,i$;var GY=H(()=>{x();p();k4=class k4 extends B{list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/fine_tuning/jobs/${$}/checkpoints`,i$,{query:Y,...Z})}};i$=class i$ extends P{};k4.FineTuningJobCheckpointsPage=i$});var a0,n$,a$;var KY=H(()=>{x();GY();GY();p();a0=class a0 extends B{constructor(){super(...arguments);this.checkpoints=new k4(this._client)}create($,Y){return this._client.post("/fine_tuning/jobs",{body:$,...Y})}retrieve($,Y){return this._client.get(`/fine_tuning/jobs/${$}`,Y)}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/fine_tuning/jobs",n$,{query:$,...Y})}cancel($,Y){return this._client.post(`/fine_tuning/jobs/${$}/cancel`,Y)}listEvents($,Y={},Z){if(q(Y))return this.listEvents($,{},Y);return this._client.getAPIList(`/fine_tuning/jobs/${$}/events`,a$,{query:Y,...Z})}pause($,Y){return this._client.post(`/fine_tuning/jobs/${$}/pause`,Y)}resume($,Y){return this._client.post(`/fine_tuning/jobs/${$}/resume`,Y)}};n$=class n$ extends P{};a$=class a$ extends P{};a0.FineTuningJobsPage=n$;a0.FineTuningJobEventsPage=a$;a0.Checkpoints=k4;a0.FineTuningJobCheckpointsPage=i$});var M0;var WY=H(()=>{e8();e8();YY();YY();XY();XY();KY();KY();M0=class M0 extends B{constructor(){super(...arguments);this.methods=new u$(this._client),this.jobs=new a0(this._client),this.checkpoints=new j1(this._client),this.alpha=new j4(this._client)}};M0.Methods=u$;M0.Jobs=a0;M0.FineTuningJobsPage=n$;M0.FineTuningJobEventsPage=a$;M0.Checkpoints=j1;M0.Alpha=j4});var r$;var zY=H(()=>{r$=class r$ extends B{}});var I1;var QY=H(()=>{zY();zY();I1=class I1 extends B{constructor(){super(...arguments);this.graderModels=new r$(this._client)}};I1.GraderModels=r$});var b4;var JY=H(()=>{x();b4=class b4 extends B{createVariation($,Y){return this._client.post("/images/variations",z0({body:$,...Y}))}edit($,Y){return this._client.post("/images/edits",z0({body:$,...Y}))}generate($,Y){return this._client.post("/images/generations",{body:$,...Y})}}});var k1,f4;var NY=H(()=>{p();k1=class k1 extends B{retrieve($,Y){return this._client.get(`/models/${$}`,Y)}list($){return this._client.getAPIList("/models",f4,$)}del($,Y){return this._client.delete(`/models/${$}`,Y)}};f4=class f4 extends c0{};k1.ModelsPage=f4});var y4;var HY=H(()=>{y4=class y4 extends B{create($,Y){return this._client.post("/moderations",{body:$,...Y})}}});function RZ($,Y){if(!Y||!Z7(Y))return{...$,output_parsed:null,output:$.output.map((Z)=>{if(Z.type==="function_call")return{...Z,parsed_arguments:null};if(Z.type==="message")return{...Z,content:Z.content.map((X)=>({...X,parsed:null}))};else return Z})};return UY($,Y)}function UY($,Y){let Z=$.output.map((G)=>{if(G.type==="function_call")return{...G,parsed_arguments:K7(Y,G)};if(G.type==="message"){let K=G.content.map((W)=>{if(W.type==="output_text")return{...W,parsed:Y7(Y,W.text)};return W});return{...G,content:K}}return G}),X=Object.assign({},$,{output:Z});if(!Object.getOwnPropertyDescriptor($,"output_text"))BY(X);return Object.defineProperty(X,"output_parsed",{enumerable:!0,get(){for(let G of X.output){if(G.type!=="message")continue;for(let K of G.content)if(K.type==="output_text"&&K.parsed!==null)return K.parsed}return null}}),X}function Y7($,Y){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(Y);return JSON.parse(Y)}function Z7($){if(S$($.text?.format))return!0;return!1}function X7($){return $?.$brand==="auto-parseable-tool"}function G7($,Y){return $.find((Z)=>Z.type==="function"&&Z.name===Y)}function K7($,Y){let Z=G7($.tools??[],Y.name);return{...Y,...Y,parsed_arguments:X7(Z)?Z.$parseRaw(Y.arguments):Z?.strict?JSON.parse(Y.arguments):null}}function BY($){let Y=[];for(let Z of $.output){if(Z.type!=="message")continue;for(let X of Z.content)if(X.type==="output_text")Y.push(X.text)}$.output_text=Y.join("")}var DY=H(()=>{j$()});var s$;var VY=H(()=>{x();s6();s$=class s$ extends B{list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/responses/${$}/input_items`,FY,{query:Y,...Z})}}});function z7($,Y){return RZ($,Y)}var h4=function($,Y,Z,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Y==="function"?$!==Y||!G:!Y.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call($,Z):G?G.value=Z:Y.set($,Z),Z},W1=function($,Y,Z,X){if(Z==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Y==="function"?$!==Y||!X:!Y.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?X:Z==="a"?X.call($):X?X.value:Y.get($)},g4,o6,z1,t6,SZ,TZ,jZ,IZ,e6;var kZ=H(()=>{W0();m6();DY();e6=class e6 extends q1{constructor($){super();g4.add(this),o6.set(this,void 0),z1.set(this,void 0),t6.set(this,void 0),h4(this,o6,$,"f")}static createResponse($,Y,Z){let X=new e6(Y);return X._run(()=>X._createOrRetrieveResponse($,Y,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createOrRetrieveResponse($,Y,Z){let X=Z?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}W1(this,g4,"m",SZ).call(this);let G,K=null;if("response_id"in Y)G=await $.responses.retrieve(Y.response_id,{stream:!0},{...Z,signal:this.controller.signal,stream:!0}),K=Y.starting_after??null;else G=await $.responses.create({...Y,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let W of G)W1(this,g4,"m",TZ).call(this,W,K);if(G.controller.signal?.aborted)throw new d;return W1(this,g4,"m",jZ).call(this)}[(o6=new WeakMap,z1=new WeakMap,t6=new WeakMap,g4=new WeakSet,SZ=function(){if(this.ended)return;h4(this,z1,void 0,"f")},TZ=function(Y,Z){if(this.ended)return;let X=(K,W)=>{if(Z==null||W.sequence_number>Z)this._emit(K,W)},G=W1(this,g4,"m",IZ).call(this,Y);switch(X("event",Y),Y.type){case"response.output_text.delta":{let K=G.output[Y.output_index];if(!K)throw new F(`missing output at index ${Y.output_index}`);if(K.type==="message"){let W=K.content[Y.content_index];if(!W)throw new F(`missing content at index ${Y.content_index}`);if(W.type!=="output_text")throw new F(`expected content to be 'output_text', got ${W.type}`);X("response.output_text.delta",{...Y,snapshot:W.text})}break}case"response.function_call_arguments.delta":{let K=G.output[Y.output_index];if(!K)throw new F(`missing output at index ${Y.output_index}`);if(K.type==="function_call")X("response.function_call_arguments.delta",{...Y,snapshot:K.arguments});break}default:X(Y.type,Y);break}},jZ=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");let Y=W1(this,z1,"f");if(!Y)throw new F("request ended without sending any events");h4(this,z1,void 0,"f");let Z=z7(Y,W1(this,o6,"f"));return h4(this,t6,Z,"f"),Z},IZ=function(Y){let Z=W1(this,z1,"f");if(!Z){if(Y.type!=="response.created")throw new F(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Y.type}`);return Z=h4(this,z1,Y.response,"f"),Z}switch(Y.type){case"response.output_item.added":{Z.output.push(Y.item);break}case"response.content_part.added":{let X=Z.output[Y.output_index];if(!X)throw new F(`missing output at index ${Y.output_index}`);if(X.type==="message")X.content.push(Y.part);break}case"response.output_text.delta":{let X=Z.output[Y.output_index];if(!X)throw new F(`missing output at index ${Y.output_index}`);if(X.type==="message"){let G=X.content[Y.content_index];if(!G)throw new F(`missing content at index ${Y.content_index}`);if(G.type!=="output_text")throw new F(`expected content to be 'output_text', got ${G.type}`);G.text+=Y.delta}break}case"response.function_call_arguments.delta":{let X=Z.output[Y.output_index];if(!X)throw new F(`missing output at index ${Y.output_index}`);if(X.type==="function_call")X.arguments+=Y.delta;break}case"response.completed":{h4(this,z1,Y.response,"f");break}}return Z},Symbol.asyncIterator)](){let $=[],Y=[],Z=!1;return this.on("event",(X)=>{let G=Y.shift();if(G)G.resolve(X);else $.push(X)}),this.on("end",()=>{Z=!0;for(let X of Y)X.resolve(void 0);Y.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),this.on("error",(X)=>{Z=!0;for(let G of Y)G.reject(X);Y.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((G,K)=>Y.push({resolve:G,reject:K})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=W1(this,t6,"f");if(!$)throw new F("stream ended without producing a ChatCompletion");return $}}});var b1,FY;var s6=H(()=>{DY();VY();VY();kZ();p();b1=class b1 extends B{constructor(){super(...arguments);this.inputItems=new s$(this._client)}create($,Y){return this._client.post("/responses",{body:$,...Y,stream:$.stream??!1})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")BY(Z);return Z})}retrieve($,Y={},Z){return this._client.get(`/responses/${$}`,{query:Y,...Z,stream:Y?.stream??!1})}del($,Y){return this._client.delete(`/responses/${$}`,{...Y,headers:{Accept:"*/*",...Y?.headers}})}parse($,Y){return this._client.responses.create($,Y)._thenUnwrap((Z)=>UY(Z,$))}stream($,Y){return e6.createResponse(this._client,$,Y)}cancel($,Y){return this._client.post(`/responses/${$}/cancel`,{...Y,headers:{Accept:"*/*",...Y?.headers}})}};FY=class FY extends P{};b1.InputItems=s$});var o$;var wY=H(()=>{x();o$=class o$ extends B{create($,Y,Z){return this._client.post(`/uploads/${$}/parts`,z0({body:Y,...Z}))}}});var f1;var LY=H(()=>{wY();wY();f1=class f1 extends B{constructor(){super(...arguments);this.parts=new o$(this._client)}create($,Y){return this._client.post("/uploads",{body:$,...Y})}cancel($,Y){return this._client.post(`/uploads/${$}/cancel`,Y)}complete($,Y,Z){return this._client.post(`/uploads/${$}/complete`,{body:Y,...Z})}};f1.Parts=o$});var bZ=async($)=>{let Y=await Promise.allSettled($),Z=Y.filter((G)=>G.status==="rejected");if(Z.length){for(let G of Z)console.error(G.reason);throw Error(`${Z.length} promise(s) failed - see the above errors`)}let X=[];for(let G of Y)if(G.status==="fulfilled")X.push(G.value);return X};var y1,h1,t$;var $2=H(()=>{x();p();y1=class y1 extends B{create($,Y,Z){return this._client.post(`/vector_stores/${$}/files`,{body:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}retrieve($,Y,Z){return this._client.get(`/vector_stores/${$}/files/${Y}`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}update($,Y,Z,X){return this._client.post(`/vector_stores/${$}/files/${Y}`,{body:Z,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}list($,Y={},Z){if(q(Y))return this.list($,{},Y);return this._client.getAPIList(`/vector_stores/${$}/files`,h1,{query:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}del($,Y,Z){return this._client.delete(`/vector_stores/${$}/files/${Y}`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}async createAndPoll($,Y,Z){let X=await this.create($,Y,Z);return await this.poll($,X.id,Z)}async poll($,Y,Z){let X={...Z?.headers,"X-Stainless-Poll-Helper":"true"};if(Z?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=Z.pollIntervalMs.toString();while(!0){let G=await this.retrieve($,Y,{...Z,headers:X}).withResponse(),K=G.data;switch(K.status){case"in_progress":let W=5000;if(Z?.pollIntervalMs)W=Z.pollIntervalMs;else{let z=G.response.headers.get("openai-poll-after-ms");if(z){let Q=parseInt(z);if(!isNaN(Q))W=Q}}await v0(W);break;case"failed":case"completed":return K}}}async upload($,Y,Z){let X=await this._client.files.create({file:Y,purpose:"assistants"},Z);return this.create($,{file_id:X.id},Z)}async uploadAndPoll($,Y,Z){let X=await this.upload($,Y,Z);return await this.poll($,X.id,Z)}content($,Y,Z){return this._client.getAPIList(`/vector_stores/${$}/files/${Y}/content`,t$,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}};h1=class h1 extends P{};t$=class t$ extends c0{};y1.VectorStoreFilesPage=h1;y1.FileContentResponsesPage=t$});var e$;var OY=H(()=>{x();x();$2();e$=class e$ extends B{create($,Y,Z){return this._client.post(`/vector_stores/${$}/file_batches`,{body:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}retrieve($,Y,Z){return this._client.get(`/vector_stores/${$}/file_batches/${Y}`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}cancel($,Y,Z){return this._client.post(`/vector_stores/${$}/file_batches/${Y}/cancel`,{...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}async createAndPoll($,Y,Z){let X=await this.create($,Y);return await this.poll($,X.id,Z)}listFiles($,Y,Z={},X){if(q(Z))return this.listFiles($,Y,{},Z);return this._client.getAPIList(`/vector_stores/${$}/file_batches/${Y}/files`,h1,{query:Z,...X,headers:{"OpenAI-Beta":"assistants=v2",...X?.headers}})}async poll($,Y,Z){let X={...Z?.headers,"X-Stainless-Poll-Helper":"true"};if(Z?.pollIntervalMs)X["X-Stainless-Custom-Poll-Interval"]=Z.pollIntervalMs.toString();while(!0){let{data:G,response:K}=await this.retrieve($,Y,{...Z,headers:X}).withResponse();switch(G.status){case"in_progress":let W=5000;if(Z?.pollIntervalMs)W=Z.pollIntervalMs;else{let z=K.headers.get("openai-poll-after-ms");if(z){let Q=parseInt(z);if(!isNaN(Q))W=Q}}await v0(W);break;case"failed":case"cancelled":case"completed":return G}}}async uploadAndPoll($,{files:Y,fileIds:Z=[]},X){if(Y==null||Y.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let G=X?.maxConcurrency??5,K=Math.min(G,Y.length),W=this._client,z=Y.values(),Q=[...Z];async function J(N){for(let D of N){let O=await W.files.create({file:D,purpose:"assistants"},X);Q.push(O.id)}}let U=Array(K).fill(z).map(J);return await bZ(U),await this.createAndPoll($,{file_ids:Q})}}});var E0,v4,m4;var MY=H(()=>{x();OY();OY();$2();$2();p();E0=class E0 extends B{constructor(){super(...arguments);this.files=new y1(this._client),this.fileBatches=new e$(this._client)}create($,Y){return this._client.post("/vector_stores",{body:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}retrieve($,Y){return this._client.get(`/vector_stores/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}update($,Y,Z){return this._client.post(`/vector_stores/${$}`,{body:Y,...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}list($={},Y){if(q($))return this.list({},$);return this._client.getAPIList("/vector_stores",v4,{query:$,...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}del($,Y){return this._client.delete(`/vector_stores/${$}`,{...Y,headers:{"OpenAI-Beta":"assistants=v2",...Y?.headers}})}search($,Y,Z){return this._client.getAPIList(`/vector_stores/${$}/search`,m4,{body:Y,method:"post",...Z,headers:{"OpenAI-Beta":"assistants=v2",...Z?.headers}})}};v4=class v4 extends P{};m4=class m4 extends c0{};E0.VectorStoresPage=v4;E0.VectorStoreSearchResponsesPage=m4;E0.Files=y1;E0.VectorStoreFilesPage=h1;E0.FileContentResponsesPage=t$;E0.FileBatches=e$});var fZ=H(()=>{B8();D8();u8();p8();n8();a8();o8();t8();WY();QY();JY();NY();HY();s6();LY();MY();XZ();GZ()});var EY={};K2(EY,{toFile:()=>D$,fileFromPath:()=>K4,default:()=>B7,UnprocessableEntityError:()=>H4,RateLimitError:()=>U4,PermissionDeniedError:()=>Q4,OpenAIError:()=>F,OpenAI:()=>E,NotFoundError:()=>J4,InternalServerError:()=>B4,ConflictError:()=>N4,BadRequestError:()=>W4,AzureOpenAI:()=>gZ,AuthenticationError:()=>z4,APIUserAbortError:()=>d,APIError:()=>m,APIConnectionTimeoutError:()=>h0,APIConnectionError:()=>y0});var hZ,E,gZ,U7,yZ="<Missing Key>",B7;var qY=H(()=>{T9();x();W0();V$();fZ();D8();p8();a8();t8();JY();NY();HY();B8();u8();J8();n8();o8();WY();QY();s6();LY();MY();w$();V$();W0();E=class E extends W8{constructor({baseURL:$=$1("OPENAI_BASE_URL"),apiKey:Y=$1("OPENAI_API_KEY"),organization:Z=$1("OPENAI_ORG_ID")??null,project:X=$1("OPENAI_PROJECT_ID")??null,...G}={}){if(Y===void 0)throw new F("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let K={apiKey:Y,organization:Z,project:X,...G,baseURL:$||"https://api.openai.com/v1"};if(!K.dangerouslyAllowBrowser&&YZ())throw new F(`It looks like you're running in a browser-like environment.
41
+
42
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
43
+ If you understand the risks and have appropriate mitigations in place,
44
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
45
+
46
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
47
+
48
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
49
+ `);super({baseURL:K.baseURL,timeout:K.timeout??600000,httpAgent:K.httpAgent,maxRetries:K.maxRetries,fetch:K.fetch});this.completions=new A4(this),this.chat=new Y1(this),this.embeddings=new P4(this),this.files=new T1(this),this.images=new b4(this),this.audio=new d0(this),this.moderations=new y4(this),this.models=new k1(this),this.fineTuning=new M0(this),this.graders=new I1(this),this.vectorStores=new E0(this),this.beta=new R0(this),this.batches=new E1(this),this.uploads=new f1(this),this.responses=new b1(this),this.evals=new n0(this),this.containers=new i0(this),this._options=K,this.apiKey=Y,this.organization=Z,this.project=X}defaultQuery(){return this._options.defaultQuery}defaultHeaders($){return{...super.defaultHeaders($),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders($){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery($){return l2($,{arrayFormat:"brackets"})}};hZ=E;E.OpenAI=hZ;E.DEFAULT_TIMEOUT=600000;E.OpenAIError=F;E.APIError=m;E.APIConnectionError=y0;E.APIConnectionTimeoutError=h0;E.APIUserAbortError=d;E.NotFoundError=J4;E.ConflictError=N4;E.RateLimitError=U4;E.BadRequestError=W4;E.AuthenticationError=z4;E.InternalServerError=B4;E.PermissionDeniedError=Q4;E.UnprocessableEntityError=H4;E.toFile=D$;E.fileFromPath=K4;E.Completions=A4;E.Chat=Y1;E.ChatCompletionsPage=M1;E.Embeddings=P4;E.Files=T1;E.FileObjectsPage=T4;E.Images=b4;E.Audio=d0;E.Moderations=y4;E.Models=k1;E.ModelsPage=f4;E.FineTuning=M0;E.Graders=I1;E.VectorStores=E0;E.VectorStoresPage=v4;E.VectorStoreSearchResponsesPage=m4;E.Beta=R0;E.Batches=E1;E.BatchesPage=F4;E.Uploads=f1;E.Responses=b1;E.Evals=n0;E.EvalListResponsesPage=S4;E.Containers=i0;E.ContainerListResponsesPage=x4;gZ=class gZ extends E{constructor({baseURL:$=$1("OPENAI_BASE_URL"),apiKey:Y=$1("AZURE_OPENAI_API_KEY"),apiVersion:Z=$1("OPENAI_API_VERSION"),endpoint:X,deployment:G,azureADTokenProvider:K,dangerouslyAllowBrowser:W,...z}={}){if(!Z)throw new F("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof K==="function")W=!0;if(!K&&!Y)throw new F("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(K&&Y)throw new F("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(Y??(Y=yZ),z.defaultQuery={...z.defaultQuery,"api-version":Z},!$){if(!X)X=process.env.AZURE_OPENAI_ENDPOINT;if(!X)throw new F("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");$=`${X}/openai`}else if(X)throw new F("baseURL and endpoint are mutually exclusive");super({apiKey:Y,baseURL:$,...z,...W!==void 0?{dangerouslyAllowBrowser:W}:{}});this.apiVersion="",this._azureADTokenProvider=K,this.apiVersion=Z,this.deploymentName=G}buildRequest($,Y={}){if(U7.has($.path)&&$.method==="post"&&$.body!==void 0){if(!V4($.body))throw Error("Expected request body to be an object");let Z=this.deploymentName||$.body.model||$.__metadata?.model;if(Z!==void 0&&!this.baseURL.includes("/deployments"))$.path=`/deployments/${Z}${$.path}`}return super.buildRequest($,Y)}async _getAzureADToken(){if(typeof this._azureADTokenProvider==="function"){let $=await this._azureADTokenProvider();if(!$||typeof $!=="string")throw new F(`Expected 'azureADTokenProvider' argument to return a string but it returned ${$}`);return $}return}authHeaders($){return{}}async prepareOptions($){if($.headers?.["api-key"])return super.prepareOptions($);let Y=await this._getAzureADToken();if($.headers??($.headers={}),Y)$.headers.Authorization=`Bearer ${Y}`;else if(this.apiKey!==yZ)$.headers["api-key"]=this.apiKey;else throw new F("Unable to handle auth");return super.prepareOptions($)}};U7=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/images/edits"]),B7=E});function c4($,Y){let Z=Y||process.env.OPENAI_API_KEY;return{name:"openai",async available(){return!!Z},async analyze(X,G){return(await new(await Promise.resolve().then(() => (qY(),EY))).default({apiKey:Z}).chat.completions.create({model:$||"gpt-4o-mini",max_tokens:1500,messages:[{role:"user",content:G.replace("{{TEMPLATE}}",X)}]})).choices[0]?.message?.content||""}}}function d4($,Y){let Z=Y||"http://localhost:11434";return{name:"ollama",async available(){try{return(await fetch(`${Z}/api/tags`,{signal:AbortSignal.timeout(2000)})).ok}catch{return!1}},async analyze(X,G){let K=await fetch(`${Z}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$||"llama3.1",prompt:G.replace("{{TEMPLATE}}",X),stream:!1})});if(!K.ok)throw Error(`Ollama error: ${K.statusText}`);return(await K.json()).response}}}function u4($,Y){let Z=Y||process.env.GROQ_API_KEY;return{name:"groq",async available(){return!!Z},async analyze(X,G){if(!Z)throw Error("Groq API key not provided");let K=await fetch("https://api.groq.com/openai/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify({model:$||"llama-3.1-70b-versatile",max_tokens:1500,messages:[{role:"user",content:G.replace("{{TEMPLATE}}",X)}]})});if(!K.ok){let z=await K.text();throw Error(`Groq error: ${z}`)}return(await K.json()).choices[0]?.message?.content||""}}}function CY($,Y={}){switch($){case"anthropic":return G4(Y.model,Y.apiKey);case"openai":return c4(Y.model,Y.apiKey);case"ollama":return d4(Y.model,Y.ollamaUrl);case"groq":return u4(Y.model,Y.apiKey);default:throw Error(`Unknown provider: ${$}`)}}async function _Y($={}){let Y=[{name:"anthropic",create:()=>G4($.model,$.apiKey)},{name:"openai",create:()=>c4($.model,$.apiKey)},{name:"groq",create:()=>u4($.model,$.apiKey)},{name:"ollama",create:()=>d4($.model,$.ollamaUrl)}];for(let{name:Z,create:X}of Y){let G=X();if(await G.available())return G}throw Error(`No AI provider available.
50
+
51
+ Configure one of the following:
52
+ - ANTHROPIC_API_KEY (Claude)
53
+ - OPENAI_API_KEY (GPT-4)
54
+ - GROQ_API_KEY (Llama, free tier)
55
+ - Ollama running locally (http://localhost:11434)
56
+
57
+ Install SDK if needed:
58
+ bun add @anthropic-ai/sdk # for Claude
59
+ bun add openai # for OpenAI`)}async function Y2($={}){let Y=$.provider||"auto";if(Y==="auto")return _Y($);let Z=CY(Y,$);if(!await Z.available())throw Error(`Provider '${Y}' is not available. Check your API key or configuration.`);return Z}var Z2=()=>{};function vZ($){if(!$||$.length===0)return`Analyze this Jinja2/Django template for issues.
60
+
61
+ TEMPLATE:
62
+ \`\`\`jinja
63
+ {{TEMPLATE}}
64
+ \`\`\`
65
+
66
+ Check for:
67
+
68
+ 1. SECURITY
69
+ - XSS vulnerabilities (unescaped user input, |safe on untrusted data)
70
+ - Variables in onclick/onerror/javascript: without escapejs
71
+ - Sensitive data exposure (passwords, tokens, API keys)
72
+ - SQL/command injection patterns
73
+
74
+ 2. PERFORMANCE
75
+ - Heavy filters inside loops (date, filesizeformat)
76
+ - Repeated filter calls on same value (use {% with %})
77
+ - N+1 query patterns (accessing relations in loops)
78
+
79
+ 3. ACCESSIBILITY
80
+ - Images without alt text
81
+ - Forms without labels
82
+ - Missing ARIA attributes on interactive elements
83
+ - Poor heading hierarchy
84
+
85
+ 4. BEST PRACTICES
86
+ - {% for %} without {% empty %}
87
+ - Deeply nested conditionals (>3 levels)
88
+ - Magic numbers/strings (should be variables)
89
+ - Deprecated filter usage
90
+
91
+ Respond ONLY with valid JSON (no markdown, no explanation):
92
+ {
93
+ "issues": [
94
+ {
95
+ "line": 1,
96
+ "type": "security|performance|accessibility|best-practice",
97
+ "severity": "error|warning|suggestion",
98
+ "message": "Brief description",
99
+ "suggestion": "How to fix"
100
+ }
101
+ ]
102
+ }
103
+
104
+ If no issues found, return: {"issues": []}`;let Y={syntax:"SYNTAX",security:"SECURITY",performance:"PERFORMANCE",accessibility:"ACCESSIBILITY","best-practice":"BEST PRACTICES",deprecated:"DEPRECATED"},Z=$.map((X)=>Y[X]).filter(Boolean);return`Analyze this Jinja2/Django template for issues.
105
+
106
+ TEMPLATE:
107
+ \`\`\`jinja
108
+ {{TEMPLATE}}
109
+ \`\`\`
110
+
111
+ Check for:
112
+
113
+ 1. SECURITY
114
+ - XSS vulnerabilities (unescaped user input, |safe on untrusted data)
115
+ - Variables in onclick/onerror/javascript: without escapejs
116
+ - Sensitive data exposure (passwords, tokens, API keys)
117
+ - SQL/command injection patterns
118
+
119
+ 2. PERFORMANCE
120
+ - Heavy filters inside loops (date, filesizeformat)
121
+ - Repeated filter calls on same value (use {% with %})
122
+ - N+1 query patterns (accessing relations in loops)
123
+
124
+ 3. ACCESSIBILITY
125
+ - Images without alt text
126
+ - Forms without labels
127
+ - Missing ARIA attributes on interactive elements
128
+ - Poor heading hierarchy
129
+
130
+ 4. BEST PRACTICES
131
+ - {% for %} without {% empty %}
132
+ - Deeply nested conditionals (>3 levels)
133
+ - Magic numbers/strings (should be variables)
134
+ - Deprecated filter usage
135
+
136
+ Respond ONLY with valid JSON (no markdown, no explanation):
137
+ {
138
+ "issues": [
139
+ {
140
+ "line": 1,
141
+ "type": "security|performance|accessibility|best-practice",
142
+ "severity": "error|warning|suggestion",
143
+ "message": "Brief description",
144
+ "suggestion": "How to fix"
145
+ }
146
+ ]
147
+ }
148
+
149
+ If no issues found, return: {"issues": []}`.replace(/Check for:[\s\S]*?Respond ONLY/,`Check ONLY for: ${Z.join(", ")}
150
+
151
+ Respond ONLY`)}async function mZ($,Y={}){let Z=Date.now(),X={valid:!0,errors:[],warnings:[],suggestions:[]};try{let K=new Q1($).tokenize();new J1(K,$).parse()}catch(G){return X.valid=!1,X.errors.push({line:G.line||1,type:"syntax",severity:"error",message:G.message}),X.duration=Date.now()-Z,X}try{let G=await Y2(Y);X.provider=G.name;let K=vZ(Y.categories),W=await G.analyze($,K),z=D7(W);for(let Q of z){if(Y.maxIssues&&X.errors.length+X.warnings.length+X.suggestions.length>=Y.maxIssues)break;switch(Q.severity){case"error":X.errors.push(Q);break;case"warning":X.warnings.push(Q);break;case"suggestion":X.suggestions.push(Q);break}}X.valid=X.errors.length===0}catch(G){X.warnings.push({line:0,type:"best-practice",severity:"warning",message:`AI analysis failed: ${G.message}`})}return X.duration=Date.now()-Z,X}function D7($){try{let Y=$.trim(),Z=Y.match(/```(?:json)?\s*([\s\S]*?)```/);if(Z)Y=Z[1].trim();let X=Y.match(/\{[\s\S]*\}/);if(X)Y=X[0];let G=JSON.parse(Y);if(!G.issues||!Array.isArray(G.issues))return[];return G.issues.filter((K)=>K&&typeof K==="object").map((K)=>({line:typeof K.line==="number"?K.line:1,type:V7(K.type),severity:F7(K.severity),message:String(K.message||"Unknown issue"),suggestion:K.suggestion?String(K.suggestion):void 0}))}catch{return[]}}function V7($){return{security:"security",performance:"performance",accessibility:"accessibility",a11y:"accessibility","best-practice":"best-practice","best-practices":"best-practice",bestpractice:"best-practice",deprecated:"deprecated",syntax:"syntax"}[String($).toLowerCase()]||"best-practice"}function F7($){return{error:"error",warning:"warning",warn:"warning",suggestion:"suggestion",info:"suggestion",hint:"suggestion"}[String($).toLowerCase()]||"warning"}function cZ($){let Y={valid:!0,errors:[],warnings:[],suggestions:[]};try{let X=new Q1($).tokenize();new J1(X,$).parse()}catch(Z){Y.valid=!1,Y.errors.push({line:Z.line||1,type:"syntax",severity:"error",message:Z.message})}return Y}var dZ=H(()=>{$6();J2();Z2()});var uZ={};K2(uZ,{syntaxCheck:()=>cZ,resolveProvider:()=>Y2,lint:()=>mZ,getProvider:()=>CY,detectProvider:()=>_Y,createOpenAIProvider:()=>c4,createOllamaProvider:()=>d4,createGroqProvider:()=>u4,createAnthropicProvider:()=>G4});var pZ=H(()=>{dZ();Z2();Z2()});$6();J2();import*as g from"fs";import*as I from"path";function IY($,Y={}){return new kY(Y).compile($)}class kY{options;indent=0;varCounter=0;loopStack=[];localVars=[];constructor($={}){this.options={functionName:$.functionName??"render",inlineHelpers:$.inlineHelpers??!0,minify:$.minify??!1,autoescape:$.autoescape??!0}}pushScope(){this.localVars.push(new Set)}popScope(){this.localVars.pop()}addLocalVar($){if(this.localVars.length>0)this.localVars[this.localVars.length-1].add($)}isLocalVar($){for(let Y=this.localVars.length-1;Y>=0;Y--)if(this.localVars[Y].has($))return!0;return!1}compile($){let Y=this.compileNodes($.body),Z=this.options.minify?"":`
152
+ `;return`function ${this.options.functionName}(__ctx) {${Z} let __out = '';${Z}`+Y+` return __out;${Z}}`}compileNodes($){return $.map((Y)=>this.compileNode(Y)).join("")}compileNode($){switch($.type){case"Text":return this.compileText($);case"Output":return this.compileOutput($);case"If":return this.compileIf($);case"For":return this.compileFor($);case"Set":return this.compileSet($);case"With":return this.compileWith($);case"Comment":return"";case"Extends":case"Block":case"Include":throw Error(`AOT compilation does not support '${$.type}' - use Environment.render() for templates with inheritance`);case"Url":case"Static":throw Error(`AOT compilation does not support '${$.type}' tag - use Environment.render() with urlResolver/staticResolver`);default:throw Error(`Unknown node type in AOT compiler: ${$.type}`)}}compileText($){return` __out += ${JSON.stringify($.value)};${this.nl()}`}compileOutput($){let Y=this.compileExpr($.expression);if(this.options.autoescape&&!this.isMarkedSafe($.expression))return` __out += escape(${Y});${this.nl()}`;return` __out += (${Y}) ?? '';${this.nl()}`}compileIf($){let Y="",Z=this.compileExpr($.test);Y+=` if (isTruthy(${Z})) {${this.nl()}`,Y+=this.compileNodes($.body),Y+=" }";for(let X of $.elifs){let G=this.compileExpr(X.test);Y+=` else if (isTruthy(${G})) {${this.nl()}`,Y+=this.compileNodes(X.body),Y+=" }"}if($.else_.length>0)Y+=` else {${this.nl()}`,Y+=this.compileNodes($.else_),Y+=" }";return Y+=this.nl(),Y}compileFor($){let Y=this.genVar("iter"),Z=this.genVar("i"),X=this.genVar("len"),G=this.genVar("loop"),K=Array.isArray($.target)?$.target[0]:$.target,W=Array.isArray($.target)&&$.target[1]?$.target[1]:null,z=this.loopStack.length>0?this.loopStack[this.loopStack.length-1]:null,Q=this.compileExpr($.iter),J="";if(J+=` const ${Y} = toArray(${Q});${this.nl()}`,J+=` const ${X} = ${Y}.length;${this.nl()}`,$.else_.length>0)J+=` if (${X} === 0) {${this.nl()}`,J+=this.compileNodes($.else_),J+=` } else {${this.nl()}`;if(J+=` for (let ${Z} = 0; ${Z} < ${X}; ${Z}++) {${this.nl()}`,W)J+=` const ${K} = ${Y}[${Z}][0];${this.nl()}`,J+=` const ${W} = ${Y}[${Z}][1];${this.nl()}`;else J+=` const ${K} = ${Y}[${Z}];${this.nl()}`;if(J+=` const ${G} = {${this.nl()}`,J+=` counter: ${Z} + 1,${this.nl()}`,J+=` counter0: ${Z},${this.nl()}`,J+=` revcounter: ${X} - ${Z},${this.nl()}`,J+=` revcounter0: ${X} - ${Z} - 1,${this.nl()}`,J+=` first: ${Z} === 0,${this.nl()}`,J+=` last: ${Z} === ${X} - 1,${this.nl()}`,J+=` length: ${X},${this.nl()}`,J+=` index: ${Z} + 1,${this.nl()}`,J+=` index0: ${Z},${this.nl()}`,z)J+=` parentloop: ${z},${this.nl()}`,J+=` parent: ${z}${this.nl()}`;else J+=` parentloop: null,${this.nl()}`,J+=` parent: null${this.nl()}`;J+=` };${this.nl()}`,J+=` const forloop = ${G};${this.nl()}`,J+=` const loop = ${G};${this.nl()}`,this.loopStack.push(G);let U=this.compileNodes($.body);if(J+=U.replace(new RegExp(`__ctx\\.${K}`,"g"),K),this.loopStack.pop(),J+=` }${this.nl()}`,$.else_.length>0)J+=` }${this.nl()}`;return J}compileSet($){let Y=this.compileExpr($.value);return` const ${$.target} = ${Y};${this.nl()}`}compileWith($){let Y=` {${this.nl()}`;this.pushScope();for(let{target:Z,value:X}of $.assignments){let G=this.compileExpr(X);Y+=` const ${Z} = ${G};${this.nl()}`,this.addLocalVar(Z)}return Y+=this.compileNodes($.body),Y+=` }${this.nl()}`,this.popScope(),Y}compileExpr($){switch($.type){case"Name":return this.compileName($);case"Literal":return this.compileLiteral($);case"Array":return this.compileArray($);case"Object":return this.compileObject($);case"BinaryOp":return this.compileBinaryOp($);case"UnaryOp":return this.compileUnaryOp($);case"Compare":return this.compileCompare($);case"GetAttr":return this.compileGetAttr($);case"GetItem":return this.compileGetItem($);case"FilterExpr":return this.compileFilter($);case"TestExpr":return this.compileTest($);case"Conditional":return this.compileConditional($);default:return"undefined"}}compileName($){if($.name==="true"||$.name==="True")return"true";if($.name==="false"||$.name==="False")return"false";if($.name==="none"||$.name==="None"||$.name==="null")return"null";if($.name==="forloop"||$.name==="loop")return $.name;if(this.isLocalVar($.name))return $.name;return`__ctx.${$.name}`}compileLiteral($){if(typeof $.value==="string")return JSON.stringify($.value);return String($.value)}compileArray($){return`[${$.elements.map((Z)=>this.compileExpr(Z)).join(", ")}]`}compileObject($){return`{${$.pairs.map(({key:Z,value:X})=>{let G=this.compileExpr(Z),K=this.compileExpr(X);return`[${G}]: ${K}`}).join(", ")}}`}compileBinaryOp($){let Y=this.compileExpr($.left),Z=this.compileExpr($.right);switch($.operator){case"and":return`(${Y} && ${Z})`;case"or":return`(${Y} || ${Z})`;case"~":return`(String(${Y}) + String(${Z}))`;case"in":return`(Array.isArray(${Z}) ? ${Z}.includes(${Y}) : String(${Z}).includes(String(${Y})))`;case"not in":return`!(Array.isArray(${Z}) ? ${Z}.includes(${Y}) : String(${Z}).includes(String(${Y})))`;default:return`(${Y} ${$.operator} ${Z})`}}compileUnaryOp($){let Y=this.compileExpr($.operand);switch($.operator){case"not":return`!isTruthy(${Y})`;case"-":return`-(${Y})`;case"+":return`+(${Y})`;default:return Y}}compileCompare($){let Y=this.compileExpr($.left);for(let{operator:Z,right:X}of $.ops){let G=this.compileExpr(X);switch(Z){case"==":case"===":Y=`(${Y} === ${G})`;break;case"!=":case"!==":Y=`(${Y} !== ${G})`;break;default:Y=`(${Y} ${Z} ${G})`}}return Y}compileGetAttr($){return`${this.compileExpr($.object)}?.${$.attribute}`}compileGetItem($){let Y=this.compileExpr($.object),Z=this.compileExpr($.index);return`${Y}?.[${Z}]`}compileFilter($){let Y=this.compileExpr($.node),Z=$.args.map((X)=>this.compileExpr(X));switch($.filter){case"upper":return`String(${Y}).toUpperCase()`;case"lower":return`String(${Y}).toLowerCase()`;case"title":return`String(${Y}).replace(/\\b\\w/g, c => c.toUpperCase())`;case"trim":return`String(${Y}).trim()`;case"length":return`(${Y}?.length ?? Object.keys(${Y} ?? {}).length)`;case"first":return`(${Y})?.[0]`;case"last":return`(${Y})?.[(${Y})?.length - 1]`;case"default":return`((${Y}) ?? ${Z[0]??'""'})`;case"safe":return`{ __safe: true, value: String(${Y}) }`;case"escape":case"e":return`escape(${Y})`;case"join":return`(${Y} ?? []).join(${Z[0]??'""'})`;case"abs":return`Math.abs(${Y})`;case"round":return Z.length?`Number(${Y}).toFixed(${Z[0]})`:`Math.round(${Y})`;case"int":return`parseInt(${Y}, 10)`;case"float":return`parseFloat(${Y})`;case"floatformat":return`Number(${Y}).toFixed(${Z[0]??1})`;case"filesizeformat":return`applyFilter('filesizeformat', ${Y})`;default:let X=Z.length?", "+Z.join(", "):"";return`applyFilter('${$.filter}', ${Y}${X})`}}compileTest($){let Y=this.compileExpr($.node),Z=$.args.map((G)=>this.compileExpr(G)),X=$.negated?"!":"";switch($.test){case"defined":return`${X}(${Y} !== undefined)`;case"undefined":return`${X}(${Y} === undefined)`;case"none":return`${X}(${Y} === null)`;case"even":return`${X}(${Y} % 2 === 0)`;case"odd":return`${X}(${Y} % 2 !== 0)`;case"divisibleby":return`${X}(${Y} % ${Z[0]} === 0)`;case"empty":return`${X}((${Y} == null) || (${Y}.length === 0) || (Object.keys(${Y}).length === 0))`;case"iterable":return`${X}(Array.isArray(${Y}) || typeof ${Y} === 'string')`;case"number":return`${X}(typeof ${Y} === 'number' && !isNaN(${Y}))`;case"string":return`${X}(typeof ${Y} === 'string')`;default:let G=Z.length?", "+Z.join(", "):"";return`${X}applyTest('${$.test}', ${Y}${G})`}}compileConditional($){let Y=this.compileExpr($.test),Z=this.compileExpr($.trueExpr),X=this.compileExpr($.falseExpr);return`(isTruthy(${Y}) ? ${Z} : ${X})`}isMarkedSafe($){if($.type==="FilterExpr")return $.filter==="safe";return!1}genVar($){return`__${$}${this.varCounter++}`}nl(){return this.options.minify?"":`
153
+ `}}function bY($,Y){return new fY(Y).flatten($)}function Y6($){return new yY().check($)}class fY{loader;maxDepth;blocks=new Map;depth=0;constructor($){this.loader=$.loader,this.maxDepth=$.maxDepth??10}flatten($){return this.blocks.clear(),this.depth=0,this.processTemplate($)}processTemplate($,Y=!0){if(this.depth>this.maxDepth)throw Error(`Maximum template inheritance depth (${this.maxDepth}) exceeded`);this.collectBlocks($.body,Y);let Z=this.findExtends($.body);if(Z){let X=this.getStaticTemplateName(Z.template),G=this.loader.load(X),K=this.loader.parse(G);this.depth++;let W=this.processTemplate(K,!1);return this.depth--,{type:"Template",body:this.replaceBlocks(W.body),line:$.line,column:$.column}}return{type:"Template",body:this.processNodes($.body),line:$.line,column:$.column}}collectBlocks($,Y=!0){for(let Z of $){if(Z.type==="Block"){let X=Z;if(Y||!this.blocks.has(X.name))this.blocks.set(X.name,X)}this.collectBlocksFromNode(Z,Y)}}collectBlocksFromNode($,Y=!0){switch($.type){case"If":{let Z=$;this.collectBlocks(Z.body,Y);for(let X of Z.elifs)this.collectBlocks(X.body,Y);this.collectBlocks(Z.else_,Y);break}case"For":{let Z=$;this.collectBlocks(Z.body,Y),this.collectBlocks(Z.else_,Y);break}case"With":{let Z=$;this.collectBlocks(Z.body,Y);break}case"Block":{let Z=$;this.collectBlocks(Z.body,Y);break}}}findExtends($){for(let Y of $)if(Y.type==="Extends")return Y;return null}processNodes($){let Y=[];for(let Z of $){if(Z.type==="Extends")continue;if(Z.type==="Include"){let G=Z,K=this.inlineInclude(G);Y.push(...K);continue}if(Z.type==="Block"){let G=Z,K=this.blocks.get(G.name);if(K&&K!==G)Y.push(...this.processNodes(K.body));else Y.push(...this.processNodes(G.body));continue}let X=this.processNode(Z);if(X)Y.push(X)}return Y}processNode($){switch($.type){case"If":{let Y=$;return{...Y,body:this.processNodes(Y.body),elifs:Y.elifs.map((Z)=>({test:Z.test,body:this.processNodes(Z.body)})),else_:this.processNodes(Y.else_)}}case"For":{let Y=$;return{...Y,body:this.processNodes(Y.body),else_:this.processNodes(Y.else_)}}case"With":{let Y=$;return{...Y,body:this.processNodes(Y.body)}}default:return $}}replaceBlocks($){return this.processNodes($)}inlineInclude($){let Y=this.getStaticTemplateName($.template);try{let Z=this.loader.load(Y),X=this.loader.parse(Z);this.depth++;let G=this.processTemplate(X);if(this.depth--,$.context&&Object.keys($.context).length>0)return[{type:"With",assignments:Object.entries($.context).map(([W,z])=>({target:W,value:z})),body:G.body,line:$.line,column:$.column}];return G.body}catch(Z){if($.ignoreMissing)return[];throw Z}}getStaticTemplateName($){if($.type==="Literal"){let Y=$;if(typeof Y.value==="string")return Y.value}throw Error(`AOT compilation requires static template names. Found dynamic expression at line ${$.line}. Use Environment.render() for dynamic template names.`)}}class yY{check($){return this.checkNodes($.body)}checkNodes($){for(let Y of $){let Z=this.checkNode(Y);if(!Z.canFlatten)return Z}return{canFlatten:!0}}checkNode($){switch($.type){case"Extends":{let Y=$;if(!this.isStaticName(Y.template))return{canFlatten:!1,reason:`Dynamic extends at line ${$.line} - use static string literal`};break}case"Include":{let Y=$;if(!this.isStaticName(Y.template))return{canFlatten:!1,reason:`Dynamic include at line ${$.line} - use static string literal`};break}case"If":{let Y=$,Z=this.checkNodes(Y.body);if(!Z.canFlatten)return Z;for(let X of Y.elifs)if(Z=this.checkNodes(X.body),!Z.canFlatten)return Z;if(Z=this.checkNodes(Y.else_),!Z.canFlatten)return Z;break}case"For":{let Y=$,Z=this.checkNodes(Y.body);if(!Z.canFlatten)return Z;if(Z=this.checkNodes(Y.else_),!Z.canFlatten)return Z;break}case"With":{let Y=$,Z=this.checkNodes(Y.body);if(!Z.canFlatten)return Z;break}case"Block":{let Y=$,Z=this.checkNodes(Y.body);if(!Z.canFlatten)return Z;break}}return{canFlatten:!0}}isStaticName($){return $.type==="Literal"&&typeof $.value==="string"}}var w7="0.9.0",w={reset:"\x1B[0m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",dim:"\x1B[2m"};function u($){console.log($)}function g1($){console.log(`${w.green}\u2713${w.reset} ${$}`)}function X2($){console.log(`${w.yellow}\u26A0${w.reset} ${$}`)}function Y0($){console.error(`${w.red}\u2717${w.reset} ${$}`)}function AY(){console.log(`
154
+ ${w.cyan}binja${w.reset} - High-performance template compiler
155
+
156
+ ${w.yellow}Usage:${w.reset}
18
157
  binja compile <source> [options] Compile templates to JavaScript
19
158
  binja check <source> Check if templates can be AOT compiled
159
+ binja lint <source> [options] Lint templates for issues
20
160
  binja --help Show this help
21
161
  binja --version Show version
22
162
 
23
- ${J.yellow}Compile Options:${J.reset}
163
+ ${w.yellow}Compile Options:${w.reset}
24
164
  -o, --output <dir> Output directory (required)
25
165
  -n, --name <name> Function name for single file compilation
26
166
  -m, --minify Minify output
@@ -28,29 +168,44 @@ ${J.yellow}Compile Options:${J.reset}
28
168
  -v, --verbose Verbose output
29
169
  -w, --watch Watch for changes and recompile
30
170
 
31
- ${J.yellow}Examples:${J.reset}
32
- ${J.dim}# Compile all templates in a directory${J.reset}
171
+ ${w.yellow}Lint Options:${w.reset}
172
+ --ai Enable AI-powered analysis (requires API key)
173
+ --ai=<provider> Use specific AI provider (anthropic, openai, groq, ollama)
174
+ --format=<format> Output format: text (default), json
175
+ -e, --ext <extensions> File extensions to lint
176
+
177
+ ${w.yellow}Examples:${w.reset}
178
+ ${w.dim}# Compile all templates in a directory${w.reset}
33
179
  binja compile ./templates -o ./dist/templates
34
180
 
35
- ${J.dim}# Compile with minification${J.reset}
181
+ ${w.dim}# Compile with minification${w.reset}
36
182
  binja compile ./views -o ./compiled --minify
37
183
 
38
- ${J.dim}# Compile single file with custom function name${J.reset}
184
+ ${w.dim}# Compile single file with custom function name${w.reset}
39
185
  binja compile ./templates/home.html -o ./dist --name renderHome
40
186
 
41
- ${J.dim}# Watch mode for development${J.reset}
187
+ ${w.dim}# Watch mode for development${w.reset}
42
188
  binja compile ./templates -o ./dist --watch
43
189
 
44
- ${J.yellow}Output:${J.reset}
190
+ ${w.dim}# Lint templates (syntax only)${w.reset}
191
+ binja lint ./templates
192
+
193
+ ${w.dim}# Lint with AI analysis${w.reset}
194
+ binja lint ./templates --ai
195
+
196
+ ${w.dim}# Lint with specific AI provider${w.reset}
197
+ binja lint ./templates --ai=ollama
198
+
199
+ ${w.yellow}Output:${w.reset}
45
200
  Generated files export a render function:
46
201
 
47
- ${J.dim}// dist/templates/home.js${J.reset}
202
+ ${w.dim}// dist/templates/home.js${w.reset}
48
203
  export function render(ctx) { ... }
49
204
 
50
- ${J.dim}// Usage${J.reset}
205
+ ${w.dim}// Usage${w.reset}
51
206
  import { render } from './dist/templates/home.js'
52
207
  const html = render({ title: 'Hello' })
53
- `)}function u(A){let B={output:"",minify:!1,watch:!1,extensions:[".html",".jinja",".jinja2"],verbose:!1},R="",O="";for(let K=0;K<A.length;K++){let Q=A[K];if(Q==="compile"||Q==="check"||Q==="watch"){if(R=Q,Q==="watch")B.watch=!0,R="compile"}else if(Q==="-o"||Q==="--output")B.output=A[++K];else if(Q==="-n"||Q==="--name")B.name=A[++K];else if(Q==="-m"||Q==="--minify")B.minify=!0;else if(Q==="-w"||Q==="--watch")B.watch=!0;else if(Q==="-v"||Q==="--verbose")B.verbose=!0;else if(Q==="-e"||Q==="--ext")B.extensions=A[++K].split(",").map((M)=>M.startsWith(".")?M:`.${M}`);else if(Q==="--help"||Q==="-h")w(),process.exit(0);else if(Q==="--version"||Q==="-V")console.log(`binja v${i}`),process.exit(0);else if(!Q.startsWith("-")&&!O)O=Q}return{command:R,source:O,options:B}}function V(A,B){return{load(R){let O=Y.resolve(A,R);for(let K of[...B,""]){let Q=O+K;if(X.existsSync(Q))return X.readFileSync(Q,"utf-8")}throw Error(`Template not found: ${R}`)},parse(R){let K=new D(R).tokenize();return new S(K).parse()}}}function s(A,B){return`// Generated by binja - DO NOT EDIT
208
+ `)}function L7($){let Y={output:"",minify:!1,watch:!1,extensions:[".html",".jinja",".jinja2"],verbose:!1},Z={ai:!1,format:"text",extensions:[".html",".jinja",".jinja2"]},X="",G="";for(let K=0;K<$.length;K++){let W=$[K];if(W==="compile"||W==="check"||W==="watch"||W==="lint"){if(X=W,W==="watch")Y.watch=!0,X="compile"}else if(W==="-o"||W==="--output")Y.output=$[++K];else if(W==="-n"||W==="--name")Y.name=$[++K];else if(W==="-m"||W==="--minify")Y.minify=!0;else if(W==="-w"||W==="--watch")Y.watch=!0;else if(W==="-v"||W==="--verbose")Y.verbose=!0;else if(W==="-e"||W==="--ext"){let z=$[++K].split(",").map((Q)=>Q.startsWith(".")?Q:`.${Q}`);Y.extensions=z,Z.extensions=z}else if(W==="--ai")Z.ai=!0;else if(W.startsWith("--ai="))Z.ai=!0,Z.aiProvider=W.split("=")[1];else if(W.startsWith("--format="))Z.format=W.split("=")[1];else if(W==="--help"||W==="-h")AY(),process.exit(0);else if(W==="--version"||W==="-V")console.log(`binja v${w7}`),process.exit(0);else if(!W.startsWith("-")&&!G)G=W}return{command:X,source:G,compileOptions:Y,lintOptions:Z}}function xY($,Y){return{load(Z){let X=I.resolve($,Z);for(let G of[...Y,""]){let K=X+G;if(g.existsSync(K))return g.readFileSync(K,"utf-8")}throw Error(`Template not found: ${Z}`)},parse(Z){let G=new Q1(Z).tokenize();return new J1(G).parse()}}}function O7($,Y){return`// Generated by binja - DO NOT EDIT
54
209
  // Source: binja compile
55
210
 
56
211
  const escape = (v) => {
@@ -90,9 +245,9 @@ const applyTest = (name, value, ...args) => {
90
245
  throw new Error(\`Test '\${name}' not available in compiled template.\`);
91
246
  };
92
247
 
93
- ${A}
248
+ ${$}
94
249
 
95
- export { ${B} as render };
96
- export default ${B};
97
- `}async function b(A,B,R,O){try{let K=X.readFileSync(A,"utf-8"),Q=V(R,O.extensions),M=Q.parse(K),$=N(M),Z=M;if(!$.canFlatten){if(O.verbose)_(`${Y.basename(A)}: ${$.reason} - compiling without inheritance resolution`)}else Z=k(M,{loader:Q});let U=Y.relative(R,A),G=O.name||"render"+U.replace(/\.[^.]+$/,"").replace(/[^a-zA-Z0-9]/g,"_").replace(/^_+|_+$/g,"").replace(/_([a-z])/g,(o,c)=>c.toUpperCase()),W=f(Z,{functionName:G,minify:O.minify}),H=U.replace(/\.[^.]+$/,".js"),z=Y.join(B,H),C=Y.dirname(z);if(!X.existsSync(C))X.mkdirSync(C,{recursive:!0});let j=s(W,G);return X.writeFileSync(z,j),{success:!0,outputPath:z}}catch(K){return{success:!1,error:K.message}}}async function T(A,B,R){let O=0,K=0,Q=[];function M($){let Z=X.readdirSync($,{withFileTypes:!0});for(let U of Z){let G=Y.join($,U.name);if(U.isDirectory())M(G);else if(U.isFile()){let W=Y.extname(U.name);if(R.extensions.includes(W))Q.push(G)}}}M(A);for(let $ of Q){let Z=await b($,B,A,R);if(Z.success){if(O++,R.verbose)L(`${Y.relative(A,$)} \u2192 ${Y.relative(process.cwd(),Z.outputPath)}`)}else K++,F(`${Y.relative(A,$)}: ${Z.error}`)}return{compiled:O,failed:K}}async function r(A,B){let R=V(A,B.extensions),O=0,K=0,Q=0;function M($){let Z=X.readdirSync($,{withFileTypes:!0});for(let U of Z){let G=Y.join($,U.name);if(U.isDirectory())M(G);else if(U.isFile()){let W=Y.extname(U.name);if(B.extensions.includes(W)){O++;try{let H=X.readFileSync(G,"utf-8"),z=R.parse(H),C=N(z),j=Y.relative(A,G);if(C.canFlatten)K++,L(`${j}`);else Q++,_(`${j}: ${C.reason}`)}catch(H){Q++,F(`${Y.relative(A,G)}: ${H.message}`)}}}}}if(M(A),E(""),E(`Total: ${O} templates`),E(`${J.green}AOT compatible: ${K}${J.reset}`),Q>0)E(`${J.yellow}Require runtime: ${Q}${J.reset}`)}async function l(A,B,R){E(`${J.cyan}Watching${J.reset} ${A} for changes...`),E(`${J.dim}Press Ctrl+C to stop${J.reset}`),E("");let{compiled:O,failed:K}=await T(A,B,{...R,verbose:!0});E(""),E(`Compiled ${O} templates${K>0?`, ${K} failed`:""}`),E("");let Q=X.watch(A,{recursive:!0},async(M,$)=>{if(!$)return;let Z=Y.extname($);if(!R.extensions.includes(Z))return;let U=Y.join(A,$);if(!X.existsSync(U))return;E(`${J.dim}[${new Date().toLocaleTimeString()}]${J.reset} ${$} changed`);let G=await b(U,B,A,R);if(G.success)L(`Compiled ${$}`);else F(`${$}: ${G.error}`)});process.on("SIGINT",()=>{Q.close(),E(`
98
- Stopped watching.`),process.exit(0)})}async function n(){let A=process.argv.slice(2);if(A.length===0)w(),process.exit(0);let{command:B,source:R,options:O}=u(A);if(!B)F('No command specified. Use "compile" or "check".'),w(),process.exit(1);if(!R)F("No source path specified."),process.exit(1);let K=Y.resolve(R);if(!X.existsSync(K))F(`Source not found: ${R}`),process.exit(1);let Q=X.statSync(K).isDirectory();if(B==="check")if(Q)await r(K,O);else{let M=V(Y.dirname(K),O.extensions),$=X.readFileSync(K,"utf-8"),Z=M.parse($),U=N(Z);if(U.canFlatten)L(`${R} can be AOT compiled`);else _(`${R}: ${U.reason}`)}else if(B==="compile"){if(!O.output)F("Output directory required. Use -o <dir>"),process.exit(1);let M=Y.resolve(O.output);if(O.watch){if(!Q)F("Watch mode requires a directory, not a single file."),process.exit(1);await l(K,M,O)}else if(Q){let $=Date.now(),{compiled:Z,failed:U}=await T(K,M,O),G=Date.now()-$;if(E(""),U===0)L(`Compiled ${Z} templates in ${G}ms`);else _(`Compiled ${Z} templates, ${U} failed (${G}ms)`)}else{let $=await b(K,M,Y.dirname(K),O);if($.success)L(`Compiled to ${$.outputPath}`);else F($.error),process.exit(1)}}}n().catch((A)=>{F(A.message),process.exit(1)});
250
+ export { ${Y} as render };
251
+ export default ${Y};
252
+ `}async function PY($,Y,Z,X){try{let G=g.readFileSync($,"utf-8"),K=xY(Z,X.extensions),W=K.parse(G),z=Y6(W),Q=W;if(!z.canFlatten){if(X.verbose)X2(`${I.basename($)}: ${z.reason} - compiling without inheritance resolution`)}else Q=bY(W,{loader:K});let J=I.relative(Z,$),U=X.name||"render"+J.replace(/\.[^.]+$/,"").replace(/[^a-zA-Z0-9]/g,"_").replace(/^_+|_+$/g,"").replace(/_([a-z])/g,(f,y)=>y.toUpperCase()),N=IY(Q,{functionName:U,minify:X.minify}),D=J.replace(/\.[^.]+$/,".js"),O=I.join(Y,D),V=I.dirname(O);if(!g.existsSync(V))g.mkdirSync(V,{recursive:!0});let R=O7(N,U);return g.writeFileSync(O,R),{success:!0,outputPath:O}}catch(G){return{success:!1,error:G.message}}}async function lZ($,Y,Z){let X=0,G=0,K=[];function W(z){let Q=g.readdirSync(z,{withFileTypes:!0});for(let J of Q){let U=I.join(z,J.name);if(J.isDirectory())W(U);else if(J.isFile()){let N=I.extname(J.name);if(Z.extensions.includes(N))K.push(U)}}}W($);for(let z of K){let Q=await PY(z,Y,$,Z);if(Q.success){if(X++,Z.verbose)g1(`${I.relative($,z)} \u2192 ${I.relative(process.cwd(),Q.outputPath)}`)}else G++,Y0(`${I.relative($,z)}: ${Q.error}`)}return{compiled:X,failed:G}}async function M7($,Y){let Z=xY($,Y.extensions),X=0,G=0,K=0;function W(z){let Q=g.readdirSync(z,{withFileTypes:!0});for(let J of Q){let U=I.join(z,J.name);if(J.isDirectory())W(U);else if(J.isFile()){let N=I.extname(J.name);if(Y.extensions.includes(N)){X++;try{let D=g.readFileSync(U,"utf-8"),O=Z.parse(D),V=Y6(O),R=I.relative($,U);if(V.canFlatten)G++,g1(`${R}`);else K++,X2(`${R}: ${V.reason}`)}catch(D){K++,Y0(`${I.relative($,U)}: ${D.message}`)}}}}}if(W($),u(""),u(`Total: ${X} templates`),u(`${w.green}AOT compatible: ${G}${w.reset}`),K>0)u(`${w.yellow}Require runtime: ${K}${w.reset}`)}async function E7($,Y,Z){u(`${w.cyan}Watching${w.reset} ${$} for changes...`),u(`${w.dim}Press Ctrl+C to stop${w.reset}`),u("");let{compiled:X,failed:G}=await lZ($,Y,{...Z,verbose:!0});u(""),u(`Compiled ${X} templates${G>0?`, ${G} failed`:""}`),u("");let K=g.watch($,{recursive:!0},async(W,z)=>{if(!z)return;let Q=I.extname(z);if(!Z.extensions.includes(Q))return;let J=I.join($,z);if(!g.existsSync(J))return;u(`${w.dim}[${new Date().toLocaleTimeString()}]${w.reset} ${z} changed`);let U=await PY(J,Y,$,Z);if(U.success)g1(`Compiled ${z}`);else Y0(`${z}: ${U.error}`)});process.on("SIGINT",()=>{K.close(),u(`
253
+ Stopped watching.`),process.exit(0)})}async function q7($,Y,Z){let X,G;if(Z.ai)try{let U=await Promise.resolve().then(() => (pZ(),uZ));X=U.lint,G=U.syntaxCheck}catch(U){Y0("AI lint requires the AI module."),Y0("Make sure you have an AI provider configured:"),Y0(" - ANTHROPIC_API_KEY + bun add @anthropic-ai/sdk"),Y0(" - OPENAI_API_KEY + bun add openai"),Y0(" - GROQ_API_KEY"),Y0(" - Ollama running locally"),process.exit(1)}else G=(U)=>{try{let D=new Q1(U).tokenize();return new J1(D,U).parse(),{valid:!0,errors:[],warnings:[],suggestions:[]}}catch(N){return{valid:!1,errors:[{line:N.line||1,type:"syntax",severity:"error",message:N.message}],warnings:[],suggestions:[]}}},X=async(U)=>G(U);let K=[];if(Y){let U=function(N){let D=g.readdirSync(N,{withFileTypes:!0});for(let O of D){let V=I.join(N,O.name);if(O.isDirectory())U(V);else if(O.isFile()){let R=I.extname(O.name);if(Z.extensions.includes(R))K.push(V)}}};U($)}else K.push($);let W=0,z=0,Q=0,J=[];for(let U of K){let N=g.readFileSync(U,"utf-8"),D=await X(N,{provider:Z.aiProvider||"auto"});J.push({file:U,result:D}),W+=D.errors.length,z+=D.warnings.length,Q+=D.suggestions.length}if(Z.format==="json")console.log(JSON.stringify(J,null,2));else{for(let{file:U,result:N}of J){let D=I.relative(process.cwd(),U),O=[...N.errors,...N.warnings,...N.suggestions];if(O.length===0)continue;u(""),u(` ${w.cyan}${D}${w.reset}`),u("");for(let V of O){let R=V.severity==="error"?w.red+"\u2717":V.severity==="warning"?w.yellow+"\u26A0":w.dim+"\uD83D\uDCA1",f=V.type==="security"?w.red:V.type==="performance"?w.yellow:w.dim;if(u(` ${R}${w.reset} L${V.line.toString().padEnd(4)} ${f}${V.type.padEnd(14)}${w.reset} ${V.message}`),V.suggestion)u(` ${w.dim}\u2192 ${V.suggestion}${w.reset}`)}}if(u(""),W===0&&z===0&&Q===0)g1(`${K.length} template(s) checked, no issues found`);else{let U=[];if(W>0)U.push(`${w.red}${W} error(s)${w.reset}`);if(z>0)U.push(`${w.yellow}${z} warning(s)${w.reset}`);if(Q>0)U.push(`${Q} suggestion(s)`);if(u(` ${K.length} template(s): ${U.join(", ")}`),J[0]?.result.provider)u(` ${w.dim}AI provider: ${J[0].result.provider}${w.reset}`)}}if(W>0)process.exit(1)}async function C7(){let $=process.argv.slice(2);if($.length===0)AY(),process.exit(0);let{command:Y,source:Z,compileOptions:X,lintOptions:G}=L7($);if(!Y)Y0('No command specified. Use "compile", "check", or "lint".'),AY(),process.exit(1);if(!Z)Y0("No source path specified."),process.exit(1);let K=I.resolve(Z);if(!g.existsSync(K))Y0(`Source not found: ${Z}`),process.exit(1);let W=g.statSync(K).isDirectory();if(Y==="lint")await q7(K,W,G);else if(Y==="check")if(W)await M7(K,X);else{let z=xY(I.dirname(K),X.extensions),Q=g.readFileSync(K,"utf-8"),J=z.parse(Q),U=Y6(J);if(U.canFlatten)g1(`${Z} can be AOT compiled`);else X2(`${Z}: ${U.reason}`)}else if(Y==="compile"){if(!X.output)Y0("Output directory required. Use -o <dir>"),process.exit(1);let z=I.resolve(X.output);if(X.watch){if(!W)Y0("Watch mode requires a directory, not a single file."),process.exit(1);await E7(K,z,X)}else if(W){let Q=Date.now(),{compiled:J,failed:U}=await lZ(K,z,X),N=Date.now()-Q;if(u(""),U===0)g1(`Compiled ${J} templates in ${N}ms`);else X2(`Compiled ${J} templates, ${U} failed (${N}ms)`)}else{let Q=await PY(K,z,I.dirname(K),X);if(Q.success)g1(`Compiled to ${Q.outputPath}`);else Y0(Q.error),process.exit(1)}}}C7().catch(($)=>{Y0($.message),process.exit(1)});