@isdk/ai-tool 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/chunk-PYM7DCYB.mjs +1 -0
  2. package/dist/chunk-U5DDQYSF.mjs +1 -22
  3. package/dist/funcs.d.mts +2 -2
  4. package/dist/funcs.d.ts +2 -2
  5. package/dist/funcs.js +1 -5020
  6. package/dist/funcs.mjs +1 -37
  7. package/dist/{index-D4KjfAKl.d.mts → index-japi6bEq.d.mts} +2 -13
  8. package/dist/{index-D4KjfAKl.d.ts → index-japi6bEq.d.ts} +2 -13
  9. package/dist/index.d.mts +13 -6
  10. package/dist/index.d.ts +13 -6
  11. package/dist/index.js +1 -5245
  12. package/dist/index.mjs +1 -402
  13. package/dist/test/util.js +1 -97
  14. package/dist/test/util.mjs +1 -60
  15. package/docs/classes/AbortError.md +8 -8
  16. package/docs/classes/AlreadyExistsError.md +8 -8
  17. package/docs/classes/BaseError.md +8 -8
  18. package/docs/classes/ClientTools.md +51 -51
  19. package/docs/classes/CommonError.md +8 -8
  20. package/docs/classes/EventClient.md +73 -73
  21. package/docs/classes/EventServer.md +71 -71
  22. package/docs/classes/EventToolFunc.md +41 -41
  23. package/docs/classes/FStringPromptTemplate.md +18 -18
  24. package/docs/classes/FewShotPromptTemplate.md +22 -22
  25. package/docs/classes/GolangPromptTemplate.md +18 -18
  26. package/docs/classes/HFEnvironment.md +9 -9
  27. package/docs/classes/HFInterpreter.md +17 -17
  28. package/docs/classes/HFTemplate.md +4 -4
  29. package/docs/classes/HfPromptTemplate.md +18 -18
  30. package/docs/classes/NotFoundError.md +8 -8
  31. package/docs/classes/NotImplementationError.md +8 -8
  32. package/docs/classes/PromptExampleSelector.md +8 -8
  33. package/docs/classes/PromptTemplate.md +17 -17
  34. package/docs/classes/ReadableStreamError.md +8 -8
  35. package/docs/classes/ResClientTools.md +57 -57
  36. package/docs/classes/ResServerTools.md +55 -55
  37. package/docs/classes/SSEChannel.md +15 -15
  38. package/docs/classes/ServerTools.md +48 -48
  39. package/docs/classes/ToolFunc.md +38 -38
  40. package/docs/enums/ErrorCode.md +19 -19
  41. package/docs/enums/XXHashAlgorithm.md +2 -2
  42. package/docs/interfaces/AIChatAssistantMessageParam.md +6 -6
  43. package/docs/interfaces/AIChatContentPartImage.md +2 -2
  44. package/docs/interfaces/AIChatContentPartText.md +2 -2
  45. package/docs/interfaces/AIChatMessageParamBase.md +1 -1
  46. package/docs/interfaces/AIChatMessageToolCall.md +3 -3
  47. package/docs/interfaces/AIChatSystemMessageParam.md +3 -3
  48. package/docs/interfaces/AIChatToolMessageParam.md +4 -4
  49. package/docs/interfaces/AIChatUserMessageParam.md +7 -7
  50. package/docs/interfaces/AIResult.md +4 -4
  51. package/docs/interfaces/AIStreamCallbacksAndOptions.md +6 -6
  52. package/docs/interfaces/AIStreamParser.md +1 -1
  53. package/docs/interfaces/AIStreamParserOptions.md +1 -1
  54. package/docs/interfaces/BaseFunc.md +7 -7
  55. package/docs/interfaces/BaseFuncItem.md +6 -6
  56. package/docs/interfaces/ClientFuncItem.md +10 -10
  57. package/docs/interfaces/DotenvExpandOptions.md +3 -3
  58. package/docs/interfaces/DotenvExpandOutput.md +2 -2
  59. package/docs/interfaces/EventClientFuncParams.md +4 -4
  60. package/docs/interfaces/EventServerFuncParams.md +5 -5
  61. package/docs/interfaces/FewShotPromptTemplateOptions.md +11 -11
  62. package/docs/interfaces/FuncItem.md +7 -7
  63. package/docs/interfaces/FuncParam.md +5 -5
  64. package/docs/interfaces/PromptExampleSelectorOptions.md +2 -2
  65. package/docs/interfaces/PromptTemplateOptions.md +6 -6
  66. package/docs/interfaces/RemoteFuncItem.md +10 -10
  67. package/docs/interfaces/ResClientFuncParams.md +2 -2
  68. package/docs/interfaces/ResServerFuncParams.md +5 -5
  69. package/docs/interfaces/SanitizeFilenameOptions.md +2 -2
  70. package/docs/interfaces/ServerFuncItem.md +11 -11
  71. package/docs/interfaces/ServerFuncParams.md +2 -2
  72. package/docs/modules.md +109 -182
  73. package/package.json +3 -5
  74. package/dist/chunk-6AXCY6TJ.mjs +0 -5090
