@isdk/ai-tool 0.2.3 → 0.3.0

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 (267) hide show
  1. package/dist/chunk-JHHFTTVE.mjs +1 -0
  2. package/dist/funcs.d.mts +1 -1
  3. package/dist/funcs.d.ts +1 -1
  4. package/dist/funcs.js +1 -1
  5. package/dist/funcs.mjs +1 -1
  6. package/dist/{index-DUEs7T8M.d.mts → index-BC3GQn6-.d.mts} +7 -0
  7. package/dist/{index-DUEs7T8M.d.ts → index-BC3GQn6-.d.ts} +7 -0
  8. package/dist/index.d.mts +411 -10
  9. package/dist/index.d.ts +411 -10
  10. package/dist/index.js +1 -1
  11. package/dist/index.mjs +1 -1
  12. package/dist/test/util.mjs +1 -1
  13. package/docs/classes/AbortError.md +45 -15
  14. package/docs/classes/AlreadyExistsError.md +45 -15
  15. package/docs/classes/BaseError.md +42 -16
  16. package/docs/classes/CancelableAbility.md +20 -20
  17. package/docs/classes/ClientTools.md +93 -93
  18. package/docs/classes/CommonError.md +45 -15
  19. package/docs/classes/EventClient.md +115 -115
  20. package/docs/classes/EventServer.md +117 -117
  21. package/docs/classes/EventToolFunc.md +85 -85
  22. package/docs/classes/FStringPromptTemplate.md +18 -18
  23. package/docs/classes/FewShotPromptTemplate.md +22 -22
  24. package/docs/classes/GolangPromptTemplate.md +18 -18
  25. package/docs/classes/HFEnvironment.md +9 -9
  26. package/docs/classes/HFInterpreter.md +4 -4
  27. package/docs/classes/HFTemplate.md +4 -4
  28. package/docs/classes/HfPromptTemplate.md +18 -18
  29. package/docs/classes/IntSet.md +11 -11
  30. package/docs/classes/NotFoundError.md +45 -15
  31. package/docs/classes/NotImplementationError.md +45 -15
  32. package/docs/classes/PromptExampleSelector.md +8 -8
  33. package/docs/classes/PromptTemplate.md +17 -17
  34. package/docs/classes/ReadableStreamError.md +45 -15
  35. package/docs/classes/ResClientTools.md +100 -100
  36. package/docs/classes/ResServerTools.md +101 -101
  37. package/docs/classes/SSEChannel.md +14 -14
  38. package/docs/classes/Semaphore.md +8 -8
  39. package/docs/classes/ServerTools.md +89 -89
  40. package/docs/classes/TaskAbortController.md +8 -8
  41. package/docs/classes/ToolFunc.md +82 -82
  42. package/docs/classes/YamlTypeBaseObject.md +29 -0
  43. package/docs/enumerations/AsyncFeatureBits.md +3 -3
  44. package/docs/enumerations/AsyncFeatures.md +3 -3
  45. package/docs/enumerations/ErrorCode.md +21 -21
  46. package/docs/enumerations/HashAlgorithm.md +117 -0
  47. package/docs/functions/AIArgProcessor.md +1 -1
  48. package/docs/functions/AIStream.md +1 -1
  49. package/docs/functions/ChoiceArgProcessor.md +1 -1
  50. package/docs/functions/RateLimit.md +1 -1
  51. package/docs/functions/TemplateArgProcessor.md +1 -1
  52. package/docs/functions/backendEventable.md +1 -1
  53. package/docs/functions/completeSentences.md +23 -0
  54. package/docs/functions/concatText.md +23 -0
  55. package/docs/functions/countLLMTokens.md +23 -0
  56. package/docs/functions/countRegexMatches.md +1 -1
  57. package/docs/functions/createCallbacksTransformer.md +1 -1
  58. package/docs/functions/createEmptyReadableStream.md +1 -1
  59. package/docs/functions/createEndWithRepetitionDetector.md +1 -1
  60. package/docs/functions/createError.md +1 -1
  61. package/docs/functions/createEventStreamTransformer.md +1 -1
  62. package/docs/functions/createHfValueFunc.md +1 -1
  63. package/docs/functions/createLRUCache.md +1 -1
  64. package/docs/functions/createYamlObjectTag.md +23 -0
  65. package/docs/functions/dateToText.md +1 -1
  66. package/docs/functions/decodeCharset.md +23 -0
  67. package/docs/functions/detectCharset.md +23 -0
  68. package/docs/functions/encodeLLMTokens.md +23 -0
  69. package/docs/functions/expandEnv.md +1 -1
  70. package/docs/functions/expandObjEnv.md +1 -1
  71. package/docs/functions/extNameLevel.md +1 -1
  72. package/docs/functions/fileIsExists.md +1 -1
  73. package/docs/functions/filenameReservedRegex.md +1 -1
  74. package/docs/functions/filterValidFnScope.md +1 -1
  75. package/docs/functions/findIndexNonEmptyFrom.md +23 -0
  76. package/docs/functions/findPort.md +1 -1
  77. package/docs/functions/formatTextWithSpace.md +59 -0
  78. package/docs/functions/getAllEnumKeys.md +1 -1
  79. package/docs/functions/getConfigFileNames.md +1 -1
  80. package/docs/functions/getConfigs.md +1 -1
  81. package/docs/functions/getFileMetaInfo.md +21 -0
  82. package/docs/functions/getHashAlgoBySize.md +21 -0
  83. package/docs/functions/getKeysPath.md +1 -1
  84. package/docs/functions/getLLMTokenizer.md +21 -0
  85. package/docs/functions/getMultiLevelExtname.md +1 -1
  86. package/docs/functions/getPackageDir.md +1 -1
  87. package/docs/functions/getRealFilepath.md +1 -1
  88. package/docs/functions/getResponseErrorReadableStream.md +1 -1
  89. package/docs/functions/hasDirectoryIn.md +1 -1
  90. package/docs/functions/hashFile.md +23 -0
  91. package/docs/functions/hashStream.md +23 -0
  92. package/docs/functions/hfParse.md +1 -1
  93. package/docs/functions/hfTokenize.md +1 -1
  94. package/docs/functions/interpolateEnv.md +1 -1
  95. package/docs/functions/interpolateFString.md +1 -1
  96. package/docs/functions/interpolateGolangTemplate.md +1 -1
  97. package/docs/functions/isLangUsingSpaces.md +21 -0
  98. package/docs/functions/isListItemString.md +21 -0
  99. package/docs/functions/isModelNameMatched.md +1 -1
  100. package/docs/functions/isPunctuationChar.md +36 -0
  101. package/docs/functions/isRegExp.md +1 -1
  102. package/docs/functions/isSectionString.md +23 -0
  103. package/docs/functions/isSentenceEnding.md +21 -0
  104. package/docs/functions/isSepLineString.md +21 -0
  105. package/docs/functions/isSubdirectory.md +1 -1
  106. package/docs/functions/isTitleString.md +23 -0
  107. package/docs/functions/isValidFilename.md +1 -1
  108. package/docs/functions/isValidFilepath.md +1 -1
  109. package/docs/functions/isWebStream.md +1 -1
  110. package/docs/functions/jsonFilterToWhere.md +1 -1
  111. package/docs/functions/jsonToMarkdownStr.md +1 -1
  112. package/docs/functions/loadFileFromPaths.md +1 -1
  113. package/docs/functions/loadTextFromPaths.md +1 -1
  114. package/docs/functions/lrucache.md +1 -1
  115. package/docs/functions/makeToolFuncCancelable.md +1 -1
  116. package/docs/functions/matchUrlProtocol.md +1 -1
  117. package/docs/functions/memoize.md +1 -1
  118. package/docs/functions/messagesToText.md +1 -1
  119. package/docs/functions/paramsSizeToScaleStr.md +1 -1
  120. package/docs/functions/parseCommand.md +1 -1
  121. package/docs/functions/parseFString.md +1 -1
  122. package/docs/functions/parseJsJson.md +3 -3
  123. package/docs/functions/parseJsJsonSimpleSync.md +23 -0
  124. package/docs/functions/parseObjectArgInfo.md +1 -1
  125. package/docs/functions/parseObjectArgumentInfos.md +1 -1
  126. package/docs/functions/parseObjectArguments.md +1 -1
  127. package/docs/functions/parseObjectArgumentsAsArgInfos.md +1 -1
  128. package/docs/functions/parseYaml.md +1 -1
  129. package/docs/functions/quoteStr.md +1 -1
  130. package/docs/functions/reControlCharsRegex.md +1 -1
  131. package/docs/functions/readFilenamesRecursiveSync.md +1 -1
  132. package/docs/functions/readTextFileChunks.md +51 -0
  133. package/docs/functions/readTextFileChunksEx.md +23 -0
  134. package/docs/functions/readableFromAsyncIterable.md +1 -1
  135. package/docs/functions/registerCoreTools.md +1 -1
  136. package/docs/functions/registerYamlTag.md +1 -1
  137. package/docs/functions/removeMarkdownBold.md +23 -0
  138. package/docs/functions/removeMarkdownBoldAndItalic.md +23 -0
  139. package/docs/functions/removeMarkdownItalic.md +23 -0
  140. package/docs/functions/replaceWithPlaceholder.md +41 -0
  141. package/docs/functions/restoreFromPlacehoders.md +45 -0
  142. package/docs/functions/sanitizeFilename.md +1 -1
  143. package/docs/functions/sanitizeFilepath.md +1 -1
  144. package/docs/functions/saveConfigFile.md +1 -1
  145. package/docs/functions/scaleStrToParamsSize.md +1 -1
  146. package/docs/functions/simplifyObjectArguments.md +1 -1
  147. package/docs/functions/sortedValues.md +1 -1
  148. package/docs/functions/splitChunks.md +23 -0
  149. package/docs/functions/splitParagraph.md +32 -0
  150. package/docs/functions/splitSentence.md +2 -2
  151. package/docs/functions/stringifyYaml.md +1 -1
  152. package/docs/functions/stripConsoleColor.md +21 -0
  153. package/docs/functions/textToDate.md +1 -1
  154. package/docs/functions/throwError.md +1 -1
  155. package/docs/functions/toDateTime.md +1 -1
  156. package/docs/functions/trimStartOfStreamHelper.md +1 -1
  157. package/docs/functions/truncTo.md +1 -1
  158. package/docs/functions/truncateByToken.md +23 -0
  159. package/docs/functions/truncateToTokenLimit.md +44 -0
  160. package/docs/functions/truncateToTokenLimitEx.md +23 -0
  161. package/docs/functions/uuid.md +1 -1
  162. package/docs/functions/wait.md +1 -1
  163. package/docs/functions/xxhash.md +2 -2
  164. package/docs/functions/xxhash32.md +1 -1
  165. package/docs/functions/xxhash64.md +1 -1
  166. package/docs/functions/xxhashAsStr.md +2 -2
  167. package/docs/globals.md +46 -1
  168. package/docs/interfaces/AIChatAssistantMessageParam.md +48 -6
  169. package/docs/interfaces/AIChatContentPartImage.md +2 -2
  170. package/docs/interfaces/AIChatContentPartText.md +2 -2
  171. package/docs/interfaces/AIChatMessageParamBase.md +31 -1
  172. package/docs/interfaces/AIChatMessageToolCall.md +3 -3
  173. package/docs/interfaces/AIChatSystemMessageParam.md +45 -3
  174. package/docs/interfaces/AIChatToolMessageParam.md +46 -4
  175. package/docs/interfaces/AIChatUserMessageParam.md +49 -7
  176. package/docs/interfaces/AIChoiceConfig.md +7 -7
  177. package/docs/interfaces/AIResult.md +5 -5
  178. package/docs/interfaces/AIStreamParser.md +1 -1
  179. package/docs/interfaces/AIStreamParserOptions.md +1 -1
  180. package/docs/interfaces/BaseFunc.md +9 -9
  181. package/docs/interfaces/BaseFuncItem.md +8 -8
  182. package/docs/interfaces/CancelableAbilityOptions.md +2 -2
  183. package/docs/interfaces/ClientFuncItem.md +11 -11
  184. package/docs/interfaces/DotenvExpandOptions.md +3 -3
  185. package/docs/interfaces/DotenvExpandOutput.md +2 -2
  186. package/docs/interfaces/EventClientFuncParams.md +4 -4
  187. package/docs/interfaces/EventServerFuncParams.md +5 -5
  188. package/docs/interfaces/FewShotPromptTemplateOptions.md +11 -11
  189. package/docs/interfaces/FuncItem.md +9 -9
  190. package/docs/interfaces/FuncParam.md +6 -6
  191. package/docs/interfaces/HashAlgoParams.md +37 -0
  192. package/docs/interfaces/IFileMetaInfo.md +77 -0
  193. package/docs/interfaces/IReadTextFileChunksOptions.md +157 -0
  194. package/docs/interfaces/ITruncateToTokenLimitOptions.md +111 -0
  195. package/docs/interfaces/ParseObjectArgumentOptions.md +45 -5
  196. package/docs/interfaces/PromptExampleSelectorOptions.md +2 -2
  197. package/docs/interfaces/PromptTemplateOptions.md +6 -6
  198. package/docs/interfaces/RemoteFuncItem.md +11 -11
  199. package/docs/interfaces/ReplacePlacehoderOptions.md +47 -0
  200. package/docs/interfaces/ResClientFuncParams.md +2 -2
  201. package/docs/interfaces/ResServerFuncParams.md +5 -5
  202. package/docs/interfaces/SanitizeFilenameOptions.md +2 -2
  203. package/docs/interfaces/SectionStringOptions.md +27 -0
  204. package/docs/interfaces/ServerFuncItem.md +12 -12
  205. package/docs/interfaces/ServerFuncParams.md +2 -2
  206. package/docs/interfaces/SplitSentenceOptions.md +47 -0
  207. package/docs/interfaces/StreamCallbacksAndOptions.md +4 -4
  208. package/docs/interfaces/TaskPromise.md +5 -5
  209. package/docs/interfaces/ToolFuncPackage.md +3 -3
  210. package/docs/type-aliases/AIChatContentPart.md +1 -1
  211. package/docs/type-aliases/AIChatMessageParam.md +1 -1
  212. package/docs/type-aliases/AIChatRole.md +1 -1
  213. package/docs/type-aliases/AIMessageType.md +1 -1
  214. package/docs/type-aliases/AIModelNameRule.md +1 -1
  215. package/docs/type-aliases/AIModelNameRuleFn.md +1 -1
  216. package/docs/type-aliases/AIModelNameRules.md +1 -1
  217. package/docs/type-aliases/AITextGenerationFinishReason.md +1 -1
  218. package/docs/type-aliases/ActionName.md +1 -1
  219. package/docs/type-aliases/AsyncTaskId.md +1 -1
  220. package/docs/type-aliases/EventErrorListenerFn.md +1 -1
  221. package/docs/type-aliases/EventListenerFn.md +1 -1
  222. package/docs/type-aliases/FStringPromptTemplateNode.md +1 -1
  223. package/docs/type-aliases/FuncParamType.md +1 -1
  224. package/docs/type-aliases/PromptExamples.md +1 -1
  225. package/docs/type-aliases/PromptTemplateType.md +1 -1
  226. package/docs/type-aliases/PromptType.md +1 -1
  227. package/docs/type-aliases/TFunc.md +1 -1
  228. package/docs/variables/AIChatRoles.md +1 -1
  229. package/docs/variables/AIMessageTypes.md +1 -1
  230. package/docs/variables/AITextGenerationFinishReasons.md +1 -1
  231. package/docs/variables/AbortErrorCode.md +1 -1
  232. package/docs/variables/ActionNames.md +1 -1
  233. package/docs/variables/AlreadyExistsErrorCode.md +1 -1
  234. package/docs/variables/ClientToolFuncSchema.md +1 -1
  235. package/docs/variables/DefaultAsyncSemaphoreCapacity.md +1 -1
  236. package/docs/variables/EventBusName.md +1 -1
  237. package/docs/variables/EventName.md +1 -1
  238. package/docs/variables/FilenameReservedRegex.md +1 -1
  239. package/docs/variables/HFBuiltins.md +1 -1
  240. package/docs/variables/InternalErrorCode.md +1 -1
  241. package/docs/variables/LLM_TOKENIZER_NAMES.md +83 -0
  242. package/docs/variables/LLM_TOKENIZER_NAMES_MAP.md +13 -0
  243. package/docs/variables/NotFoundErrorCode.md +1 -1
  244. package/docs/variables/NotImplementedErrorCode.md +1 -1
  245. package/docs/variables/PASSING_SCORE.md +1 -1
  246. package/docs/variables/PromptTemplateTypes.md +1 -1
  247. package/docs/variables/PromptTypes.md +1 -1
  248. package/docs/variables/RStreamErrCode.md +1 -1
  249. package/docs/variables/RemoteToolFuncSchema.md +1 -1
  250. package/docs/variables/ResponseRStreamErrCode.md +1 -1
  251. package/docs/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
  252. package/docs/variables/ServerToolFuncSchema.md +1 -1
  253. package/docs/variables/ToolAsyncCancelableBit.md +1 -1
  254. package/docs/variables/ToolAsyncMultiTaskBit.md +1 -1
  255. package/docs/variables/ToolAsyncPriorityBit.md +1 -1
  256. package/docs/variables/ToolFuncSchema.md +1 -1
  257. package/docs/variables/WindowsReservedNameRegex.md +1 -1
  258. package/docs/variables/base32768.md +1 -1
  259. package/docs/variables/defaultTemplateFormat.md +1 -1
  260. package/docs/variables/event.md +1 -1
  261. package/docs/variables/eventClient.md +1 -1
  262. package/docs/variables/eventServer.md +1 -1
  263. package/docs/variables/lrucache.md +1 -1
  264. package/package.json +7 -3
  265. package/dist/chunk-FLVJ4R53.mjs +0 -1
  266. package/docs/enumerations/XXHashAlgorithm.md +0 -27
  267. /package/dist/{chunk-PXQPLL62.mjs → chunk-VIG2GB47.mjs} +0 -0