@@ -0,0 +1 @@
1
+ import{__export as t,__reExport as e}from"./chunk-U5DDQYSF.mjs";import{EventEmitter as n}from"events-ex";import{AdvancePropertyManager as r}from"property-manager";import{_createFunction as s}from"util-ex";import{AbstractError as i,createErrorClass as o}from"abstract-error";var a=(t=>(t[t.OK=200]="OK",t[t.BadRequest=400]="BadRequest",t[t.InvalidArgument=400]="InvalidArgument",t[t.Unauthorized=401]="Unauthorized",t[t.PaymentRequired=402]="PaymentRequired",t[t.Forbidden=403]="Forbidden",t[t.NotFound=404]="NotFound",t[t.MethodNotAllowed=405]="MethodNotAllowed",t[t.NotAcceptable=406]="NotAcceptable",t[t.RequestTimeout=408]="RequestTimeout",t[t.Conflict=409]="Conflict",t[t.Corruption=409]="Corruption",t[t.Aborted=499]="Aborted",t[t.InternalError=500]="InternalError",t[t.NotImplemented=501]="NotImplemented",t[t.NotSupported=501]="NotSupported",t[t.BadGateway=502]="BadGateway",t[t.ServiceUnavailable=503]="ServiceUnavailable",t[t.GatewayTimeout=504]="GatewayTimeout",t))(a||{}),c=500,u=501,l=404,f=409,h=499,p=class t extends i{static createErrorClass(e,n,r=t){return o(e,n,r)}constructor(t,e,n){super(t,e);const r=this.constructor;null!=e?this.code=e:r.code?this.code=r.code:this.code=r.name,n?"string"==typeof n?this.name=n:Object.assign(this,n):"string"==typeof this.code?this.name=this.code:this.name=r.name}toJSON(){const t={name:this.name,code:this.code,data:this.data,caller:this.caller,error:this.message,stack:this.stack};return Object.keys(t).forEach((e=>void 0===t[e]&&delete t[e])),t}fromJSON(e){const n=new t(e.message);return n.code=e.code,n.data=e.data,n.caller=e.caller,n.message=e.error,n.stack=e.stack,n}},w=class extends p{constructor(t,e,n=c){super(t,n,e)}},d=class extends w{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};w[501]=d;var m=class extends w{static{this.code=l}constructor(t,e){super(`Could not find ${t}.`,e,l),this.data={what:t}}};w[404]=m;var y=class extends w{static{this.code=f}constructor(t,e){super(`The ${t} already exists.`,e,f),this.data={what:t}}};w[409]=y;var g=class extends w{static{this.code=h}constructor(t,e){super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,h),t&&(this.data={what:t})}};function b(t,e,n=c){const r=new(w[n]||w)(t,e,n);return"number"!=typeof r.code&&(r.code=n),r}function x(t,e,n=c){throw b(t,e,n)}w[499]=g;var E=class t extends r{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const r=this.get(n);let s=r.tags;if("string"==typeof s){if(s===t){e=r;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=r;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const r=this.get(n);let s=r.tags;"string"==typeof s?s===t&&e.push(r):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(r)}return e}static async run(t,e){const n=this.get(t);if(n)return await n.run(e);throw new m(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new m(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static async runWithPos(t,...e){const n=this.get(t);if(n)return await n.runWithPos(...e);throw new m(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new m(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let r=!!this.get(e);if(r)r=!1;else{if(!(n instanceof t))return r=new this(n),r.register();this.items[e]=n,r=n}return r}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,n=this.depends;if(n){const e=Object.keys(n);for(const r of e){const e=n[r];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},n=Object.keys(this.params);let r=Math.min(n.length,t.length);for(let s=0;s<r;s++)e[n[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let r=Math.min(n.length,this.params.length);for(let s=0;s<r;s++)e.push(t[n[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);x("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}async run(t){return await this.runSync(t)}async runAs(t,e){return await this.constructor.run(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}async runWithPos(...t){return await this.runWithPosSync(...t)}async runWithPosAs(t,...e){return await this.constructor.runWithPos(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}},v={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,n,r,i){let o=t;const a=typeof t;return i.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=s(t,e.scope)),o}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]}};E.defineProperties(E,v);import{createAbilityInjector as $}from"custom-ability";var S="event",k="event-bus";var O=$((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(k)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}}),!0);function C(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var A=498,j=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let n,r;this.active||x("Channel closed","SSEChannel",A);let s=e;if(t||e)r=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",n="id: "+r+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:r,_eventName:s,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!s||C(t.events,s))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return r}subscribe(t,e,n){this.active||x("Channel closed","SSEChannel",A);const r={req:t,res:e,events:n},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),r.req.socket.setNoDelay(!0),r.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>C(r.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),r.res.write(a),this.clients.add(r),s>0&&setTimeout((()=>{r.res.writableEnded||this.unsubscribe(r)}),s),r.res.on("close",(()=>this.unsubscribe(r))),r}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++})),t}getSubscriberCount(){return this.clients.size}},N=class extends E{constructor(){super(...arguments),this._emitter=new n,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},T=new N(k);import{Cache as F}from"secondary-cache";function I({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function R(t,e){let n=E.get(t);return n||(n=new E(t,{func:I,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),n.cache=new F(e)),n}var P=R("lrucache"),V={};t(V,{AIChatRoles:()=>q,AIMessageTypes:()=>_,AIStream:()=>Ie,AITextGenerationFinishReasons:()=>L,AbortError:()=>g,AbortErrorCode:()=>h,ActionNames:()=>B,AlreadyExistsError:()=>y,AlreadyExistsErrorCode:()=>f,BaseError:()=>p,CommonError:()=>w,ConfigFile:()=>Wn,ErrorCode:()=>a,EventBusName:()=>k,EventName:()=>S,FStringPromptTemplate:()=>re,FewShotPromptTemplate:()=>ce,FilenameReservedRegex:()=>hn,GolangPromptTemplate:()=>oe,HFBuiltins:()=>Wt,HFEnvironment:()=>Ht,HFInterpreter:()=>qt,HFTemplate:()=>Gt,HfPromptTemplate:()=>Zt,InternalErrorCode:()=>c,NotFoundError:()=>m,NotFoundErrorCode:()=>l,NotImplementationError:()=>d,NotImplementedErrorCode:()=>501,PASSING_SCORE:()=>U,PromptExampleSelector:()=>X,PromptTemplate:()=>H,PromptTemplateTypes:()=>z,PromptTypes:()=>J,RStreamErrCode:()=>Se,ReadableStreamError:()=>Oe,RemoteToolFuncSchema:()=>M,ResponseRStreamErrCode:()=>ke,SSEChannel:()=>j,SSEChannelAlreadyClosedErrCode:()=>A,WindowsReservedNameRegex:()=>pn,XXHashAlgorithm:()=>cn,backendEventable:()=>O,base32768:()=>en,createCallbacksTransformer:()=>Te,createEmptyReadableStream:()=>Ae,createEndWithRepetitionDetector:()=>Rn,createError:()=>b,createEventStreamTransformer:()=>Ne,createHfValueFunc:()=>Qt,defaultTemplateFormat:()=>W,expandEnv:()=>he,expandObjEnv:()=>pe,extNameLevel:()=>kn,filenameReservedRegex:()=>gn,getAllEnumKeys:()=>jn,getConfigFileNames:()=>er,getConfigs:()=>nr,getKeysPath:()=>Fn,getMultiLevelExtname:()=>Sn,getResponseErrorReadableStream:()=>Ce,hfParse:()=>Ct,hfTokenize:()=>st,interpolateEnv:()=>fe,interpolateFString:()=>ee,interpolateGolangTemplate:()=>ie,isModelNameMatched:()=>An,isValidFilename:()=>xn,isValidFilepath:()=>En,jsonFilterToWhere:()=>cr,loadFileFromPaths:()=>Un,loadTextFromPaths:()=>Mn,matchUrlProtocol:()=>ur,mimeType:()=>Xn,parseFString:()=>te,parseJsJson:()=>Tn,parseYaml:()=>tr,reControlCharsRegex:()=>bn,readableFromAsyncIterable:()=>Re,registerYamlTag:()=>Qn,sanitizeFilename:()=>vn,sanitizeFilepath:()=>$n,saveConfigFile:()=>rr,sortedValues:()=>ae,splitSentence:()=>Ee,stringifyYaml:()=>Yn,throwError:()=>x,trimStartOfStreamHelper:()=>Fe,truncTo:()=>ve,uuid:()=>Ke,uuidNIL:()=>He,uuidParse:()=>ze,uuidStringify:()=>Je,uuidValidate:()=>De,uuidVersion:()=>We,uuidv1:()=>Le,uuidv4:()=>_e,uuidv5:()=>qe,wait:()=>$e,xxhash:()=>un,xxhash32:()=>on,xxhash64:()=>an,xxhashAsStr:()=>ln});var U=.618,B=["get","post","put","delete","patch","list","res"],M={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,r,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"},stream:{type:"boolean"}},L=["stop","length","content-filter","tool-calls","abort","error","other",null],_=["human","ai","generic","system","tool"],q=["user","assistant","system","tool","tool_calls"],J=["chat","char","plan"],z=["internal","hf","fill"];import{BaseFactory as D}from"custom-factory";var W="default",H=class t extends D{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const n=e.templateFormat||W,r=t.get(n);return r.isTemplate!==t.isTemplate&&r.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,n){"string"==typeof e?(n||(n={}),n.template=e):e&&(e=(n=e).template);const{templateFormat:r}=n||{};if(super(n),this.constructor===t){const e=t.get(r||W);if(e)return Reflect.construct(e,arguments);throw new w(`Prompt template type ${r} not found`,"PromptTemplate",400)}}_initialize(t){throw new d("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new d("Not implemented","PromptTemplate")}async format(e){const n=this.data;if(e={...n,...e},n)for(const[t,r]of Object.entries(n))e[t]===r&&"function"==typeof r&&(delete e[t],e[t]=await r(e));for(const[n,r]of Object.entries(e))r instanceof t&&(delete e[n],e[n]=await r.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let n={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var r;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(n.templateFormat=e.templateFormat),r=n,n=Object.keys(r).reduce(((t,e)=>{const n=r[e];return null!=n&&(t[e]=n),t}),{}),n}};function G(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}var K=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{K=t}));var X=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var r;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(r=t,K?r:G(r))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}},Y=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),Z=Object.freeze({set:Y.Set,for:Y.For,in:Y.In,is:Y.Is,if:Y.If,else:Y.Else,endif:Y.EndIf,elif:Y.ElseIf,endfor:Y.EndFor,and:Y.And,or:Y.Or,not:Y.Not,"not in":Y.NotIn,true:Y.BooleanLiteral,false:Y.BooleanLiteral}),Q=class{constructor(t,e){this.value=t,this.type=e}};function tt(t){return/\w/.test(t)}function et(t){return/[0-9]/.test(t)}var nt=[["{%",Y.OpenStatement],["%}",Y.CloseStatement],["{{",Y.OpenExpression],["}}",Y.CloseExpression],["(",Y.OpenParen],[")",Y.CloseParen],["{",Y.OpenCurlyBracket],["}",Y.CloseCurlyBracket],["[",Y.OpenSquareBracket],["]",Y.CloseSquareBracket],[",",Y.Comma],[".",Y.Dot],[":",Y.Colon],["|",Y.Pipe],["<=",Y.ComparisonBinaryOperator],[">=",Y.ComparisonBinaryOperator],["==",Y.ComparisonBinaryOperator],["!=",Y.ComparisonBinaryOperator],["<",Y.ComparisonBinaryOperator],[">",Y.ComparisonBinaryOperator],["+",Y.AdditiveBinaryOperator],["-",Y.AdditiveBinaryOperator],["*",Y.MultiplicativeBinaryOperator],["/",Y.MultiplicativeBinaryOperator],["%",Y.MultiplicativeBinaryOperator],["=",Y.Equals]],rt=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function st(t,e={}){const n=[],r=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(r[s]);)if("\\"!==r[s]){if(e+=r[s++],s>=r.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=r.length)throw new SyntaxError("Unexpected end of input");const t=r[s++],n=rt.get(t);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=n}return e};t:for(;s<r.length;){const t=n.at(-1)?.type;if(void 0===t||t===Y.CloseStatement||t===Y.CloseExpression){let t="";for(;s<r.length&&("{"!==r[s]||"%"!==r[s+1]&&"{"!==r[s+1]);)t+=r[s++];if(t.length>0){n.push(new Q(t,Y.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===Y.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case Y.Identifier:case Y.NumericLiteral:case Y.BooleanLiteral:case Y.StringLiteral:case Y.CloseParen:case Y.CloseSquareBracket:break;default:{++s;const t=i(et);n.push(new Q(`${e}${t}`,t.length>0?Y.NumericLiteral:Y.UnaryOperator));continue}}}for(const[t,e]of nt){if(r.slice(s,s+t.length)===t){n.push(new Q(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(et(e)){const t=i(et);n.push(new Q(t,Y.NumericLiteral))}else{if(!tt(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(tt),e=Object.hasOwn(Z,t)?Z[t]:Y.Identifier;e===Y.In&&n.at(-1)?.type===Y.Not?(n.pop(),n.push(new Q("not in",Y.NotIn))):n.push(new Q(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new Q(t,Y.StringLiteral)),++s}}return n}var it=class{constructor(){this.type="Statement"}},ot=class extends it{constructor(t){super(),this.body=t,this.type="Program"}},at=class extends it{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},ct=class extends it{constructor(t,e,n){super(),this.loopvar=t,this.iterable=e,this.body=n,this.type="For"}},ut=class extends it{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},lt=class extends it{constructor(){super(...arguments),this.type="Expression"}},ft=class extends lt{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},ht=class extends lt{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},pt=class extends lt{constructor(t){super(),this.value=t,this.type="Identifier"}},wt=class extends lt{constructor(t){super(),this.value=t,this.type="Literal"}},dt=class extends wt{constructor(){super(...arguments),this.type="NumericLiteral"}},mt=class extends wt{constructor(){super(...arguments),this.type="StringLiteral"}},yt=class extends wt{constructor(){super(...arguments),this.type="BooleanLiteral"}},gt=class extends wt{constructor(){super(...arguments),this.type="ArrayLiteral"}},bt=class extends wt{constructor(){super(...arguments),this.type="TupleLiteral"}},xt=class extends wt{constructor(){super(...arguments),this.type="ObjectLiteral"}},Et=class extends lt{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},vt=class extends lt{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},$t=class extends lt{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},St=class extends lt{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},kt=class extends lt{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},Ot=class extends lt{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function Ct(t){const e=new ot([]);let n=0;function r(e,r){const s=t[n++];if(!s||s.type!==e)throw new Error(`Parser Error: ${r}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[n].type){case Y.Text:e=new mt(r(Y.Text,"Expected text token").value);break;case Y.OpenStatement:e=function(){let e;switch(r(Y.OpenStatement,"Expected opening statement token"),t[n].type){case Y.Set:++n,e=a(),r(Y.CloseStatement,"Expected closing statement token");break;case Y.If:++n,e=c(),r(Y.OpenStatement,"Expected {% token"),r(Y.EndIf,"Expected endif token"),r(Y.CloseStatement,"Expected %} token");break;case Y.For:++n,e=function(){const t=u(!0);if(!(t instanceof pt||t instanceof bt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(Y.In,"Expected `in` keyword following loop variable");const e=l();r(Y.CloseStatement,"Expected closing statement token");const n=[];for(;i(Y.OpenStatement,Y.EndFor);)n.push(s());return new ct(t,e,n)}(),r(Y.OpenStatement,"Expected {% token"),r(Y.EndFor,"Expected endfor token"),r(Y.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type}`)}return e}(),e.isStatement=!0;break;case Y.OpenExpression:e=function(){r(Y.OpenExpression,"Expected opening expression token");const t=l();return r(Y.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}return e}function i(...e){return n+e.length<=t.length&&e.some(((e,r)=>e!==t[n+r].type))}function o(...e){return n+e.length<=t.length&&e.every(((e,r)=>e===t[n+r].type))}function a(){const t=l();if(o(Y.Equals)){++n;const e=a();return new ut(t,e)}return t}function c(){const e=l();r(Y.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==Y.OpenStatement||t[n+1]?.type!==Y.ElseIf&&t[n+1]?.type!==Y.Else&&t[n+1]?.type!==Y.EndIf;)i.push(s());if(t[n]?.type===Y.OpenStatement&&t[n+1]?.type!==Y.EndIf)if(++n,o(Y.ElseIf))r(Y.ElseIf,"Expected elseif token"),a.push(c());else for(r(Y.Else,"Expected else token"),r(Y.CloseStatement,"Expected closing statement token");t[n]?.type!==Y.OpenStatement||t[n+1]?.type!==Y.EndIf;)a.push(s());return new at(e,i,a)}function u(t=!1){const e=t?x:l,r=[e()],s=o(Y.Comma);for(;s&&(++n,r.push(e()),o(Y.Comma)););return s?new bt(r):r[0]}function l(){return function(){const t=f();if(o(Y.If)){++n;const e=f();r(Y.Else,"Expected else token");const s=f();return new at(e,[t],[s])}return t}()}function f(){let e=h();for(;o(Y.Or);){const r=t[n];++n;const s=h();e=new Et(r,e,s)}return e}function h(){let e=p();for(;o(Y.And);){const r=t[n];++n;const s=p();e=new Et(r,e,s)}return e}function p(){let e;for(;o(Y.Not);){const r=t[n];++n;const s=p();e=new St(r,s)}return e??function(){let e=w();for(;o(Y.ComparisonBinaryOperator)||o(Y.In)||o(Y.NotIn);){const r=t[n];++n;const s=w();e=new Et(r,e,s)}return e}()}function w(){let e=g();for(;o(Y.AdditiveBinaryOperator);){const r=t[n];++n;const s=g();e=new Et(r,e,s)}return e}function d(){const e=function(){let e=x();for(;o(Y.Dot)||o(Y.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==Y.Dot;if(o)i=y(),r(Y.CloseSquareBracket,"Expected closing square bracket");else if(i=x(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new ft(e,i,o)}return e}();return o(Y.OpenParen)?m(e):e}function m(t){let e=new ht(t,function(){r(Y.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(Y.CloseParen);){let e=l();if(o(Y.Equals)){if(++n,!(e instanceof pt))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new Ot(e,t)}t.push(e),o(Y.Comma)&&++n}return t}();return r(Y.CloseParen,"Expected closing parenthesis for arguments list"),t}());return o(Y.OpenParen)&&(e=m(e)),e}function y(){const t=[];let e=!1;for(;!o(Y.CloseSquareBracket);)o(Y.Colon)?(t.push(void 0),++n,e=!0):(t.push(l()),o(Y.Colon)&&(++n,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new kt(...t)}return t[0]}function g(){let e=b();for(;o(Y.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=b();e=new Et(r,e,s)}return e}function b(){let t=function(){let t=d();for(;o(Y.Pipe);){++n;let e=x();if(!(e instanceof pt))throw new SyntaxError("Expected identifier for the filter");o(Y.OpenParen)&&(e=m(e)),t=new vt(t,e)}return t}();for(;o(Y.Is);){++n;const e=o(Y.Not);e&&++n;let r=x();if(r instanceof yt&&(r=new pt(r.value.toString())),!(r instanceof pt))throw new SyntaxError("Expected identifier for the test");t=new $t(t,e,r)}return t}function x(){const e=t[n];switch(e.type){case Y.NumericLiteral:return++n,new dt(Number(e.value));case Y.StringLiteral:return++n,new mt(e.value);case Y.BooleanLiteral:return++n,new yt("true"===e.value);case Y.Identifier:return++n,new pt(e.value);case Y.OpenParen:{++n;const e=u();if(t[n].type!==Y.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case Y.OpenSquareBracket:{++n;const t=[];for(;!o(Y.CloseSquareBracket);)t.push(l()),o(Y.Comma)&&++n;return++n,new gt(t)}case Y.OpenCurlyBracket:{++n;const t=new Map;for(;!o(Y.CloseCurlyBracket);){const e=l();r(Y.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(Y.Comma)&&++n}return++n,new xt(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function At(t,e,n=1){void 0===e&&(e=t,t=0);const r=[];for(let s=t;s<e;s+=n)r.push(s);return r}function jt(t,e,n,r=1){const s=Math.sign(r);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),n=(n??=t.length)<0?Math.max(t.length+n,0):Math.min(n,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),n=(n??=-1)<-1?Math.max(t.length+n,-1):Math.min(n,t.length-1));const i=[];for(let o=e;s*o<s*n;o+=r)i.push(t[o]);return i}function Nt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var Tt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Rt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},Ft=class extends Tt{constructor(){super(...arguments),this.type="NumericValue"}},It=class t extends Tt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Bt((()=>new t(this.value.toUpperCase())))],["lower",new Bt((()=>new t(this.value.toLowerCase())))],["strip",new Bt((()=>new t(this.value.trim())))],["title",new Bt((()=>new t(Nt(this.value))))],["length",new Ft(this.value.length)],["rstrip",new Bt((()=>new t(this.value.trimEnd())))],["lstrip",new Bt((()=>new t(this.value.trimStart())))]])}},Rt=class extends Tt{constructor(){super(...arguments),this.type="BooleanValue"}},Pt=class extends Tt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Bt((([t,e])=>{if(!(t instanceof It))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Mt}))],["items",new Bt((()=>new Vt(Array.from(this.value.entries()).map((([t,e])=>new Vt([new It(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new Rt(this.value.size>0)}},Vt=class extends Tt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new Ft(this.value.length)]])}__bool__(){return new Rt(this.value.length>0)}},Ut=class extends Vt{constructor(){super(...arguments),this.type="TupleValue"}},Bt=class extends Tt{constructor(){super(...arguments),this.type="FunctionValue"}},Mt=class extends Tt{constructor(){super(...arguments),this.type="NullValue"}},Lt=class extends Tt{constructor(){super(...arguments),this.type="UndefinedValue"}},_t=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Bt((t=>{if(0===t.length)return new Pt(new Map);if(1!==t.length||!(t[0]instanceof Pt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]}))]]),this.tests=new Map([["boolean",t=>"BooleanValue"===t.type],["callable",t=>t instanceof Bt],["odd",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!=0}],["even",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2==0}],["false",t=>"BooleanValue"===t.type&&!t.value],["true",t=>"BooleanValue"===t.type&&t.value],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof Vt||t instanceof It],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,Jt(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Lt}catch{return new Lt}}},qt=class{constructor(t){this.global=t??new _t}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const n=this.evaluate(t.left,e);switch(t.operator.value){case"and":return n.__bool__().value?this.evaluate(t.right,e):n;case"or":return n.__bool__().value?n:this.evaluate(t.right,e)}const r=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new Rt(n.value==r.value);case"!=":return new Rt(n.value!=r.value)}if(n instanceof Lt||r instanceof Lt)throw new Error("Cannot perform operation on undefined values");if(n instanceof Mt||r instanceof Mt)throw new Error("Cannot perform operation on null values");if(n instanceof Ft&&r instanceof Ft)switch(t.operator.value){case"+":return new Ft(n.value+r.value);case"-":return new Ft(n.value-r.value);case"*":return new Ft(n.value*r.value);case"/":return new Ft(n.value/r.value);case"%":return new Ft(n.value%r.value);case"<":return new Rt(n.value<r.value);case">":return new Rt(n.value>r.value);case">=":return new Rt(n.value>=r.value);case"<=":return new Rt(n.value<=r.value)}else if(n instanceof Vt&&r instanceof Vt){if("+"===t.operator.value)return new Vt(n.value.concat(r.value))}else if(r instanceof Vt){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new Rt(e);case"not in":return new Rt(!e)}}if((n instanceof It||r instanceof It)&&"+"===t.operator.value)return new It(n.toString()+r.toString());if(n instanceof It&&r instanceof It)switch(t.operator.value){case"in":return new Rt(r.value.includes(n.value));case"not in":return new Rt(!r.value.includes(n.value))}if(n instanceof It&&r instanceof Pt)switch(t.operator.value){case"in":return new Rt(r.value.has(n.value));case"not in":return new Rt(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const e=t.filter;if(n instanceof Vt)switch(e.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new Ft(n.value.length);case"reverse":return new Vt(n.value.reverse());case"sort":return new Vt(n.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));case"tojson":return new It(JSON.stringify(n.value));default:throw new Error(`Unknown ArrayValue filter: ${e.value}`)}else if(n instanceof It)switch(e.value){case"length":return new Ft(n.value.length);case"upper":return new It(n.value.toUpperCase());case"lower":return new It(n.value.toLowerCase());case"title":return new It(Nt(n.value));case"capitalize":return new It(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new It(n.value.trim());case"trimStart":return new It(n.value.trimStart());case"trimEnd":return new It(n.value.trimEnd());default:throw new Error(`Unknown StringValue filter: ${e.value}`)}else{if(n instanceof Ft){if("abs"===e.value)return new Ft(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${e.value}`)}if(n instanceof Pt)switch(e.value){case"items":return new Vt(Array.from(n.value.entries()).map((([t,e])=>new Vt([new It(t),e]))));case"length":return new Ft(n.value.size);case"tojson":return new It(JSON.stringify(n));case"string":return new It(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${e.value}`)}}throw new Error(`Cannot apply filter "${e.value}" to type: ${n.type}`)}if("CallExpression"===t.filter.type){const r=t.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const s=r.callee.value,i=e.lookupVariable(s);if(i instanceof Bt)return i.value([n,...r.args.map((t=>this.evaluate(t,e)))],e);if(n instanceof Vt){if("selectattr"===s){if(n.value.some((t=>!(t instanceof Pt))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=r.args.map((t=>this.evaluate(t,e)));let o;if(s){const t=e.tests.get(s.value);if(!t)throw new Error(`Unknown test: ${s.value}`);o=t}else o=(...t)=>t[0].__bool__().value;const a=n.value.filter((e=>{const n=e.value.get(t.value);return!!n&&o(n,i)}));return new Vt(a)}throw new Error(`Unknown ArrayValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const n=this.evaluate(t.operand,e),r=e.tests.get(t.test.value);if(!r)throw new Error(`Unknown test: ${t.test.value}`);const s=r(n);return new Rt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Rt(!n.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const t=this.evaluate(r,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(n+=t)}return new It(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const n=[],r=new Map;for(const s of t.args)if("KeywordArgumentExpression"===s.type){const t=s;r.set(t.key.value,this.evaluate(t.value,e))}else n.push(this.evaluate(s,e));r.size>0&&n.push(new Pt(r));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof Vt||t instanceof It))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof Ft||r instanceof Lt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof Ft||s instanceof Lt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof Ft||i instanceof Lt))throw new Error("Slice step must be numeric or undefined");return t instanceof Vt?new Vt(jt(t.value,r.value,s.value,i.value)):new It(jt(Array.from(t.value),r.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new It(t.property.value);if(n instanceof Pt){if(!(r instanceof It))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof Vt||n instanceof It)if(r instanceof Ft)s=n.value.at(r.value),n instanceof It&&(s=new It(n.value.at(r.value)));else{if(!(r instanceof It))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof It))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof Tt?s:new Lt}evaluateSet(t,e){const n=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const r=t.assignee.value;e.setVariable(r,n)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const r=t.assignee,s=this.evaluate(r.object,e);if(!(s instanceof Pt))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(r.property.value,n)}}return new Mt}evaluateIf(t,e){const n=this.evaluate(t.test,e);return this.evaluateBlock(n.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const n=new _t(e),r=this.evaluate(t.iterable,n);if(!(r instanceof Vt))throw new Error(`Expected iterable type in for loop: got ${r.type}`);let s="";for(let e=0;e<r.value.length;++e){const i=new Map([["index",new Ft(e+1)],["index0",new Ft(e)],["revindex",new Ft(r.value.length-e)],["revindex0",new Ft(r.value.length-e-1)],["first",new Rt(0===e)],["last",new Rt(e===r.value.length-1)],["length",new Ft(r.value.length)],["previtem",e>0?r.value[e-1]:new Lt],["nextitem",e<r.value.length-1?r.value[e+1]:new Lt]]);n.setVariable("loop",new Pt(i));const o=r.value[e];if("Identifier"===t.loopvar.type)n.setVariable(t.loopvar.value,o);else if("TupleLiteral"===t.loopvar.type){const e=t.loopvar;if("ArrayValue"!==o.type)throw new Error(`Cannot unpack non-iterable type: ${o.type}`);const r=o;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);for(let t=0;t<e.value.length;++t){if("Identifier"!==e.value[t].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[t].type}`);n.setVariable(e.value[t].value,r.value[t])}}s+=this.evaluateBlock(t.body,n).value}return new It(s)}evaluate(t,e){if(void 0===t)return new Lt;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"NumericLiteral":return new Ft(Number(t.value));case"StringLiteral":return new It(t.value);case"BooleanLiteral":return new Rt(t.value);case"ArrayLiteral":return new Vt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new Ut(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const t=this.evaluate(r,e);if(!(t instanceof It))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new Pt(n,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Jt(t){switch(typeof t){case"number":return new Ft(t);case"string":return new It(t);case"boolean":return new Rt(t);case"object":return null===t?new Mt:Array.isArray(t)?new Vt(t.map(Jt)):new Pt(new Map(Object.entries(t).map((([t,e])=>[t,Jt(e)]))),t);case"function":return new Bt(((e,n)=>{const r=e.map((t=>zt(t)));return Jt(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function zt(t){let e=t;return Array.isArray(t)?e=t.map((t=>zt(t))):t instanceof Map?(e={},t.forEach(((t,n)=>{e[n]=zt(t)}))):"ObjectValue"===t.type?t.orgValue?e=t.orgValue:(e={},t.forEach(((t,n)=>{e[n]=zt(t)}))):"ArrayValue"===t.type?e=t.value.map((t=>zt(t))):t.type&&(e=t.value),e}function Dt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Wt={randomInt:Dt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Dt(t.length-1):"string"==typeof e&&(e=parseInt(e)),e<0&&(e=t.length+e),t[e];if(t&&"object"==typeof t){if(void 0===e){const n=Object.keys(t);e=n[Dt(n.length-1)]}return t[e]}}},Ht=class extends _t{constructor(t){super(t),this.parent=t}assign(t){for(const[e,n]of Object.entries(t))this.set(e,n)}clear(){this.variables.clear()}},Gt=class t{static{this.global=new Ht}constructor(t,e={}){const n=st(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=Ct(n)}render(e){const n=new _t(t.global);n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",At);for(const[t,r]of Object.entries(e))n.set(t,r);return new qt(n).run(this.parsed).toString()}};function Kt(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=Kt(t.object,e);break;case"FilterExpression":n=Kt(t.operand,e);break;case"Set":{e||(e=[]);const r=Kt(t.assignee);r&&e.push(r),n=Kt(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function Xt(t){let e;if("Program"===t.type)e=t.body.some((t=>Xt(t)));else e=t.isStatement;return e}function Yt(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>Yt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>Yt(t,e))).filter(Boolean).flat();break;case"If":n=[Kt(t.test,e),...Yt(t.body,e),...Yt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[Kt(t.left,e),Kt(t.right,e)].filter(Boolean);break;case"For":{const r=Kt(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[Kt(t.iterable,e),...Yt(t.body,e)].filter(Boolean);break}case"CallExpression":n=[Kt(t.callee,e),...Yt(t.args,e)].filter(Boolean);break;default:n=[Kt(t,e)].filter(Boolean)}return n}Gt.global.assign(Wt);var Zt=class extends H{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=new Gt(n)}catch(t){}return e&&(r=Xt(e.parsed)),r}getVariables(t=this.compiledTemplate){return Yt(t.parsed,[]).filter(((t,e,n)=>n.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Gt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Qt(t){return function(e){return t}}function te(t){const e=t.split(""),n=[],r=(t,n)=>{for(let r=n;r<e.length;r+=1)if(t.includes(e[r]))return r;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])n.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])n.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=r("}",s);if(t<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,t).join("")}),s=t+1}else{if("}"===e[s])throw new Error("Single '}' in template.");{const t=r("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");n.push({type:"literal",text:i}),s=t<0?e.length:t}}return n}function ee(t,e){return t.reduce(((t,n)=>{let r;return r="variable"===n.type?n.name in e?t+e[n.name]:t:t+n.text,r}),"")}function ne(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}H.register(Zt,{name:"hf",aliases:["huggingface","internal","default"]});var re=class extends H{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=te(n)}catch(t){}if(e){r=ne(e).length>0}return r}getVariables(t=this.compiledTemplate){return ne(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=te(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return ee(this.compiledTemplate,t)}};function se(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function ie(t,e,n){let r=function(t,e,n){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])([^\2]*?)\2\s+(["'])([^\4]*?)\4\s*}}/g,((t,r,s,i,o,a)=>{if(n)return e[r]=null,t;const c=new RegExp(i,"g");return se(e,r).replace(c,a)}))}(t,e,n);return r=function(t,e,n){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])([^\2]*?)\2\s*}}/g,((t,r,s,i)=>n?(e[r]=null,t):se(e,r).join(i)))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,r,s,i,o)=>{if(n)return r.startsWith(".")&&(r=r.substring(1)),e[r]=null,t;let a;if(!r.startsWith("."))throw new Error("Functionality not implemented");{const t=se(e,r.substring(1));if(null==t)a=o??"";else if("string"==typeof t)a=t.length>0?s:o??"";else if(Array.isArray(t))a=t.length>0?s:o??"";else{if("boolean"!=typeof t)throw new Error(`Unexpected type for variable ${r}: ${typeof t}`);a=t?s:o??""}}return a}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,r,s,i)=>{if(n)return e[r]=null,t;const o=se(e,r);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,r)=>n?(e[r]=null,t):se(e,r)||""))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,r,s)=>{if(n)return e[r]=null,t;const i=se(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}H.register(re,{name:"fstring",aliases:["python","f-string","langchain"]});var oe=class extends H{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return ie(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return ie(this.template,t)}};function ae(t){return Object.keys(t).sort().map((e=>t[e]))}H.register(oe,{name:"golang",aliases:["localai","ollama"]});var ce=class extends H{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof H?t.examplePrompt:H.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=ae(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await H.format({template:n,data:t,templateFormat:r})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};H.register(ce,{name:"fewshot",aliases:["few_shot"]});var ue=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function le(t){return t.replace(/\\\$/g,"$")}function fe(t,e,n){return t.replace(ue,((r,s,i,o,a,c,u)=>"\\"===s?r.slice(1):e[a]?e[a]===n[a]?e[a]:fe(e[a],e,n):n[a]?n[a]===t?n[a]:fe(n[a],e,n):c?c.startsWith("$")?fe(c,e,n):c:""))}function he(t){let e=process.env;t&&null!=t.processEnv&&(e=t.processEnv);for(const n in t.parsed){let r=t.parsed[n];if(!r)continue;r=Object.prototype.hasOwnProperty.call(e,n)?e[n]===t.parsed[n]?fe(r,e,t.parsed):e[n]:fe(r,e,t.parsed),t.parsed[n]=r?le(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function pe(t,e={},n){switch(n||(n=new WeakSet),e.processEnv||(e.processEnv={...process.env}),e.parsed||(e.parsed=e.processEnv),typeof t){case"string":t=fe(t,e.processEnv,e.parsed);break;case"object":if(n.has(t))return t;if(n.add(t),Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];"string"!=typeof s&&"object"!=typeof s||(t[r]=pe(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=pe(s,e,n))}return t}var we="@",de=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,me=/([A-Z][a-z]{1,2}\.)\s(\w)/g,ye=/(\.[a-zA-Z]\.)\s(\w)/g,ge=new RegExp("([A-Z][a-z]{1,2}\\.)"+we+"(\\w)","g"),be=new RegExp("(\\.[a-zA-Z]\\.)"+we+"(\\w)","g");function xe(t,e,n){const r="$1"+e+"$2";let s=t;for(let t=0;t<n.length;t++)s=s.replace(n[t],r);return s}function Ee(t,e=!0){const n=(t=(t=(t=(t=t.replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let r=[];for(let t=0;t<n.length;t++){let s=n[t].trim();if(!s)continue;if(!e){r.push(s);continue}let i=xe(s,we,[me,ye]),o=Array.from(i.matchAll(de));if(o.length)for(let t=0;t<o.length;t++){let e=xe(o[t][0]," ",[ge,be]);r.push(e)}else r.push(s)}return r}function ve(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function $e(t){return new Promise((e=>setTimeout(e,t)))}var Se=600,ke=601,Oe=class extends p{constructor(t,e=Se){super(t,500)}};function Ce(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:r}=await e.read();if(!n){const e=(new TextDecoder).decode(r);t.error(new Oe(`Response error: ${e}`,ke))}}})}return new ReadableStream({start(t){t.error(new Oe("Response error: No response body",ke))}})}function Ae(){return new ReadableStream({start(t){t.close()}})}import{createParser as je}from"eventsource-parser";function Ne(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=je((n=>{if("data"in n&&"event"===n.type&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const r=t?t(n.data,{event:n.event}):n.data;r&&e.enqueue(r)}}))},transform(t){n.feed(e.decode(t))}})}function Te(t){const e=new TextEncoder;let n="";const r=t||{};return new TransformStream({async start(){r.onStart&&await r.onStart()},async transform(t,s){const i="string"==typeof t?t:t.content;s.enqueue(e.encode(i)),n+=i,r.onToken&&await r.onToken(i),r.onText&&"string"==typeof t&&await r.onText(t)},async flush(){r.onCompletion&&await r.onCompletion(n),r.onFinal&&await r.onFinal(n)}})}function Fe(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Ie(t,e){if(!t.ok)return Ce(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Ne(e))}function Re(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(t){await(e.return?.(t))}})}var Pe={};t(Pe,{XXHashAlgorithm:()=>cn,base32768:()=>en,uuid:()=>Ke,uuidNIL:()=>He,uuidParse:()=>ze,uuidStringify:()=>Je,uuidValidate:()=>De,uuidVersion:()=>We,uuidv1:()=>Le,uuidv4:()=>_e,uuidv5:()=>qe,xxhash:()=>un,xxhash32:()=>on,xxhash64:()=>an,xxhashAsStr:()=>ln});import{v1 as Ve,v5 as Ue,v4 as Be}from"uuid";import*as Me from"base32768";import{v1 as Le,v4 as _e,v5 as qe,stringify as Je,parse as ze,validate as De,version as We,NIL as He}from"uuid";var Ge={1:Ve,4:Be,5:Ue};function Ke(t=1,e){const n=Ge[t];return e?Me.encode(n(null,[])):n()}var Xe={};t(Xe,{XXHashAlgorithm:()=>cn,base32768:()=>en,xxhash:()=>un,xxhash32:()=>on,xxhash64:()=>an,xxhashAsStr:()=>ln}),e(Xe,tn);import Ye from"xxhashjs";import*as Ze from"base32768";import{canonicalize as Qe}from"json-canonicalize";import*as tn from"json-canonicalize";var en=Ze,{h32:nn,h64:rn}=Ye,sn=588213;function on(t,e=16){return"object"==typeof t&&(t=Qe(t)),nn(t,sn).toString(e)}function an(t,e=16){return"object"==typeof t&&(t=Qe(t)),rn(t,sn).toString(e)}var cn=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(cn||{});function un(t,e=111,n=sn){let r;return t.buffer&&(t=t.buffer),112!==e?(r=rn(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=nn(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function ln(t,e=111,n=sn){return Ze.encode(un(t,e,n))}e(Pe,Xe),e(V,Pe);import fn from"path";var hn=/[<>:"/\\|?*\u0000-\u001F]/,pn=/^(con|prn|aux|nul|com\d|lpt\d)$/i,wn=100,dn=/^\.+(\\|\/)|^\.+$/,mn=/\.+$/,yn=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function gn(){return new RegExp(hn.source,"g")}function bn(){return new RegExp(yn.source,"g")}function xn(t){return t&&!(hn.test(t)||bn().test(t)||dn.test(t)||mn.test(t))}function En(t){const e=t.split(fn.sep);return("/"===t[0]||e[0]&&fn.dirname(e[0])===e[0])&&e.shift(),e.every(xn)}function vn(t,e={}){const n=e.replacement||"!";if((hn.test(n)||yn.test(n))&&x("Replacement string cannot contain reserved filename characters","sanitizeFilename",400),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(dn,n)).replace(gn(),n)).replace(bn(),n)).replace(mn,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=pn.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:wn;if(t.length>r){const e=t.lastIndexOf(".");if(-1===e)t=t.slice(0,r);else{const n=t.slice(0,e),s=t.slice(e);t=n.slice(0,Math.max(1,r-s.length))+s}}return t}function $n(t,e={}){const n=t.split(fn.sep);let r;("/"===t[0]||n[0]&&fn.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>vn(t,e)));return void 0!==r&&s.unshift(r),s.join(fn.sep)}function Sn(t,e=1){let n="";for(;e--;){const e=fn.extname(t);if(!e)break;n=e+n,t=fn.basename(t,e)}return n}function kn(t){return t.split(".").length-1}import{isRegExpStr as On,toRegExp as Cn}from"util-ex";function An(t,e){if("string"!=typeof t)throw new w("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if(On(e)){const n=(e=Cn(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if(On(n)){const r=(e=Cn(n)).exec(t);if(r)return r}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function jn(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}import{newFunction as Nn}from"util-ex";function Tn(t,e){if(e){const n=Object.keys(e);if(n.length){const r=Object.values(e);return Nn("expression",n,`return ${t}`)(...r)}}return Nn("expression",[],`return ${t}`)()}function Fn(t){return t?In(t,[],""):[]}function In(t,e,n="."){return Array.isArray(t)?t.flatMap(((t,n)=>In(t,[...e,`[${n}]`]))):(r=t)&&r.constructor===Object?Object.entries(t).flatMap((([t,r])=>In(r,[...e,n+t]))):[e.join("")];var r}function Rn(t){if(t<2)throw new w("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",400);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.test(t)}}import Pn from"path";import*as Vn from"fs";function Un(t,e,n,r){let s;if(Pn.isAbsolute(t)?s=Vn.existsSync(t)?t:Bn(Pn.basename(t),[Pn.dirname(t)],n):(e||(e=["."]),s=Bn(t,e,n)),!s)throw new m(t,"loadFileFromPaths");{const t=s;s=Vn.readFileSync(s),r&&(r.filepath=t)}return s}function Bn(t,e,n){let r;const s=n?n.map((e=>Sn(t,kn(e)))):void 0;for(const i of e){const e=Pn.resolve(i,t);if(s)for(let t=0;t<s.length;t++){const i=e+(s[t]!==n[t]?n[t]:"");if(Vn.existsSync(i)){r=i;break}}else if(Vn.existsSync(e)){r=e;break}}return r}function Mn(t,e,n,r){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding??"utf8";return Un(t,e,n,r).toString(s)}import{existsSync as Ln,mkdirSync as _n,readdirSync as qn,statSync as Jn,writeFileSync as zn}from"fs";import Dn from"path";import{Config as Wn}from"load-config-file";import{parse as Hn,stringify as Gn}from"yaml";import{regexp as Kn}from"yaml-types";import{mimeType as Xn}from"mime-type/with-db";import{stringify as Yn}from"yaml";var Zn=[Kn];function Qn(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Zn.indexOf(e)&&Zn.push(e)}}function tr(t){return Hn(t,{customTags:Zn})}function er(t,e){const n=[],r=e?.after,s=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,i=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return function(t,e){const n=qn(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=Dn.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Dn.extname(t),a=Jn(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function nr(t,e){return er(t,e).map((t=>Wn.loadSync(t))).filter((t=>void 0!==t))}function rr(t,e,n=1){"."===t[0]&&n++;const r=Sn(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=Xn.lookup(t);if("application/json"===s)e=JSON.stringify(e,null,2);else{if("text/yaml"!==s)throw new Error(`${t} unsupported mime type: ${s}`);e=Gn(e)}const i=Dn.dirname(t);Ln(i)||_n(i,{recursive:!0}),zn(t,e,{encoding:"utf8"})}function sr(t,e){return t?`'${e}'`:String(e)}function ir(t,e){return t.map((t=>cr(t,e))).join(" AND ")}function or(t,e){return t.map((t=>cr(t,e))).join(" OR ")}function ar(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];let i="string"==typeof e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${sr(i,s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${sr(i,s)}`);break;case"$gt":case">":n.push(`${t} > ${sr(i,s)}`);break;case"$gte":case">=":n.push(`${t} >= ${sr(i,s)}`);break;case"$ne":case"!=":n.push(`${t} != ${sr(i,s)}`);break;case"=":case"$eq":n.push(`${t} = ${sr(i,s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>sr(!0,t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>sr(!0,t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${s.source}'`);break;case"$like":n.push(`${t} LIKE '${s}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${s}'`);break;case"$glob":n.push(`${t} GLOB '${s}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${s}'`);break;default:throw new Error(`Unsupported condition operator: ${r}`)}})),n.join(" AND ")}function cr(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(ir(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${ir(t[r],e)})`);else if("$or"===r)n.push(`(${or(t[r],e)})`);else{const t=typeof s;if(null==s)n.push(`${e(r)} IS NULL`);else if("object"!==t||Array.isArray(s))if("string"===t)n.push(`${e(r)}='${s}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${r}`);n.push(`${e(r)}=${s}`)}else n.push(ar(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function ur(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}Wn.register([".yml",".yaml"],tr),Wn.register([".json"],(function(t){return JSON.parse(t)}));var lr=class t extends E{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static async loadFrom(){if(this._apiRoot){const t=await fetch(this._apiRoot,{headers:{"Content-Type":"application/json"}}),e=await t.json();e&&this.loadFromSync(e)}else x("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const n in e){const r=this.get(n),s=e[n];r?r instanceof t?r.assign(s):x(`${n} already registered as ${r.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const n=this.get(t);if(n&&n.fetch)return n.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,n){const r={...this.fetchOptions};let s;r.headers&&r.headers["Content-Type"]||(r.headers={"Content-Type":"application/json",...r.headers}),t?.stream&&!r.headers.Connection&&(r.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,r.method=e.toUpperCase(),"get"===e||"delete"===e?s=n+this.getUrlParams(t):(r.body=JSON.stringify(t),s=n);const i=await fetch(`${this.apiRoot}/${s}`,r);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,n=t.status,r=t.statusText,s=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(r=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=r,r=e.what)),t.message&&(r=r+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return b(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},fr={...M};lr.defineProperties(lr,fr);var hr=class extends lr{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||x("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}async _func(t,e){const n=await this.fetch(e,t);if(e?.stream)return n;return await n.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},pr={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};hr.defineProperties(hr,pr);var wr=class extends hr{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=S,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",n=`${this.apiRoot}/${this.name}${e}`,r=this._es=new EventSource(n);return Object.entries(this._sseEvents).forEach((([t,e])=>{r.addEventListener(t,e)})),this._esEvents=t,r}esListener(t){const e=t.data?JSON.parse(t.data):void 0,n=t.type;if(!this._forwardEvents.has(n)){const t=this.emitter;t&&e&&n&&(Array.isArray(e)?t.emit(n,...e):t.emit(n,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);n.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},dr=new wr(S);import{getAllNames as mr}from"util-ex";var yr=class t extends E{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];r instanceof t&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}isStream(t){return this.stream}func({}){}},gr={...M};yr.defineProperties(yr,gr);var br=class extends yr{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}};const n=this.methods=[];for(const t of B)"function"==typeof this[t]&&n.push(t);mr(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((t=>{n.push(t);const e=t.slice(1);void 0===this[e]&&(this[e]=this[t])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return void 0!==t.id&&(t.id=this.cast("id",t.id)),this[e](t);throw new m(e,this.name)}},xr={methods:{type:"array"}};br.defineProperties(br,xr);var Er=T.runSync(),vr=class t extends br{constructor(){super(...arguments),this.name=S,this.description="subscribe server sent event",this.result="event",this.depends={[k]:T}}static get sse(){return this._sse||(this._sse=new j),this._sse}get sse(){return this.constructor.sse}static publish(e,n){return t.sse.publish(e,n)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,n,r){return t.sse.subscribe(e,n,r)}static alreadyForward(e){const n=Er.listeners(e);for(const e of n)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);for(const n of e)t.alreadyForward(n)||Er.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)Er.off(n,t.ebListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};x("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};x("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}x("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},$r=new vr(S);function Sr(){T.register(),P.register()}export{U as PASSING_SCORE,B as ActionNames,M as RemoteToolFuncSchema,a as ErrorCode,c as InternalErrorCode,u as NotImplementedErrorCode,l as NotFoundErrorCode,f as AlreadyExistsErrorCode,h as AbortErrorCode,p as BaseError,w as CommonError,d as NotImplementationError,m as NotFoundError,y as AlreadyExistsError,g as AbortError,b as createError,x as throwError,L as AITextGenerationFinishReasons,_ as AIMessageTypes,q as AIChatRoles,J as PromptTypes,z as PromptTemplateTypes,W as defaultTemplateFormat,H as PromptTemplate,X as PromptExampleSelector,st as tokenize,Ct as parse,qt as Interpreter,Wt as builtins,Ht as EnvironmentEx,Gt as Template,Zt as HfPromptTemplate,Qt as createHfValueFunc,te as parseFString,ee as interpolateFString,re as FStringPromptTemplate,ie as interpolateGolangTemplate,oe as GolangPromptTemplate,ae as sortedValues,ce as FewShotPromptTemplate,fe as interpolateEnv,he as expandEnv,pe as expandObjEnv,Ee as splitSentence,ve as truncTo,$e as wait,S as EventName,k as EventBusName,O as backendEventable,A as SSEChannelAlreadyClosedErrCode,j as SSEChannel,Se as RStreamErrCode,ke as ResponseRStreamErrCode,Oe as ReadableStreamError,Ce as getResponseErrorReadableStream,Ae as createEmptyReadableStream,Ne as createEventStreamTransformer,Te as createCallbacksTransformer,Fe as trimStartOfStreamHelper,Ie as AIStream,Re as readableFromAsyncIterable,Ke as uuid,Le as v1,_e as v4,qe as v5,Je as stringify,ze as parse2,De as validate,We as version,He as NIL,en as base32768,on as xxhash32,an as xxhash64,cn as XXHashAlgorithm,un as xxhash,ln as xxhashAsStr,hn as FilenameReservedRegex,pn as WindowsReservedNameRegex,gn as filenameReservedRegex,bn as reControlCharsRegex,xn as isValidFilename,En as isValidFilepath,vn as sanitizeFilename,$n as sanitizeFilepath,Sn as getMultiLevelExtname,kn as extNameLevel,An as isModelNameMatched,jn as getAllEnumKeys,Tn as parseJsJson,Fn as getKeysPath,Rn as createEndWithRepetitionDetector,Un as loadFileFromPaths,Mn as loadTextFromPaths,Wn as ConfigFile,Xn as mimeType,Qn as registerYamlTag,tr as parseYaml,er as getConfigFileNames,nr as getConfigs,rr as saveConfigFile,Yn as stringify2,cr as jsonFilterToWhere,ur as matchUrlProtocol,V as utils_exports,E as ToolFunc,v as ToolFuncSchema,lr as ClientTools,fr as ClientToolFuncSchema,yr as ServerTools,gr as ServerToolFuncSchema,N as EventToolFunc,T as event,I as _lrucache,R as createLRUCache,P as lrucache,hr as ResClientTools,pr as ResClientToolsSchema,wr as EventClient,dr as eventClient,br as ResServerTools,xr as ResServerToolsSchema,vr as EventServer,$r as eventServer,Sr as registerCoreTools};
@@ -1,22 +1 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
-
19
- export {
20
- __export,
21
- __reExport
22
- };
1
+ var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=(t,f)=>{for(var r in f)e(t,r,{get:f[r],enumerable:!0})},b=(o,b,a,c)=>{if(b&&"object"==typeof b||"function"==typeof b)for(let n of f(b))r.call(o,n)||n===a||e(o,n,{get:()=>b[n],enumerable:!(c=t(b,n))||c.enumerable});return o},a=(e,t,f)=>(b(e,t,"default"),f&&b(f,t,"default"));export{o as __export,a as __reExport};
package/dist/funcs.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- export { a1 as EventClient, a0 as EventClientFuncParams, a4 as EventServer, a3 as EventServerFuncParams, M as EventToolFunc, _ as _lrucache, Q as createLRUCache, O as event, a2 as eventClient, a5 as eventServer, W as getDefaultSimilarPassingScore, X as isSimilar, U as lrucache, Z as mergeSegments, L as registerCoreTools, $ as segments, V as similarity, Y as splitSegments } from './index-D4KjfAKl.mjs';
1
+ export { W as EventClient, V as EventClientFuncParams, Z as EventServer, Y as EventServerFuncParams, M as EventToolFunc, _ as _lrucache, Q as createLRUCache, O as event, X as eventClient, $ as eventServer, U as lrucache, L as registerCoreTools } from './index-japi6bEq.mjs';
2
2
  import 'events-ex';
3
3
  import 'property-manager';
4
4
  import 'secondary-cache';
5
- import 'http';
6
5
  import 'abstract-error';
6
+ import 'http';
package/dist/funcs.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { a1 as EventClient, a0 as EventClientFuncParams, a4 as EventServer, a3 as EventServerFuncParams, M as EventToolFunc, _ as _lrucache, Q as createLRUCache, O as event, a2 as eventClient, a5 as eventServer, W as getDefaultSimilarPassingScore, X as isSimilar, U as lrucache, Z as mergeSegments, L as registerCoreTools, $ as segments, V as similarity, Y as splitSegments } from './index-D4KjfAKl.js';
1
+ export { W as EventClient, V as EventClientFuncParams, Z as EventServer, Y as EventServerFuncParams, M as EventToolFunc, _ as _lrucache, Q as createLRUCache, O as event, X as eventClient, $ as eventServer, U as lrucache, L as registerCoreTools } from './index-japi6bEq.js';
2
2
  import 'events-ex';
3
3
  import 'property-manager';
4
4
  import 'secondary-cache';
5
- import 'http';
6
5
  import 'abstract-error';
6
+ import 'http';