package/dist/funcs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},c=(t,n,s)=>(s=null!=t?e(i(t)):{},a(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})})(u,{EventClient:()=>pe,EventServer:()=>ve,EventToolFunc:()=>ne,_lrucache:()=>oe,createLRUCache:()=>ae,event:()=>se,eventClient:()=>de,eventServer:()=>ke,lrucache:()=>ce,registerCoreTools:()=>Se}),module.exports=(t=u,a(r({},"__esModule",{value:!0}),t));var h=require("events-ex"),l=require("property-manager"),f=require("util-ex"),w=require("@isdk/common-error"),p=(require("custom-ability"),require("util-ex"),["get","post","put","delete","patch","list","res"]),d={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,r,n,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},y=(require("date-fns"),require("date-fns"),require("custom-factory"));var m="default",b=class t extends y.BaseFactory{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 r=e.templateFormat||m,n=t.get(r);return n.isTemplate!==t.isTemplate&&n.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,r){"string"==typeof e?(r||(r={}),r.template=e):e&&(e=(r=e).template);const{templateFormat:n}=r||{};if(super(r),this.constructor===t){const e=t.get(n||m);if(e)return Reflect.construct(e,arguments);throw new w.CommonError(`Prompt template type ${n} not found`,"PromptTemplate",w.ErrorCode.InvalidArgument)}}_initialize(t){throw new w.NotImplementationError("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new w.NotImplementationError("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.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 r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};(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=>{t}));var g=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",Macro:"Macro",EndMacro:"EndMacro"}),E=Object.freeze({set:g.Set,for:g.For,in:g.In,is:g.Is,if:g.If,else:g.Else,endif:g.EndIf,elif:g.ElseIf,endfor:g.EndFor,and:g.And,or:g.Or,not:g.Not,"not in":g.NotIn,macro:g.Macro,endmacro:g.EndMacro,true:g.BooleanLiteral,false:g.BooleanLiteral,True:g.BooleanLiteral,False:g.BooleanLiteral}),x=class{constructor(t,e){this.value=t,this.type=e}};function v(t){return/\w/.test(t)}function k(t){return/[0-9]/.test(t)}var S=[["{%",g.OpenStatement],["%}",g.CloseStatement],["{{",g.OpenExpression],["}}",g.CloseExpression],["(",g.OpenParen],[")",g.CloseParen],["{",g.OpenCurlyBracket],["}",g.CloseCurlyBracket],["[",g.OpenSquareBracket],["]",g.CloseSquareBracket],[",",g.Comma],[".",g.Dot],[":",g.Colon],["|",g.Pipe],["<=",g.ComparisonBinaryOperator],[">=",g.ComparisonBinaryOperator],["==",g.ComparisonBinaryOperator],["!=",g.ComparisonBinaryOperator],["<",g.ComparisonBinaryOperator],[">",g.ComparisonBinaryOperator],["+",g.AdditiveBinaryOperator],["-",g.AdditiveBinaryOperator],["*",g.MultiplicativeBinaryOperator],["/",g.MultiplicativeBinaryOperator],["%",g.MultiplicativeBinaryOperator],["=",g.Equals]],$=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);var O=class{constructor(){this.type="Statement"}},j=class extends O{constructor(t){super(),this.body=t,this.type="Program"}},C=class extends O{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},A=class extends O{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},q=class extends O{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},M=class extends O{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},T=class extends O{constructor(){super(...arguments),this.type="Expression"}},I=class extends T{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},V=class extends T{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},N=class extends T{constructor(t){super(),this.value=t,this.type="Identifier"}},P=class extends T{constructor(t){super(),this.value=t,this.type="Literal"}},U=class extends P{constructor(){super(...arguments),this.type="NumericLiteral"}},B=class extends P{constructor(){super(...arguments),this.type="StringLiteral"}},F=class extends P{constructor(){super(...arguments),this.type="BooleanLiteral"}},_=class extends P{constructor(){super(...arguments),this.type="ArrayLiteral"}},L=class extends P{constructor(){super(...arguments),this.type="TupleLiteral"}},R=class extends P{constructor(){super(...arguments),this.type="ObjectLiteral"}},J=class extends T{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},z=class extends T{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},W=class extends T{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},K=class extends T{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},D=class extends T{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},Z=class extends T{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},H=class extends T{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function G(t){const e=new j([]);let r=0;function n(e,n){const s=t[r++];if(!s||s.type!==e)throw new Error(`Parser Error: ${n}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[r].type){case g.Text:e=new B(n(g.Text,"Expected text token").value);break;case g.OpenStatement:e=function(){let e;switch(n(g.OpenStatement,"Expected opening statement token"),t[r].type){case g.Set:++r,e=a(),n(g.CloseStatement,"Expected closing statement token");break;case g.If:++r,e=c(),n(g.OpenStatement,"Expected {% token"),n(g.EndIf,"Expected endif token"),n(g.CloseStatement,"Expected %} token");break;case g.Macro:++r,e=function(){const t=v();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=m();n(g.CloseStatement,"Expected closing statement token");const r=[];for(;i(g.OpenStatement,g.EndMacro);)r.push(s());return new M(t,e,r)}(),n(g.OpenStatement,"Expected {% token"),n(g.EndMacro,"Expected endmacro token"),n(g.CloseStatement,"Expected %} token");break;case g.For:++r,e=function(){const t=u(!0);if(!(t instanceof N||t instanceof L))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(g.In,"Expected `in` keyword following loop variable");const e=h();n(g.CloseStatement,"Expected closing statement token");const a=[];for(;i(g.OpenStatement,g.EndFor)&&i(g.OpenStatement,g.Else);)a.push(s());const c=[];if(o(g.OpenStatement,g.Else))for(++r,++r,n(g.CloseStatement,"Expected closing statement token");i(g.OpenStatement,g.EndFor);)c.push(s());return new A(t,e,a,c)}(),n(g.OpenStatement,"Expected {% token"),n(g.EndFor,"Expected endfor token"),n(g.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case g.OpenExpression:e=function(){n(g.OpenExpression,"Expected opening expression token");const t=h();return n(g.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}return e}function i(...e){return r+e.length<=t.length&&e.some(((e,n)=>e!==t[r+n].type))}function o(...e){return r+e.length<=t.length&&e.every(((e,n)=>e===t[r+n].type))}function a(){const t=h();if(o(g.Equals)){++r;const e=a();return new q(t,e)}return t}function c(){const e=h();n(g.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==g.OpenStatement||t[r+1]?.type!==g.ElseIf&&t[r+1]?.type!==g.Else&&t[r+1]?.type!==g.EndIf;)i.push(s());if(t[r]?.type===g.OpenStatement&&t[r+1]?.type!==g.EndIf)if(++r,o(g.ElseIf))n(g.ElseIf,"Expected elseif token"),a.push(c());else for(n(g.Else,"Expected else token"),n(g.CloseStatement,"Expected closing statement token");t[r]?.type!==g.OpenStatement||t[r+1]?.type!==g.EndIf;)a.push(s());return new C(e,i,a)}function u(t=!1){const e=t?v:h,n=[e()],s=o(g.Comma);for(;s&&(++r,n.push(e()),o(g.Comma)););return s?new L(n):n[0]}function h(){return function(){const t=l();if(o(g.If)){++r;const e=l();if(o(g.Else)){++r;const n=l();return new C(e,[t],[n])}return new W(t,e)}return t}()}function l(){let e=f();for(;o(g.Or);){const n=t[r];++r;const s=f();e=new J(n,e,s)}return e}function f(){let e=w();for(;o(g.And);){const n=t[r];++r;const s=w();e=new J(n,e,s)}return e}function w(){let e;for(;o(g.Not);){const n=t[r];++r;const s=w();e=new D(n,s)}return e??function(){let e=p();for(;o(g.ComparisonBinaryOperator)||o(g.In)||o(g.NotIn);){const n=t[r];++r;const s=p();e=new J(n,e,s)}return e}()}function p(){let e=E();for(;o(g.AdditiveBinaryOperator);){const n=t[r];++r;const s=E();e=new J(n,e,s)}return e}function d(){const e=function(){let e=v();for(;o(g.Dot)||o(g.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==g.Dot;if(o)i=b(),n(g.CloseSquareBracket,"Expected closing square bracket");else if(i=v(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new I(e,i,o)}return e}();return o(g.OpenParen)?y(e):e}function y(t){let e=new V(t,m());return o(g.OpenParen)&&(e=y(e)),e}function m(){n(g.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(g.CloseParen);){let e=h();if(o(g.Equals)){if(++r,!(e instanceof N))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new H(e,t)}t.push(e),o(g.Comma)&&++r}return t}();return n(g.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(g.CloseSquareBracket);)o(g.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(g.Colon)&&(++r,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 Z(...t)}return t[0]}function E(){let e=x();for(;o(g.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=x();e=new J(n,e,s)}return e}function x(){let t=function(){let t=d();for(;o(g.Pipe);){++r;let e=v();if(!(e instanceof N))throw new SyntaxError("Expected identifier for the filter");o(g.OpenParen)&&(e=y(e)),t=new z(t,e)}return t}();for(;o(g.Is);){++r;const e=o(g.Not);e&&++r;let n=v();if(n instanceof F&&(n=new N(n.value.toString())),!(n instanceof N))throw new SyntaxError("Expected identifier for the test");t=new K(t,e,n)}return t}function v(){const e=t[r];switch(e.type){case g.NumericLiteral:return++r,new U(Number(e.value));case g.StringLiteral:return++r,new B(e.value);case g.BooleanLiteral:return++r,new F("true"===e.value.toLowerCase());case g.Identifier:return++r,new N(e.value);case g.OpenParen:{++r;const e=u();if(t[r].type!==g.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case g.OpenSquareBracket:{++r;const t=[];for(;!o(g.CloseSquareBracket);)t.push(h()),o(g.Comma)&&++r;return++r,new _(t)}case g.OpenCurlyBracket:{++r;const t=new Map;for(;!o(g.CloseCurlyBracket);){const e=h();n(g.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(g.Comma)&&++r}return++r,new R(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function Q(t,e,r=1){void 0===e&&(e=t,t=0);const n=[];for(let s=t;s<e;s+=r)n.push(s);return n}function X(t,e,r,n=1){const s=Math.sign(n);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const i=[];for(let o=e;s*o<s*r;o+=n)i.push(t[o]);return i}function Y(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 nt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},et=class extends tt{constructor(){super(...arguments),this.type="NumericValue"}},rt=class t extends tt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new ct((()=>new t(this.value.toUpperCase())))],["lower",new ct((()=>new t(this.value.toLowerCase())))],["strip",new ct((()=>new t(this.value.trim())))],["title",new ct((()=>new t(Y(this.value))))],["length",new et(this.value.length)],["rstrip",new ct((()=>new t(this.value.trimEnd())))],["lstrip",new ct((()=>new t(this.value.trimStart())))]])}},nt=class extends tt{constructor(){super(...arguments),this.type="BooleanValue"}},st=class extends tt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new ct((([t,e])=>{if(!(t instanceof rt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new ut}))],["items",new ct((()=>new ot(Array.from(this.value.entries()).map((([t,e])=>new ot([new rt(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 nt(this.value.size>0)}},it=class extends st{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},ot=class extends tt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new et(this.value.length)]])}__bool__(){return new nt(this.value.length>0)}},at=class extends ot{constructor(){super(...arguments),this.type="TupleValue"}},ct=class extends tt{constructor(){super(...arguments),this.type="FunctionValue"}},ut=class extends tt{constructor(){super(...arguments),this.type="NullValue"}},ht=class extends tt{constructor(){super(...arguments),this.type="UndefinedValue"}},lt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new ct((t=>{if(0===t.length)return new st(new Map);if(1!==t.length||!(t[0]instanceof st))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 ct],["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],["string",t=>"StringValue"===t.type],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof ot||t instanceof rt],["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],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,wt(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 ht}catch{return new ht}}},ft=class{constructor(t){this.global=t??new lt}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new nt(r.value==n.value);case"!=":return new nt(r.value!=n.value)}if(r instanceof ht||n instanceof ht)throw new Error("Cannot perform operation on undefined values");if(r instanceof ut||n instanceof ut)throw new Error("Cannot perform operation on null values");if(r instanceof et&&n instanceof et)switch(t.operator.value){case"+":return new et(r.value+n.value);case"-":return new et(r.value-n.value);case"*":return new et(r.value*n.value);case"/":return new et(r.value/n.value);case"%":return new et(r.value%n.value);case"<":return new nt(r.value<n.value);case">":return new nt(r.value>n.value);case">=":return new nt(r.value>=n.value);case"<=":return new nt(r.value<=n.value)}else if(r instanceof ot&&n instanceof ot){if("+"===t.operator.value)return new ot(r.value.concat(n.value))}else if(n instanceof ot){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new nt(e);case"not in":return new nt(!e)}}if((r instanceof rt||n instanceof rt)&&"+"===t.operator.value)return new rt(r.toString()+n.toString());if(r instanceof rt&&n instanceof rt)switch(t.operator.value){case"in":return new nt(n.value.includes(r.value));case"not in":return new nt(!n.value.includes(r.value))}if(r instanceof rt&&n instanceof st)switch(t.operator.value){case"in":return new nt(n.value.has(r.value));case"not in":return new nt(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(t,e){const r=[],n=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,e))}return[r,n]}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const n=t.filter,s=e.lookupVariable(n.value);if(s instanceof ct)return s.value([r],e);if(r instanceof ot)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new et(r.value.length);case"reverse":return new ot(r.value.reverse());case"sort":return new ot(r.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}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof rt)switch(n.value){case"length":return new et(r.value.length);case"upper":return new rt(r.value.toUpperCase());case"lower":return new rt(r.value.toLowerCase());case"title":return new rt(Y(r.value));case"capitalize":return new rt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new rt(r.value.trim());case"trimStart":return new rt(r.value.trimStart());case"trimEnd":return new rt(r.value.trimEnd());case"indent":return new rt(r.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return r;default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else{if(r instanceof et){if("abs"===n.value)return new et(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof st)switch(n.value){case"items":return new ot(Array.from(r.value.entries()).map((([t,e])=>new ot([new rt(t),e]))));case"length":return new et(r.value.size);case"string":return new rt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}throw new Error(`Cannot apply filter "${n.value}" to type: ${r.type}`)}if("CallExpression"===t.filter.type){const n=t.filter;if("Identifier"!==n.callee.type)throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value,i=e.lookupVariable(s);if(i instanceof ct){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new it(s)),i.value([r,...t],e)}if(r instanceof ot){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof st))))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=n.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=r.value.filter((e=>{const r=e.value.get(t.value);return!!r&&o(r,i)}));return new ot(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof rt))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof st))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new ht}));return new ot(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof rt){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new et(4);if(!(i instanceof et))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new nt(!1),a=t.at(2)??s.get("blank")??new nt(!1),c=r.value.split("\n"),u=" ".repeat(i.value),h=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new rt(h.join("\n"))}throw new Error(`Unknown StringValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const s=n(r);return new nt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new nt(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const t=this.evaluate(n,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(r+=t)}return new rt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[r,n]=this.evaluateArguments(t.args,e);n.size>0&&r.push(new it(n));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(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ot||t instanceof rt))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),s=this.evaluate(e.stop,r),i=this.evaluate(e.step,r);if(!(n instanceof et||n instanceof ht))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof et||s instanceof ht))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof et||i instanceof ht))throw new Error("Slice step must be numeric or undefined");return t instanceof ot?new ot(X(t.value,n.value,s.value,i.value)):new rt(X(Array.from(t.value),n.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new rt(t.property.value);if(r instanceof st){if(!(n instanceof rt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof ot||r instanceof rt)if(n instanceof et)s=r.value.at(n.value),r instanceof rt&&(s=new rt(r.value.at(n.value)));else{if(!(n instanceof rt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof rt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof tt?s:new ht}evaluateSet(t,e){const r=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const n=t.assignee.value;e.setVariable(n,r)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const n=t.assignee,s=this.evaluate(n.object,e);if(!(s instanceof st))throw new Error("Cannot assign to member of non-object");if("Identifier"!==n.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}}return new ut}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new lt(e);let n,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,r),n=e.test}else s=this.evaluate(t.iterable,r);if(!(s instanceof ot))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],o=[];for(let e=0;e<s.value.length;++e){const a=new lt(r),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const r=c;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);u=t=>{for(let n=0;n<e.value.length;++n){if("Identifier"!==e.value[n].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[n].type}`);t.setVariable(e.value[n].value,r.value[n])}}}}if(n){u(a);if(!this.evaluate(n,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const n=new Map([["index",new et(e+1)],["index0",new et(e)],["revindex",new et(i.length-e)],["revindex0",new et(i.length-e-1)],["first",new nt(0===e)],["last",new nt(e===i.length-1)],["length",new et(i.length)],["previtem",e>0?i[e-1]:new ht],["nextitem",e<i.length-1?i[e+1]:new ht]]);r.setVariable("loop",new st(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new rt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new ct(((e,r)=>{const n=new lt(r);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let r=0;r<t.args.length;++r){const i=t.args[r],o=e[r];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);n.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,n);n.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,n)}))),new ut}evaluate(t,e){if(void 0===t)return new ht;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"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new et(Number(t.value));case"StringLiteral":return new rt(t.value);case"BooleanLiteral":return new nt(t.value);case"ArrayLiteral":return new ot(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new at(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const r=new Map;for(const[n,s]of t.value){const t=this.evaluate(n,e);if(!(t instanceof rt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new st(r,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 wt(t){switch(typeof t){case"number":return new et(t);case"string":return new rt(t);case"boolean":return new nt(t);case"undefined":return new ht;case"object":return null===t?new ut:Array.isArray(t)?new ot(t.map(wt)):new st(new Map(Object.entries(t).map((([t,e])=>[t,wt(e)]))),t);case"function":return new ct(((e,r)=>{const n=e.map((t=>pt(t)));return wt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function pt(t){let e=t;if(Array.isArray(t))e=t.map((t=>pt(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=pt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>pt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:pt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function dt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var yt={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 r=Object.keys(t);e=r[dt(r.length-1)]}return t[e]}},tojson:function(t,e,r){return e&&"object"==typeof e&&(e.depth&&(r=e.depth),e=e.indent),mt(t,e,r)}};function mt(t,e,r){let n="";const s=r??0;if(null===t)n="null";else{const r=typeof t;switch(r){case"undefined":n="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const r=e?" ".repeat(e):"",n="\n"+r.repeat(s),i=n+r;if(Array.isArray(t)){const r=t.map((t=>mt(t,e,s+1)));return e?`[${i}${r.join(`,${i}`)}${n}]`:`[${r.join(", ")}]`}{const r=Array.from(Object.entries(t)).map((([t,r])=>{const n=`"${t}": ${mt(r,e,s+1)}`;return e?`${i}${n}`:n}));return e?`{${r.join(",")}${n}}`:`{${r.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${r}`)}}return n}var bt=class extends lt{constructor(t){super(t),this.parent=t}assign(t){for(const[e,r]of Object.entries(t))this.set(e,r)}clear(){this.variables.clear()}},gt=class t{static{this.global=new bt}constructor(t,e={}){const r=function(t,e={}){const r=[],n=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(n[s]);)if("\\"!==n[s]){if(e+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const t=n[s++],r=$.get(t);if(void 0===r)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=r}return e};t:for(;s<n.length;){const t=r.at(-1)?.type;if(void 0===t||t===g.CloseStatement||t===g.CloseExpression){let t="";for(;s<n.length&&("{"!==n[s]||"%"!==n[s+1]&&"{"!==n[s+1]);)t+=n[s++];if(t.length>0){r.push(new x(t,g.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===g.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case g.Identifier:case g.NumericLiteral:case g.BooleanLiteral:case g.StringLiteral:case g.CloseParen:case g.CloseSquareBracket:break;default:{++s;const t=i(k);r.push(new x(`${e}${t}`,t.length>0?g.NumericLiteral:g.UnaryOperator));continue}}}for(const[t,e]of S)if(n.slice(s,s+t.length)===t){r.push(new x(t,e)),s+=t.length;continue t}if("'"!==e&&'"'!==e)if(k(e)){const t=i(k);r.push(new x(t,g.NumericLiteral))}else{if(!v(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(v),e=Object.hasOwn(E,t)?E[t]:g.Identifier;e===g.In&&r.at(-1)?.type===g.Not?(r.pop(),r.push(new x("not in",g.NotIn))):r.push(new x(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new x(t,g.StringLiteral)),++s}}return r}(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=G(r)}render(e){const r=new lt(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",Q);for(const[t,n]of Object.entries(e))r.set(t,n);return new ft(r).run(this.parsed).toString()}};function Et(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=Et(t.object,e);break;case"FilterExpression":r=Et(t.operand,e);break;case"Set":{e||(e=[]);const n=Et(t.assignee);n&&e.push(n),r=Et(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function xt(t){let e;if("Program"===t.type)e=t.body.some((t=>xt(t)));else e=t.isStatement;return e}function vt(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>vt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>vt(t,e))).filter(Boolean).flat();break;case"If":r=[Et(t.test,e),...vt(t.body,e),...vt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[Et(t.left,e),Et(t.right,e)].filter(Boolean);break;case"For":{const n=Et(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[Et(t.iterable,e),...vt(t.body,e)].filter(Boolean);break}case"CallExpression":r=[Et(t.callee,e),...vt(t.args,e)].filter(Boolean);break;default:r=[Et(t,e)].filter(Boolean)}return r}gt.global.assign(yt);function kt(t){const e=t.split(""),r=[],n=(t,r)=>{for(let n=r;n<e.length;n+=1)if(t.includes(e[n]))return n;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])r.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])r.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=n("}",s);if(t<0)throw new Error("Unclosed '{' in template.");r.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=n("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");r.push({type:"literal",text:i}),s=t<0?e.length:t}}return r}function St(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}b.register(class extends b{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=new gt(r)}catch(t){}return e&&(n=xt(e.parsed)),n}getVariables(t=this.compiledTemplate){return vt(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w.CommonError("Prompt template must be a string","PromptTemplate",w.ErrorCode.InvalidArgument);this.compiledTemplate=new gt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}},{name:"hf",aliases:["huggingface","internal","default"]});function $t(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Ot(t,e,r){let n=function(t,e,r){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s+(["'])((?:(?!\4).)*?)\4\s*}}/g,((t,n,s,i,o,a)=>{if(r)return e[n]=null,t;const c=new RegExp(i,"g");return $t(e,n).replace(c,a)}))}(t,e,r);return n=function(t,e,r){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s*}}/g,((t,n,s,i)=>r?(e[n]=null,t):$t(e,n).join(i)))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,n,s,i,o)=>{if(r)return n.startsWith(".")&&(n=n.substring(1)),e[n]=null,t;let a;if(!n.startsWith("."))throw new Error("Functionality not implemented");{const t=$t(e,n.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 ${n}: ${typeof t}`);a=t?s:o??""}}return a}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,n,s,i)=>{if(r)return e[n]=null,t;const o=$t(e,n);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,n)=>r?(e[n]=null,t):$t(e,n)||""))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,n,s)=>{if(r)return e[n]=null,t;const i=$t(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}b.register(class extends b{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=kt(r)}catch(t){}if(e){n=St(e).length>0}return n}getVariables(t=this.compiledTemplate){return St(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w.CommonError("Prompt template must be a string","PromptTemplate",w.ErrorCode.InvalidArgument);this.compiledTemplate=kt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return e=this.compiledTemplate,r=t,e.reduce(((t,e)=>{let n;return n="variable"===e.type?e.name in r?t+r[e.name]:t:t+e.text,n}),"");var e,r}},{name:"fstring",aliases:["python","f-string","langchain"]});function jt(t){return Object.keys(t).sort().map((e=>t[e]))}b.register(class extends b{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Ot(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w.CommonError("Prompt template must be a string","PromptTemplate",w.ErrorCode.InvalidArgument);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return Ot(this.template,t)}},{name:"golang",aliases:["localai","ollama"]});b.register(class extends b{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 b?t.examplePrompt:b.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 r=await this.examplePrompt.format(t);e.push(r)}else if("string"==typeof t)e.push(t);else if(t){const r=jt(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await b.format({template:r,data:t,templateFormat:n})}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}},{name:"fewshot",aliases:["few_shot"]});new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var Ct=require("custom-ability"),At="event",qt="event-bus";(0,Ct.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(qt)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.on(e,r)}once(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.once(e,r)}off(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.off(e,r)}emit(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,r):n.emit.call(this,e,this.name,...r)}emitError(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emit.call(this,"error",e,this.name,...r)}async emitAsync(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emitAsync.call(this,e,this.name,...r)}}}),!0);function Mt(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Tt=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 r,n;this.active||(0,w.throwError)("Channel closed","SSEChannel",498);let s=e;if(t||e)n=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"):"",r="id: "+n+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:n,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}for([...this.clients].filter((t=>!s||Mt(t.events,s))).forEach(((t,e)=>{t.res.write(r)}));this.messages.length>this.options.historySize;)this.messages.shift();return n}subscribe(t,e,r){this.active||(0,w.throwError)("Channel closed","SSEChannel",498);const n={req:t,res:e,events:r},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"]="*"),n.req.socket.setNoDelay(!0),n.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=>Mt(n.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),n.res.write(a),this.clients.add(n),s>0&&setTimeout((()=>{n.res.writableEnded||this.unsubscribe(n)}),s),n.res.on("close",(()=>this.unsubscribe(n))),n}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 r=e.req.socket.remoteAddress??"";r in t||(t[r]=0),t[r]++})),t}getSubscriberCount(){return this.clients.size}};require("eventsource-parser");require("uuid"),c(require("base32768")),require("uuid");var It=c(require("xxhashjs")),{h32:Vt,h64:Nt}=(c(require("base32768")),require("json-canonicalize"),It.default),Pt=(require("util-ex"),require("lodash-es"),require("util-ex"),require("load-config-file")),Ut=require("yaml"),Bt=require("yaml-types"),Ft=(require("mime-type/with-db"),[Bt.regexp]);Pt.Config.register([".yml",".yaml"],(function(t){return(0,Ut.parse)(t,{customTags:Ft})})),Pt.Config.register([".json"],(function(t){return JSON.parse(t)}));var _t=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}},Lt=require("events-ex");function Rt(t){return e=Math.min(Math.max(16,t),1073741824),e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,1+(e|=e>>16);var e}var Jt=class{constructor(t){this._capacity=Rt(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const r=this._front+e&this._capacity-1;return this.arr[r]=t,this._length=e+1,r}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,r=this.arr[e];return this.arr[e]=void 0,this._length=t-1,r}shift(){const t=this._length;if(0===t)return;const e=this._front,r=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,r}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(Rt(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const r=this._front,n=this._length;if(r+n>e){const t=r+n&e-1;!function(t,e,r,n,s){for(let i=0;i<s;++i)r[i+n]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},zt=class extends Lt.EventEmitter{};function Wt(t){return"function"==typeof t}function Kt(){return"1"}var Dt=class{constructor(t,{initFn:e=Kt,pauseFn:r,resumeFn:n,capacity:s=32}={}){if(Wt(r)!==Wt(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new Jt(t),this.waiting=new Jt(s),this.releaseEmitter=new zt,this.useDefaultTokens=e===Kt,this.pauseFn=r,this.resumeFn=n,this.paused=!1,this.releaseEmitter.on("release",(t=>{const e=this.waiting.shift();e?e.resolve(t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(t))}));for(let r=0;r<t;r++)this.free.push(e())}tryAcquire(){return this.free.pop()}acquire(t){let e=this.tryAcquire();return void 0!==e?Promise.resolve(e):new Promise(((e,r)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push({resolve:e,reject:r});return t&&t.addEventListener("abort",(()=>{this.waiting[n]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,r(e)})),n}))}release(t){this.releaseEmitter.emit("release",this.useDefaultTokens?"1":t)}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}pendingCount(){return this.waiting.length}},Zt=require("custom-ability"),Ht=require("util-ex"),Gt=class extends AbortController{constructor(t){super(),(0,Ht.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new w.AbortError(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new w.AbortError(e.reason||"aborted")}}},Qt=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){const t=this._maxTaskConcurrency;let e=this.__task_semaphore;return t>0&&!e&&(e=this.__task_semaphore=new Dt(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(Yt);let r=this.__task_aborter;if(r&&e){if(null==t)throw new w.CommonError("Missing taskId",this.name+".isAborted",w.ErrorCode.InvalidArgument);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(Yt);let r=this.__task_aborter;if(r&&e){if(null==t)throw new w.CommonError("Missing taskId",this.name+".getRunningTask",w.ErrorCode.InvalidArgument);r=r[t]}return r?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,r=void 0),r}getRunningTaskCount(){let t;if(this.hasAsyncFeature(Yt)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,r])=>{if(!r?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const r=this.super,n=this.self||this;return t=r?r.call(n,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,r=!0){const n=this.hasAsyncFeature(Yt);if(!n&&r&&this.getRunningTask())throw new w.CommonError("The task is running",this.name,w.ErrorCode.TooManyRequests);const s=t?.aborter||new Gt(this);if(!(s instanceof Gt)){if(!(s instanceof AbortController))throw new w.CommonError("aborter should be an AbortController",this.name,w.ErrorCode.InvalidArgument);Object.setPrototypeOf(s,new Gt(this))}if(n){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const r=this.super,n=this.self||this;r?r.call(n,t,e):n._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(Yt)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,r){const n=this.createAborter(e,r?.taskId,r?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=n);let s=t(e,n).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(n)},r=function(t){const e=t||{};return new TransformStream({async start(t){const r=t.error;if(t.error=n=>{r.call(t,n),e.onError&&e.onError(n)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,r){try{let n;e.onTransform&&(n=await e.onTransform(t,r)),n||(n=t),r.enqueue(n)}catch(t){r.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,Ht.defineProperty)(n,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=n.id),t)});t=t.pipeThrough(r)}else this.cleanTaskAborter(n);return t})).catch((t=>{throw this.cleanTaskAborter(n),t})).finally((()=>{n.timeoutId&&(clearTimeout(n.timeoutId),n.timeoutId=void 0)}));return s.task=n,s}runAsyncCancelableTask(t={},e,r){let n=this.createTaskPromise(e,t,r);const s=this.semaphore;if(s){const t=n,e=t.task;n=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),n.task=e}return n}abort(t,e){let r=this.__task_aborter;if(r){const n=r;if(this.hasAsyncFeature(Yt)){const t=e?.taskId;if(null==t)throw new w.CommonError("Missing data.taskId",this.name+".abort",w.ErrorCode.InvalidArgument);r=r[t],this.cleanMultiTaskAborter(t,n)}else this.__task_aborter=void 0;r&&!r.signal.aborted&&r.abort(t,e)}}};Qt.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Qt.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,Zt.createAbilityInjector)(Qt,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=te.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}}),require("lodash-es"),require("util-ex"),c(require("memoizee")),require("json-canonicalize"),require("pkg-dir"),require("util-ex");var Xt,Yt=0,te=((Xt=te||{})[Xt.MultiTask=1<<Yt]="MultiTask",Xt[Xt.Cancelable=2]="Cancelable",Xt[Xt.Priority=4]="Priority",Xt),ee=class t extends l.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const r in this.list()){const n=this.get(r);let s=n.tags;if("string"==typeof s){if(s===t){e=n;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=n;break}}return e}static getAllByTag(t){let e=[];for(const r in this.list()){const n=this.get(r);let s=n.tags;"string"==typeof s?s===t&&e.push(n):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(n)}return e}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),_t.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new w.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new w.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const r=this.get(t);if(r)return r.runWithPos(...e);throw new w.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new w.NotFoundError(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,r={}){switch(typeof e){case"string":r.name=e;break;case"function":r.func=e;break;case"object":r=e}e=r.name;let n=!!this.get(e);if(n)n=!1;else{if(!(r instanceof t))return n=new this(r),n.register();this.items[e]=r,n=r}return n}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,r=this.depends;if(r){const e=Object.keys(r);for(const n of e){const e=r[n];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={},r=Object.keys(this.params);let n=Math.min(r.length,t.length);for(let s=0;s<n;s++)e[r[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const r=Object.keys(t);let n=Math.min(r.length,this.params.length);for(let s=0;s<n;s++)e.push(t[r[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,w.throwError)("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)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(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)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),_t.has(e,t)}isStream(t){return this.stream}},re={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,f._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"}};ee.defineProperties(ee,re);var ne=class extends ee{constructor(){super(...arguments),this._emitter=new h.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},se=new ne(qt),ie=require("secondary-cache");function oe({key:t,value:e,options:r}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,r):this.cache.get(t):(r&&this.cache.setDefaultOptions(r),this.cache)}function ae(t,e){let r=ee.get(t);return r||(r=new ee(t,{func:oe,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"}),r.cache=new ie.Cache(e)),r}var ce=ae("lrucache"),ue=class t extends ee{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(0,w.throwError)("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const r in e){const n=this.get(r),s=e[r];n?n instanceof t?n.assign(s):(0,w.throwError)(`${r} already registered as ${n.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const r=this.get(t);if(r&&r.fetch)return r.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,r){const n={...this.fetchOptions};let s;n.headers&&n.headers["Content-Type"]||(n.headers={"Content-Type":"application/json",...n.headers}),t?.stream&&!n.headers.Connection&&(n.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),r?("string"!=typeof r&&(r=JSON.stringify(r)),r=this.name+"/"+r):r=this.name,n.method=e.toUpperCase(),"get"===e||"delete"===e?s=r+this.getUrlParams(t):(n.body=JSON.stringify(t),s=r);const i=await fetch(`${this.apiRoot}/${s}`,n);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,r=t.status,n=t.statusText,s=this.name;if(t.body){const r=await t.text();try{const t=JSON.parse(r);t&&(t.error&&(n=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=n,n=e.what)),t.message&&(n=n+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return(0,w.createError)(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},he={...d};ue.defineProperties(ue,he);var le=class extends ue{async _func(t,e){const r=await this.fetch(e,t);if(e?.stream)return r;return await r.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))}}},fe={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};le.defineProperties(le,fe);var we=class extends le{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||(0,w.throwError)("id is required"),"string"==typeof r&&(r=encodeURIComponent(r)),delete t.id,super.fetch(t,e,r)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},pe=class extends we{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=At,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}):"",r=`${this.apiRoot}/${this.name}${e}`,n=this._es=new EventSource(r);return Object.entries(this._sseEvents).forEach((([t,e])=>{n.addEventListener(t,e)})),this._esEvents=t,n}esListener(t){const e=t.data?JSON.parse(t.data):void 0,r=t.type;if(!this._forwardEvents.has(r)){const t=this.emitter;t&&e&&r&&(Array.isArray(e)?t.emit(r,...e):t.emit(r,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const r=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);r.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)}},de=new pe(At),ye=require("util-ex"),me=class t extends ee{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];(n instanceof t||n.isApi)&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}func({}){}},be={...d};me.defineProperties(me,be);var ge=class extends me{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const r=this.methods=[];this.initRpcMethods(r)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const r of e)"function"==typeof this[r]&&t.push(r);(0,ye.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const r=e.slice(1);void 0===this[r]&&(this[r]=this[e])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new w.NotFoundError(e,this.name)}};ge.defineProperties(ge,{methods:{type:"array"}});var Ee=class extends ge{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=p}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}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},xe=se.runSync(),ve=class t extends Ee{constructor(){super(...arguments),this.name=At,this.description="subscribe server sent event",this.result="event",this.depends={[qt]:se}}static get sse(){return this._sse||(this._sse=new Tt),this._sse}get sse(){return this.constructor.sse}static publish(e,r){return t.sse.publish(e,r)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,r,n){return t.sse.subscribe(e,r,n)}static alreadyForward(e){const r=xe.listeners(e);for(const e of r)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,r){return"string"==typeof r&&(r=[r]),this.constructor.subscribe(t,e,r)}forward(e){Array.isArray(e)||(e=[e]);for(const r of e)t.alreadyForward(r)||xe.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)xe.off(r,t.ebListener)}list({_req:t,_res:e,event:r}){t&&e&&this.subscribeSSE(t,e,r)}$sub({event:t}){if(t)return this.forward(t),{event:t};(0,w.throwError)("event is required","sub",w.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,w.throwError)("event is required","unsub",w.ErrorCode.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const r of t)this.publishSSE(e,r);return{event:t}}(0,w.throwError)("event or data is required","pub",w.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},ke=new ve(At);function Se(){se.register(),ce.register()}
1
+ "use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},c=(t,n,s)=>(s=null!=t?e(i(t)):{},a(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})})(u,{EventClient:()=>ve,EventServer:()=>qe,EventToolFunc:()=>le,_lrucache:()=>pe,createLRUCache:()=>de,event:()=>fe,eventClient:()=>ke,eventServer:()=>Me,lrucache:()=>ye,registerCoreTools:()=>Te}),module.exports=(t=u,a(r({},"__esModule",{value:!0}),t));var h=(()=>"undefined"==typeof document?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href)(),l=require("events-ex"),f=require("property-manager"),w=require("util-ex"),p=require("@isdk/common-error"),d=(require("custom-ability"),require("util-ex"),["get","post","put","delete","patch","list","res"]),y={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,r,n,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},m=(require("date-fns"),require("date-fns"),require("custom-factory"));var b="default",g=class t extends m.BaseFactory{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 r=e.templateFormat||b,n=t.get(r);return n.isTemplate!==t.isTemplate&&n.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,r){"string"==typeof e?(r||(r={}),r.template=e):e&&(e=(r=e).template);const{templateFormat:n}=r||{};if(super(r),this.constructor===t){const e=t.get(n||b);if(e)return Reflect.construct(e,arguments);throw new p.CommonError(`Prompt template type ${n} not found`,"PromptTemplate",p.ErrorCode.InvalidArgument)}}_initialize(t){throw new p.NotImplementationError("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new p.NotImplementationError("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.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 r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};(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=>{0}));var E=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",Macro:"Macro",EndMacro:"EndMacro"}),x=Object.freeze({set:E.Set,for:E.For,in:E.In,is:E.Is,if:E.If,else:E.Else,endif:E.EndIf,elif:E.ElseIf,endfor:E.EndFor,and:E.And,or:E.Or,not:E.Not,"not in":E.NotIn,macro:E.Macro,endmacro:E.EndMacro,true:E.BooleanLiteral,false:E.BooleanLiteral,True:E.BooleanLiteral,False:E.BooleanLiteral}),v=class{constructor(t,e){this.value=t,this.type=e}};function k(t){return/\w/.test(t)}function S(t){return/[0-9]/.test(t)}var $=[["{%",E.OpenStatement],["%}",E.CloseStatement],["{{",E.OpenExpression],["}}",E.CloseExpression],["(",E.OpenParen],[")",E.CloseParen],["{",E.OpenCurlyBracket],["}",E.CloseCurlyBracket],["[",E.OpenSquareBracket],["]",E.CloseSquareBracket],[",",E.Comma],[".",E.Dot],[":",E.Colon],["|",E.Pipe],["<=",E.ComparisonBinaryOperator],[">=",E.ComparisonBinaryOperator],["==",E.ComparisonBinaryOperator],["!=",E.ComparisonBinaryOperator],["<",E.ComparisonBinaryOperator],[">",E.ComparisonBinaryOperator],["+",E.AdditiveBinaryOperator],["-",E.AdditiveBinaryOperator],["*",E.MultiplicativeBinaryOperator],["/",E.MultiplicativeBinaryOperator],["%",E.MultiplicativeBinaryOperator],["=",E.Equals]],j=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);var O=class{constructor(){this.type="Statement"}},C=class extends O{constructor(t){super(),this.body=t,this.type="Program"}},A=class extends O{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},q=class extends O{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},M=class extends O{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},T=class extends O{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},I=class extends O{constructor(){super(...arguments),this.type="Expression"}},V=class extends I{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},N=class extends I{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},P=class extends I{constructor(t){super(),this.value=t,this.type="Identifier"}},U=class extends I{constructor(t){super(),this.value=t,this.type="Literal"}},B=class extends U{constructor(){super(...arguments),this.type="NumericLiteral"}},_=class extends U{constructor(){super(...arguments),this.type="StringLiteral"}},F=class extends U{constructor(){super(...arguments),this.type="BooleanLiteral"}},R=class extends U{constructor(){super(...arguments),this.type="ArrayLiteral"}},L=class extends U{constructor(){super(...arguments),this.type="TupleLiteral"}},J=class extends U{constructor(){super(...arguments),this.type="ObjectLiteral"}},z=class extends I{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},W=class extends I{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},K=class extends I{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},D=class extends I{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},Z=class extends I{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},H=class extends I{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},G=class extends I{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function Q(t){const e=new C([]);let r=0;function n(e,n){const s=t[r++];if(!s||s.type!==e)throw new Error(`Parser Error: ${n}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[r].type){case E.Text:e=new _(n(E.Text,"Expected text token").value);break;case E.OpenStatement:e=function(){let e;switch(n(E.OpenStatement,"Expected opening statement token"),t[r].type){case E.Set:++r,e=a(),n(E.CloseStatement,"Expected closing statement token");break;case E.If:++r,e=c(),n(E.OpenStatement,"Expected {% token"),n(E.EndIf,"Expected endif token"),n(E.CloseStatement,"Expected %} token");break;case E.Macro:++r,e=function(){const t=v();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=m();n(E.CloseStatement,"Expected closing statement token");const r=[];for(;i(E.OpenStatement,E.EndMacro);)r.push(s());return new T(t,e,r)}(),n(E.OpenStatement,"Expected {% token"),n(E.EndMacro,"Expected endmacro token"),n(E.CloseStatement,"Expected %} token");break;case E.For:++r,e=function(){const t=u(!0);if(!(t instanceof P||t instanceof L))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(E.In,"Expected `in` keyword following loop variable");const e=h();n(E.CloseStatement,"Expected closing statement token");const a=[];for(;i(E.OpenStatement,E.EndFor)&&i(E.OpenStatement,E.Else);)a.push(s());const c=[];if(o(E.OpenStatement,E.Else))for(++r,++r,n(E.CloseStatement,"Expected closing statement token");i(E.OpenStatement,E.EndFor);)c.push(s());return new q(t,e,a,c)}(),n(E.OpenStatement,"Expected {% token"),n(E.EndFor,"Expected endfor token"),n(E.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case E.OpenExpression:e=function(){n(E.OpenExpression,"Expected opening expression token");const t=h();return n(E.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}return e}function i(...e){return r+e.length<=t.length&&e.some(((e,n)=>e!==t[r+n].type))}function o(...e){return r+e.length<=t.length&&e.every(((e,n)=>e===t[r+n].type))}function a(){const t=h();if(o(E.Equals)){++r;const e=a();return new M(t,e)}return t}function c(){const e=h();n(E.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==E.OpenStatement||t[r+1]?.type!==E.ElseIf&&t[r+1]?.type!==E.Else&&t[r+1]?.type!==E.EndIf;)i.push(s());if(t[r]?.type===E.OpenStatement&&t[r+1]?.type!==E.EndIf)if(++r,o(E.ElseIf))n(E.ElseIf,"Expected elseif token"),a.push(c());else for(n(E.Else,"Expected else token"),n(E.CloseStatement,"Expected closing statement token");t[r]?.type!==E.OpenStatement||t[r+1]?.type!==E.EndIf;)a.push(s());return new A(e,i,a)}function u(t=!1){const e=t?v:h,n=[e()],s=o(E.Comma);for(;s&&(++r,n.push(e()),o(E.Comma)););return s?new L(n):n[0]}function h(){return function(){const t=l();if(o(E.If)){++r;const e=l();if(o(E.Else)){++r;const n=l();return new A(e,[t],[n])}return new K(t,e)}return t}()}function l(){let e=f();for(;o(E.Or);){const n=t[r];++r;const s=f();e=new z(n,e,s)}return e}function f(){let e=w();for(;o(E.And);){const n=t[r];++r;const s=w();e=new z(n,e,s)}return e}function w(){let e;for(;o(E.Not);){const n=t[r];++r;const s=w();e=new Z(n,s)}return e??function(){let e=p();for(;o(E.ComparisonBinaryOperator)||o(E.In)||o(E.NotIn);){const n=t[r];++r;const s=p();e=new z(n,e,s)}return e}()}function p(){let e=g();for(;o(E.AdditiveBinaryOperator);){const n=t[r];++r;const s=g();e=new z(n,e,s)}return e}function d(){const e=function(){let e=v();for(;o(E.Dot)||o(E.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==E.Dot;if(o)i=b(),n(E.CloseSquareBracket,"Expected closing square bracket");else if(i=v(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new V(e,i,o)}return e}();return o(E.OpenParen)?y(e):e}function y(t){let e=new N(t,m());return o(E.OpenParen)&&(e=y(e)),e}function m(){n(E.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(E.CloseParen);){let e=h();if(o(E.Equals)){if(++r,!(e instanceof P))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new G(e,t)}t.push(e),o(E.Comma)&&++r}return t}();return n(E.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(E.CloseSquareBracket);)o(E.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(E.Colon)&&(++r,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 H(...t)}return t[0]}function g(){let e=x();for(;o(E.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=x();e=new z(n,e,s)}return e}function x(){let t=function(){let t=d();for(;o(E.Pipe);){++r;let e=v();if(!(e instanceof P))throw new SyntaxError("Expected identifier for the filter");o(E.OpenParen)&&(e=y(e)),t=new W(t,e)}return t}();for(;o(E.Is);){++r;const e=o(E.Not);e&&++r;let n=v();if(n instanceof F&&(n=new P(n.value.toString())),!(n instanceof P))throw new SyntaxError("Expected identifier for the test");t=new D(t,e,n)}return t}function v(){const e=t[r];switch(e.type){case E.NumericLiteral:return++r,new B(Number(e.value));case E.StringLiteral:return++r,new _(e.value);case E.BooleanLiteral:return++r,new F("true"===e.value.toLowerCase());case E.Identifier:return++r,new P(e.value);case E.OpenParen:{++r;const e=u();if(t[r].type!==E.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case E.OpenSquareBracket:{++r;const t=[];for(;!o(E.CloseSquareBracket);)t.push(h()),o(E.Comma)&&++r;return++r,new R(t)}case E.OpenCurlyBracket:{++r;const t=new Map;for(;!o(E.CloseCurlyBracket);){const e=h();n(E.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(E.Comma)&&++r}return++r,new J(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function X(t,e,r=1){void 0===e&&(e=t,t=0);const n=[];for(let s=t;s<e;s+=r)n.push(s);return n}function Y(t,e,r,n=1){const s=Math.sign(n);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const i=[];for(let o=e;s*o<s*r;o+=n)i.push(t[o]);return i}function tt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var et=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new st(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},rt=class extends et{constructor(){super(...arguments),this.type="NumericValue"}},nt=class t extends et{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new ut((()=>new t(this.value.toUpperCase())))],["lower",new ut((()=>new t(this.value.toLowerCase())))],["strip",new ut((()=>new t(this.value.trim())))],["title",new ut((()=>new t(tt(this.value))))],["length",new rt(this.value.length)],["rstrip",new ut((()=>new t(this.value.trimEnd())))],["lstrip",new ut((()=>new t(this.value.trimStart())))]])}},st=class extends et{constructor(){super(...arguments),this.type="BooleanValue"}},it=class extends et{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new ut((([t,e])=>{if(!(t instanceof nt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new ht}))],["items",new ut((()=>new at(Array.from(this.value.entries()).map((([t,e])=>new at([new nt(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 st(this.value.size>0)}},ot=class extends it{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},at=class extends et{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new rt(this.value.length)]])}__bool__(){return new st(this.value.length>0)}},ct=class extends at{constructor(){super(...arguments),this.type="TupleValue"}},ut=class extends et{constructor(){super(...arguments),this.type="FunctionValue"}},ht=class extends et{constructor(){super(...arguments),this.type="NullValue"}},lt=class extends et{constructor(){super(...arguments),this.type="UndefinedValue"}},ft=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new ut((t=>{if(0===t.length)return new it(new Map);if(1!==t.length||!(t[0]instanceof it))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 ut],["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],["string",t=>"StringValue"===t.type],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof at||t instanceof nt],["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],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,pt(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}}},wt=class{constructor(t){this.global=t??new ft}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new st(r.value==n.value);case"!=":return new st(r.value!=n.value)}if(r instanceof lt||n instanceof lt)throw new Error("Cannot perform operation on undefined values");if(r instanceof ht||n instanceof ht)throw new Error("Cannot perform operation on null values");if(r instanceof rt&&n instanceof rt)switch(t.operator.value){case"+":return new rt(r.value+n.value);case"-":return new rt(r.value-n.value);case"*":return new rt(r.value*n.value);case"/":return new rt(r.value/n.value);case"%":return new rt(r.value%n.value);case"<":return new st(r.value<n.value);case">":return new st(r.value>n.value);case">=":return new st(r.value>=n.value);case"<=":return new st(r.value<=n.value)}else if(r instanceof at&&n instanceof at){if("+"===t.operator.value)return new at(r.value.concat(n.value))}else if(n instanceof at){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new st(e);case"not in":return new st(!e)}}if((r instanceof nt||n instanceof nt)&&"+"===t.operator.value)return new nt(r.toString()+n.toString());if(r instanceof nt&&n instanceof nt)switch(t.operator.value){case"in":return new st(n.value.includes(r.value));case"not in":return new st(!n.value.includes(r.value))}if(r instanceof nt&&n instanceof it)switch(t.operator.value){case"in":return new st(n.value.has(r.value));case"not in":return new st(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(t,e){const r=[],n=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,e))}return[r,n]}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const n=t.filter,s=e.lookupVariable(n.value);if(s instanceof ut)return s.value([r],e);if(r instanceof at)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new rt(r.value.length);case"reverse":return new at(r.value.reverse());case"sort":return new at(r.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}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof nt)switch(n.value){case"length":return new rt(r.value.length);case"upper":return new nt(r.value.toUpperCase());case"lower":return new nt(r.value.toLowerCase());case"title":return new nt(tt(r.value));case"capitalize":return new nt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new nt(r.value.trim());case"trimStart":return new nt(r.value.trimStart());case"trimEnd":return new nt(r.value.trimEnd());case"indent":return new nt(r.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return r;default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else{if(r instanceof rt){if("abs"===n.value)return new rt(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof it)switch(n.value){case"items":return new at(Array.from(r.value.entries()).map((([t,e])=>new at([new nt(t),e]))));case"length":return new rt(r.value.size);case"string":return new nt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}throw new Error(`Cannot apply filter "${n.value}" to type: ${r.type}`)}if("CallExpression"===t.filter.type){const n=t.filter;if("Identifier"!==n.callee.type)throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value,i=e.lookupVariable(s);if(i instanceof ut){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new ot(s)),i.value([r,...t],e)}if(r instanceof at){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof it))))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=n.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=r.value.filter((e=>{const r=e.value.get(t.value);return!!r&&o(r,i)}));return new at(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof nt))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof it))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new lt}));return new at(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof nt){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new rt(4);if(!(i instanceof rt))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new st(!1),a=t.at(2)??s.get("blank")??new st(!1),c=r.value.split("\n"),u=" ".repeat(i.value),h=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new nt(h.join("\n"))}throw new Error(`Unknown StringValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const s=n(r);return new st(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new st(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const t=this.evaluate(n,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(r+=t)}return new nt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[r,n]=this.evaluateArguments(t.args,e);n.size>0&&r.push(new ot(n));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(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof at||t instanceof nt))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),s=this.evaluate(e.stop,r),i=this.evaluate(e.step,r);if(!(n instanceof rt||n instanceof lt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof rt||s instanceof lt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof rt||i instanceof lt))throw new Error("Slice step must be numeric or undefined");return t instanceof at?new at(Y(t.value,n.value,s.value,i.value)):new nt(Y(Array.from(t.value),n.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new nt(t.property.value);if(r instanceof it){if(!(n instanceof nt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof at||r instanceof nt)if(n instanceof rt)s=r.value.at(n.value),r instanceof nt&&(s=new nt(r.value.at(n.value)));else{if(!(n instanceof nt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof nt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof et?s:new lt}evaluateSet(t,e){const r=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const n=t.assignee.value;e.setVariable(n,r)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const n=t.assignee,s=this.evaluate(n.object,e);if(!(s instanceof it))throw new Error("Cannot assign to member of non-object");if("Identifier"!==n.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}}return new ht}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new ft(e);let n,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,r),n=e.test}else s=this.evaluate(t.iterable,r);if(!(s instanceof at))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],o=[];for(let e=0;e<s.value.length;++e){const a=new ft(r),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const r=c;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);u=t=>{for(let n=0;n<e.value.length;++n){if("Identifier"!==e.value[n].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[n].type}`);t.setVariable(e.value[n].value,r.value[n])}}}}if(n){u(a);if(!this.evaluate(n,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const n=new Map([["index",new rt(e+1)],["index0",new rt(e)],["revindex",new rt(i.length-e)],["revindex0",new rt(i.length-e-1)],["first",new st(0===e)],["last",new st(e===i.length-1)],["length",new rt(i.length)],["previtem",e>0?i[e-1]:new lt],["nextitem",e<i.length-1?i[e+1]:new lt]]);r.setVariable("loop",new it(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new nt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new ut(((e,r)=>{const n=new ft(r);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let r=0;r<t.args.length;++r){const i=t.args[r],o=e[r];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);n.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,n);n.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,n)}))),new ht}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"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new rt(Number(t.value));case"StringLiteral":return new nt(t.value);case"BooleanLiteral":return new st(t.value);case"ArrayLiteral":return new at(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new ct(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const r=new Map;for(const[n,s]of t.value){const t=this.evaluate(n,e);if(!(t instanceof nt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new it(r,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 pt(t){switch(typeof t){case"number":return new rt(t);case"string":return new nt(t);case"boolean":return new st(t);case"undefined":return new lt;case"object":return null===t?new ht:Array.isArray(t)?new at(t.map(pt)):new it(new Map(Object.entries(t).map((([t,e])=>[t,pt(e)]))),t);case"function":return new ut(((e,r)=>{const n=e.map((t=>dt(t)));return pt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function dt(t){let e=t;if(Array.isArray(t))e=t.map((t=>dt(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=dt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>dt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:dt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function yt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var mt={randomInt:yt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=yt(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 r=Object.keys(t);e=r[yt(r.length-1)]}return t[e]}},tojson:function(t,e,r){return e&&"object"==typeof e&&(e.depth&&(r=e.depth),e=e.indent),bt(t,e,r)}};function bt(t,e,r){let n="";const s=r??0;if(null===t)n="null";else{const r=typeof t;switch(r){case"undefined":n="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const r=e?" ".repeat(e):"",n="\n"+r.repeat(s),i=n+r;if(Array.isArray(t)){const r=t.map((t=>bt(t,e,s+1)));return e?`[${i}${r.join(`,${i}`)}${n}]`:`[${r.join(", ")}]`}{const r=Array.from(Object.entries(t)).map((([t,r])=>{const n=`"${t}": ${bt(r,e,s+1)}`;return e?`${i}${n}`:n}));return e?`{${r.join(",")}${n}}`:`{${r.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${r}`)}}return n}var gt=class extends ft{constructor(t){super(t),this.parent=t}assign(t){for(const[e,r]of Object.entries(t))this.set(e,r)}clear(){this.variables.clear()}},Et=class t{static{this.global=new gt}constructor(t,e={}){const r=function(t,e={}){const r=[],n=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(n[s]);)if("\\"!==n[s]){if(e+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const t=n[s++],r=j.get(t);if(void 0===r)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=r}return e};t:for(;s<n.length;){const t=r.at(-1)?.type;if(void 0===t||t===E.CloseStatement||t===E.CloseExpression){let t="";for(;s<n.length&&("{"!==n[s]||"%"!==n[s+1]&&"{"!==n[s+1]);)t+=n[s++];if(t.length>0){r.push(new v(t,E.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===E.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case E.Identifier:case E.NumericLiteral:case E.BooleanLiteral:case E.StringLiteral:case E.CloseParen:case E.CloseSquareBracket:break;default:{++s;const t=i(S);r.push(new v(`${e}${t}`,t.length>0?E.NumericLiteral:E.UnaryOperator));continue}}}for(const[t,e]of $)if(n.slice(s,s+t.length)===t){r.push(new v(t,e)),s+=t.length;continue t}if("'"!==e&&'"'!==e)if(S(e)){const t=i(S);r.push(new v(t,E.NumericLiteral))}else{if(!k(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(k),e=Object.hasOwn(x,t)?x[t]:E.Identifier;e===E.In&&r.at(-1)?.type===E.Not?(r.pop(),r.push(new v("not in",E.NotIn))):r.push(new v(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new v(t,E.StringLiteral)),++s}}return r}(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=Q(r)}render(e){const r=new ft(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",X);for(const[t,n]of Object.entries(e))r.set(t,n);return new wt(r).run(this.parsed).toString()}};function xt(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=xt(t.object,e);break;case"FilterExpression":r=xt(t.operand,e);break;case"Set":{e||(e=[]);const n=xt(t.assignee);n&&e.push(n),r=xt(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function vt(t){let e;if("Program"===t.type)e=t.body.some((t=>vt(t)));else e=t.isStatement;return e}function kt(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>kt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>kt(t,e))).filter(Boolean).flat();break;case"If":r=[xt(t.test,e),...kt(t.body,e),...kt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[xt(t.left,e),xt(t.right,e)].filter(Boolean);break;case"For":{const n=xt(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[xt(t.iterable,e),...kt(t.body,e)].filter(Boolean);break}case"CallExpression":r=[xt(t.callee,e),...kt(t.args,e)].filter(Boolean);break;default:r=[xt(t,e)].filter(Boolean)}return r}Et.global.assign(mt);function St(t){const e=t.split(""),r=[],n=(t,r)=>{for(let n=r;n<e.length;n+=1)if(t.includes(e[n]))return n;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])r.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])r.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=n("}",s);if(t<0)throw new Error("Unclosed '{' in template.");r.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=n("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");r.push({type:"literal",text:i}),s=t<0?e.length:t}}return r}function $t(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}g.register(class extends g{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=new Et(r)}catch(t){}return e&&(n=vt(e.parsed)),n}getVariables(t=this.compiledTemplate){return kt(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new p.CommonError("Prompt template must be a string","PromptTemplate",p.ErrorCode.InvalidArgument);this.compiledTemplate=new Et(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}},{name:"hf",aliases:["huggingface","internal","default"]});function jt(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Ot(t,e,r){let n=function(t,e,r){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s+(["'])((?:(?!\4).)*?)\4\s*}}/g,((t,n,s,i,o,a)=>{if(r)return e[n]=null,t;const c=new RegExp(i,"g");return jt(e,n).replace(c,a)}))}(t,e,r);return n=function(t,e,r){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])((?:(?!\2).)*?)\2\s*}}/g,((t,n,s,i)=>r?(e[n]=null,t):jt(e,n).join(i)))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,n,s,i,o)=>{if(r)return n.startsWith(".")&&(n=n.substring(1)),e[n]=null,t;let a;if(!n.startsWith("."))throw new Error("Functionality not implemented");{const t=jt(e,n.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 ${n}: ${typeof t}`);a=t?s:o??""}}return a}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,n,s,i)=>{if(r)return e[n]=null,t;const o=jt(e,n);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,n)=>r?(e[n]=null,t):jt(e,n)||""))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,n,s)=>{if(r)return e[n]=null,t;const i=jt(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}g.register(class extends g{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=St(r)}catch(t){}if(e){n=$t(e).length>0}return n}getVariables(t=this.compiledTemplate){return $t(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new p.CommonError("Prompt template must be a string","PromptTemplate",p.ErrorCode.InvalidArgument);this.compiledTemplate=St(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return e=this.compiledTemplate,r=t,e.reduce(((t,e)=>{let n;return n="variable"===e.type?e.name in r?t+r[e.name]:t:t+e.text,n}),"");var e,r}},{name:"fstring",aliases:["python","f-string","langchain"]});function Ct(t){return Object.keys(t).sort().map((e=>t[e]))}g.register(class extends g{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Ot(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new p.CommonError("Prompt template must be a string","PromptTemplate",p.ErrorCode.InvalidArgument);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return Ot(this.template,t)}},{name:"golang",aliases:["localai","ollama"]});g.register(class extends g{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 g?t.examplePrompt:g.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 r=await this.examplePrompt.format(t);e.push(r)}else if("string"==typeof t)e.push(t);else if(t){const r=Ct(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await g.format({template:r,data:t,templateFormat:n})}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}},{name:"fewshot",aliases:["few_shot"]});require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var At=require("custom-ability"),qt="event",Mt="event-bus";(0,At.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Mt)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.on(e,r)}once(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.once(e,r)}off(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.off(e,r)}emit(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,r):n.emit.call(this,e,this.name,...r)}emitError(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emit.call(this,"error",e,this.name,...r)}async emitAsync(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emitAsync.call(this,e,this.name,...r)}}}),!0);function Tt(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var It=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 r,n;this.active||(0,p.throwError)("Channel closed","SSEChannel",498);let s=e;if(t||e)n=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"):"",r="id: "+n+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:n,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}for([...this.clients].filter((t=>!s||Tt(t.events,s))).forEach(((t,e)=>{t.res.write(r)}));this.messages.length>this.options.historySize;)this.messages.shift();return n}subscribe(t,e,r){this.active||(0,p.throwError)("Channel closed","SSEChannel",498);const n={req:t,res:e,events:r},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"]="*"),n.req.socket.setNoDelay(!0),n.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=>Tt(n.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),n.res.write(a),this.clients.add(n),s>0&&setTimeout((()=>{n.res.writableEnded||this.unsubscribe(n)}),s),n.res.on("close",(()=>this.unsubscribe(n))),n}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 r=e.req.socket.remoteAddress??"";r in t||(t[r]=0),t[r]++})),t}getSubscriberCount(){return this.clients.size}};require("eventsource-parser");require("uuid"),c(require("base32768")),require("uuid"),require("hash-wasm");var Vt=c(require("xxhashjs")),{h32:Nt,h64:Pt}=(c(require("base32768")),require("json-canonicalize"),Vt.default),Ut=(require("util-ex"),require("lodash-es"),require("util-ex"),require("lodash-es"),require("util-ex"),"[a-zA-Z_$][a-zA-Z_\\d$]*"),Bt=(new RegExp(`^\\s*(\\(\\s*\\)|${Ut}|\\(${`${Ut}\\s*(,\\s*${Ut})*`}\\))\\s*=>`),c(require("mime-type/with-db")),c(require("jschardet")),require("load-config-file")),_t=require("yaml"),Ft=require("yaml-types"),Rt=(require("mime-type/with-db"),[Ft.regexp]);Bt.Config.register([".yml",".yaml"],(function(t){return(0,_t.parse)(t,{customTags:Rt})})),Bt.Config.register([".json"],(function(t){return JSON.parse(t)}));var Lt=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}},Jt=require("events-ex");function zt(t){return e=Math.min(Math.max(16,t),1073741824),e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,1+(e|=e>>16);var e}var Wt=class{constructor(t){this._capacity=zt(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const r=this._front+e&this._capacity-1;return this.arr[r]=t,this._length=e+1,r}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,r=this.arr[e];return this.arr[e]=void 0,this._length=t-1,r}shift(){const t=this._length;if(0===t)return;const e=this._front,r=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,r}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(zt(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const r=this._front,n=this._length;if(r+n>e){const t=r+n&e-1;!function(t,e,r,n,s){for(let i=0;i<s;++i)r[i+n]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},Kt=class extends Jt.EventEmitter{};function Dt(t){return"function"==typeof t}function Zt(){return"1"}var Ht=class{constructor(t,{initFn:e=Zt,pauseFn:r,resumeFn:n,capacity:s=32}={}){if(Dt(r)!==Dt(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new Wt(t),this.waiting=new Wt(s),this.releaseEmitter=new Kt,this.useDefaultTokens=e===Zt,this.pauseFn=r,this.resumeFn=n,this.paused=!1,this.releaseEmitter.on("release",(t=>{const e=this.waiting.shift();e?e.resolve(t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(t))}));for(let r=0;r<t;r++)this.free.push(e())}tryAcquire(){return this.free.pop()}acquire(t){let e=this.tryAcquire();return void 0!==e?Promise.resolve(e):new Promise(((e,r)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push({resolve:e,reject:r});return t&&t.addEventListener("abort",(()=>{this.waiting[n]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,r(e)})),n}))}release(t){this.releaseEmitter.emit("release",this.useDefaultTokens?"1":t)}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}pendingCount(){return this.waiting.length}},Gt=require("custom-ability"),Qt=require("util-ex"),Xt=class extends AbortController{constructor(t){super(),(0,Qt.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new p.AbortError(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new p.AbortError(e.reason||"aborted")}}},Yt=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){const t=this._maxTaskConcurrency;let e=this.__task_semaphore;return t>0&&!e&&(e=this.__task_semaphore=new Ht(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(ae);let r=this.__task_aborter;if(r&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".isAborted",p.ErrorCode.InvalidArgument);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(ae);let r=this.__task_aborter;if(r&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".getRunningTask",p.ErrorCode.InvalidArgument);r=r[t]}return r?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,r=void 0),r}getRunningTaskCount(){let t;if(this.hasAsyncFeature(ae)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,r])=>{if(!r?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const r=this.super,n=this.self||this;return t=r?r.call(n,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,r=!0){const n=this.hasAsyncFeature(ae);if(!n&&r&&this.getRunningTask())throw new p.CommonError("The task is running",this.name,p.ErrorCode.TooManyRequests);const s=t?.aborter||new Xt(this);if(!(s instanceof Xt)){if(!(s instanceof AbortController))throw new p.CommonError("aborter should be an AbortController",this.name,p.ErrorCode.InvalidArgument);Object.setPrototypeOf(s,new Xt(this))}if(n){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const r=this.super,n=this.self||this;r?r.call(n,t,e):n._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(ae)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,r){const n=this.createAborter(e,r?.taskId,r?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=n);let s=t(e,n).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(n)},r=function(t){const e=t||{};return new TransformStream({async start(t){const r=t.error;if(t.error=n=>{r.call(t,n),e.onError&&e.onError(n)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,r){try{let n;e.onTransform&&(n=await e.onTransform(t,r)),n||(n=t),r.enqueue(n)}catch(t){r.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,Qt.defineProperty)(n,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=n.id),t)});t=t.pipeThrough(r)}else this.cleanTaskAborter(n);return t})).catch((t=>{throw this.cleanTaskAborter(n),t})).finally((()=>{n.timeoutId&&(clearTimeout(n.timeoutId),n.timeoutId=void 0)}));return s.task=n,s}runAsyncCancelableTask(t={},e,r){let n=this.createTaskPromise(e,t,r);const s=this.semaphore;if(s){const t=n,e=t.task;n=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),n.task=e}return n}abort(t,e){let r=this.__task_aborter;if(r){const n=r;if(this.hasAsyncFeature(ae)){const t=e?.taskId;if(null==t)throw new p.CommonError("Missing data.taskId",this.name+".abort",p.ErrorCode.InvalidArgument);r=r[t],this.cleanMultiTaskAborter(t,n)}else this.__task_aborter=void 0;r&&!r.signal.aborted&&r.abort(t,e)}}};Yt.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Yt.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,Gt.createAbilityInjector)(Yt,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=ce.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}}),c(require("memoizee")),require("json-canonicalize");var te=c(require("path")),ee=require("pkg-dir");require("util-ex");var re,ne=c(require("path")),se=require("url"),ie=(require("@xenova/transformers"),(0,se.fileURLToPath)(h)),oe=ne.default.dirname(ie),ae=(ne.default.join(function(t){const e=(0,ee.packageDirectorySync)({cwd:t});if(e)return e;const r=t.split(te.default.sep);let n=r.lastIndexOf("dist");if(n>0)return r.slice(0,n).join(te.default.sep);if(n=r.lastIndexOf("src"),n>0)return r.slice(0,n).join(te.default.sep);throw new Error("can not find package directory")}(oe),".cache"),require("yaml"),0),ce=((re=ce||{})[re.MultiTask=1<<ae]="MultiTask",re[re.Cancelable=2]="Cancelable",re[re.Priority=4]="Priority",re),ue=class t extends f.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const r in this.list()){const n=this.get(r);let s=n.tags;if("string"==typeof s){if(s===t){e=n;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=n;break}}return e}static getAllByTag(t){let e=[];for(const r in this.list()){const n=this.get(r);let s=n.tags;"string"==typeof s?s===t&&e.push(n):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(n)}return e}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),Lt.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new p.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new p.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const r=this.get(t);if(r)return r.runWithPos(...e);throw new p.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new p.NotFoundError(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,r={}){switch(typeof e){case"string":r.name=e;break;case"function":r.func=e;break;case"object":r=e}e=r.name;let n=!!this.get(e);if(n)n=!1;else{if(!(r instanceof t))return n=new this(r),n.register();this.items[e]=r,n=r}return n}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,r=this.depends;if(r){const e=Object.keys(r);for(const n of e){const e=r[n];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={},r=Object.keys(this.params);let n=Math.min(r.length,t.length);for(let s=0;s<n;s++)e[r[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const r=Object.keys(t);let n=Math.min(r.length,this.params.length);for(let s=0;s<n;s++)e.push(t[r[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,p.throwError)("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)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(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)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Lt.has(e,t)}isStream(t){return this.stream}},he={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,w._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"}};ue.defineProperties(ue,he);var le=class extends ue{constructor(){super(...arguments),this._emitter=new l.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},fe=new le(Mt),we=require("secondary-cache");function pe({key:t,value:e,options:r}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,r):this.cache.get(t):(r&&this.cache.setDefaultOptions(r),this.cache)}function de(t,e){let r=ue.get(t);return r||(r=new ue(t,{func:pe,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"}),r.cache=new we.Cache(e)),r}var ye=de("lrucache"),me=class t extends ue{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(0,p.throwError)("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const r in e){const n=this.get(r),s=e[r];n?n instanceof t?n.assign(s):(0,p.throwError)(`${r} already registered as ${n.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const r=this.get(t);if(r&&r.fetch)return r.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,r){const n={...this.fetchOptions};let s;n.headers&&n.headers["Content-Type"]||(n.headers={"Content-Type":"application/json",...n.headers}),t?.stream&&!n.headers.Connection&&(n.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),r?("string"!=typeof r&&(r=JSON.stringify(r)),r=this.name+"/"+r):r=this.name,n.method=e.toUpperCase(),"get"===e||"delete"===e?s=r+this.getUrlParams(t):(n.body=JSON.stringify(t),s=r);const i=await fetch(`${this.apiRoot}/${s}`,n);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,r=t.status,n=t.statusText,s=this.name;if(t.body){const r=await t.text();try{const t=JSON.parse(r);t&&(t.error&&(n=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=n,n=e.what)),t.message&&(n=n+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return(0,p.createError)(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},be={...y};me.defineProperties(me,be);var ge=class extends me{async _func(t,e){const r=await this.fetch(e,t);if(e?.stream)return r;return await r.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))}}},Ee={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};ge.defineProperties(ge,Ee);var xe=class extends ge{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||(0,p.throwError)("id is required"),"string"==typeof r&&(r=encodeURIComponent(r)),delete t.id,super.fetch(t,e,r)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},ve=class extends xe{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=qt,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}):"",r=`${this.apiRoot}/${this.name}${e}`,n=this._es=new EventSource(r);return Object.entries(this._sseEvents).forEach((([t,e])=>{n.addEventListener(t,e)})),this._esEvents=t,n}esListener(t){const e=t.data?JSON.parse(t.data):void 0,r=t.type;if(!this._forwardEvents.has(r)){const t=this.emitter;t&&e&&r&&(Array.isArray(e)?t.emit(r,...e):t.emit(r,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const r=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);r.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)}},ke=new ve(qt),Se=require("util-ex"),$e=class t extends ue{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];(n instanceof t||n.isApi)&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}func({}){}},je={...y};$e.defineProperties($e,je);var Oe=class extends $e{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const r=this.methods=[];this.initRpcMethods(r)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const r of e)"function"==typeof this[r]&&t.push(r);(0,Se.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const r=e.slice(1);void 0===this[r]&&(this[r]=this[e])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new p.NotFoundError(e,this.name)}};Oe.defineProperties(Oe,{methods:{type:"array"}});var Ce=class extends Oe{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=d}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}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},Ae=fe.runSync(),qe=class t extends Ce{constructor(){super(...arguments),this.name=qt,this.description="subscribe server sent event",this.result="event",this.depends={[Mt]:fe}}static get sse(){return this._sse||(this._sse=new It),this._sse}get sse(){return this.constructor.sse}static publish(e,r){return t.sse.publish(e,r)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,r,n){return t.sse.subscribe(e,r,n)}static alreadyForward(e){const r=Ae.listeners(e);for(const e of r)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,r){return"string"==typeof r&&(r=[r]),this.constructor.subscribe(t,e,r)}forward(e){Array.isArray(e)||(e=[e]);for(const r of e)t.alreadyForward(r)||Ae.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)Ae.off(r,t.ebListener)}list({_req:t,_res:e,event:r}){t&&e&&this.subscribeSSE(t,e,r)}$sub({event:t}){if(t)return this.forward(t),{event:t};(0,p.throwError)("event is required","sub",p.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,p.throwError)("event is required","unsub",p.ErrorCode.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const r of t)this.publishSSE(e,r);return{event:t}}(0,p.throwError)("event or data is required","pub",p.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},Me=new qe(qt);function Te(){fe.register(),ye.register()}
package/dist/funcs.mjs CHANGED
@@ -1 +1 @@
1
- import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as L,eventClient as c,eventServer as h,lrucache as i,registerCoreTools as j}from"./chunk-FLVJ4R53.mjs";import"./chunk-PXQPLL62.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,L as event,c as eventClient,h as eventServer,i as lrucache,j as registerCoreTools};
1
+ import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as c,eventClient as h,eventServer as i,lrucache as j,registerCoreTools as k}from"./chunk-JHHFTTVE.mjs";import"./chunk-VIG2GB47.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,c as event,h as eventClient,i as eventServer,j as lrucache,k as registerCoreTools};
@@ -228,6 +228,13 @@ declare class SSEChannel {
228
228
  getSubscriberCount(): number;
229
229
  }
230
230
 
231
+ declare global {
232
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
233
+ interface SymbolConstructor {
234
+ readonly observable: symbol;
235
+ }
236
+ }
237
+
231
238
  interface ClientFuncItem extends RemoteFuncItem {
232
239
  }
233
240
  declare interface ClientTools extends ClientFuncItem {
@@ -228,6 +228,13 @@ declare class SSEChannel {
228
228
  getSubscriberCount(): number;
229
229
  }
230
230
 
231
+ declare global {
232
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
233
+ interface SymbolConstructor {
234
+ readonly observable: symbol;
235
+ }
236
+ }
237
+
231
238
  interface ClientFuncItem extends RemoteFuncItem {
232
239
  }
233
240
  declare interface ClientTools extends ClientFuncItem {