@isdk/ai-tool 0.5.7 → 0.6.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 (292) hide show
  1. package/dist/chunk-OYDBRUZJ.mjs +1 -0
  2. package/dist/funcs.js +1 -1
  3. package/dist/funcs.mjs +1 -1
  4. package/dist/index.d.mts +11 -637
  5. package/dist/index.d.ts +11 -637
  6. package/dist/index.js +1 -1
  7. package/dist/index.mjs +1 -1
  8. package/docs/classes/BinarySemaphore.md +25 -25
  9. package/docs/classes/CancelableAbility.md +25 -25
  10. package/docs/classes/ClientTools.md +57 -57
  11. package/docs/classes/ConfigFile.md +78 -262
  12. package/docs/classes/EnvPromptTemplate.md +233 -36
  13. package/docs/classes/EventClient.md +80 -80
  14. package/docs/classes/EventServer.md +81 -81
  15. package/docs/classes/EventToolFunc.md +49 -49
  16. package/docs/classes/FStringPromptTemplate.md +234 -37
  17. package/docs/classes/FewShotPromptTemplate.md +213 -34
  18. package/docs/classes/GolangPromptTemplate.md +230 -33
  19. package/docs/classes/IntSet.md +12 -12
  20. package/docs/classes/PromptExampleSelector.md +9 -9
  21. package/docs/classes/PromptTemplate.md +230 -34
  22. package/docs/classes/ReadableStreamError.md +2 -2
  23. package/docs/classes/ResClientTools.md +64 -64
  24. package/docs/classes/ResServerTools.md +65 -65
  25. package/docs/classes/SSEChannel.md +16 -16
  26. package/docs/classes/Semaphore.md +26 -26
  27. package/docs/classes/ServerTools.md +53 -53
  28. package/docs/classes/SignalGate.md +9 -9
  29. package/docs/classes/TaskAbortController.md +8 -8
  30. package/docs/classes/ToolFunc.md +46 -46
  31. package/docs/classes/YamlTypeBaseObject.md +2 -2
  32. package/docs/enumerations/AsyncFeatureBits.md +4 -4
  33. package/docs/enumerations/AsyncFeatures.md +4 -4
  34. package/docs/enumerations/HashAlgorithm.md +12 -12
  35. package/docs/functions/AIArgProcessor.md +1 -1
  36. package/docs/functions/AIStream.md +1 -1
  37. package/docs/functions/ChoiceArgProcessor.md +1 -1
  38. package/docs/functions/ObjectArgsToArgsInfo.md +1 -1
  39. package/docs/functions/RateLimit.md +1 -1
  40. package/docs/functions/TemplateArgProcessor.md +1 -1
  41. package/docs/functions/assignDirs.md +1 -1
  42. package/docs/functions/backendEventable.md +1 -1
  43. package/docs/functions/beforeShutdown.md +1 -1
  44. package/docs/functions/completeSentences.md +1 -1
  45. package/docs/functions/concatText.md +1 -1
  46. package/docs/functions/countLLMTokens.md +1 -1
  47. package/docs/functions/countRegexMatches.md +1 -1
  48. package/docs/functions/createCallbacksTransformer.md +1 -1
  49. package/docs/functions/createEmptyReadableStream.md +1 -1
  50. package/docs/functions/createEndWithRepetitionDetector.md +1 -1
  51. package/docs/functions/createEventStreamTransformer.md +1 -1
  52. package/docs/functions/createHfValueFunc.md +1 -1
  53. package/docs/functions/createLRUCache.md +1 -1
  54. package/docs/functions/createYamlObjectTag.md +1 -1
  55. package/docs/functions/dateToText.md +1 -1
  56. package/docs/functions/decodeCharset.md +1 -1
  57. package/docs/functions/detectCharset.md +1 -1
  58. package/docs/functions/encodeLLMTokens.md +1 -1
  59. package/docs/functions/ensureQuoted.md +1 -1
  60. package/docs/functions/expandConfig.md +3 -3
  61. package/docs/functions/expandEnv.md +4 -4
  62. package/docs/functions/expandObjEnv.md +4 -4
  63. package/docs/functions/expandPath.md +1 -1
  64. package/docs/functions/extNameLevel.md +1 -1
  65. package/docs/functions/fileIsExists.md +1 -1
  66. package/docs/functions/filterValidFnScope.md +1 -1
  67. package/docs/functions/findIndexNonEmptyFrom.md +1 -1
  68. package/docs/functions/findPort.md +1 -1
  69. package/docs/functions/formatTextWithSpace.md +1 -1
  70. package/docs/functions/getAllEnumKeys.md +1 -1
  71. package/docs/functions/getConfigFileNames.md +1 -1
  72. package/docs/functions/getConfigs.md +1 -1
  73. package/docs/functions/getEnvVairables.md +1 -1
  74. package/docs/functions/getFileMetaInfo.md +1 -1
  75. package/docs/functions/getHashAlgoBySize.md +1 -1
  76. package/docs/functions/getKeysPath.md +1 -1
  77. package/docs/functions/getLLMTokenizer.md +1 -1
  78. package/docs/functions/getMultiLevelExtname.md +4 -4
  79. package/docs/functions/getPackageDir.md +1 -1
  80. package/docs/functions/getRealFilepath.md +1 -1
  81. package/docs/functions/getResponseErrorReadableStream.md +1 -1
  82. package/docs/functions/getXDGConfigs.md +1 -1
  83. package/docs/functions/hasDirectoryIn.md +1 -1
  84. package/docs/functions/hash.md +1 -1
  85. package/docs/functions/hashFile.md +1 -1
  86. package/docs/functions/hashStream.md +1 -1
  87. package/docs/functions/initShutdown.md +1 -1
  88. package/docs/functions/isLangUsingSpaces.md +1 -1
  89. package/docs/functions/isListItemString.md +1 -1
  90. package/docs/functions/isModelNameMatched.md +1 -1
  91. package/docs/functions/isPunctuationChar.md +1 -1
  92. package/docs/functions/isQuoted.md +1 -1
  93. package/docs/functions/isRegExp.md +1 -1
  94. package/docs/functions/isSameString.md +1 -1
  95. package/docs/functions/isSectionString.md +1 -1
  96. package/docs/functions/isSentenceEnding.md +1 -1
  97. package/docs/functions/isSepLineString.md +1 -1
  98. package/docs/functions/isStrWrapped.md +1 -1
  99. package/docs/functions/isSubdirectory.md +1 -1
  100. package/docs/functions/isTitleString.md +1 -1
  101. package/docs/functions/isValidFilename.md +1 -1
  102. package/docs/functions/isValidFilepath.md +1 -1
  103. package/docs/functions/isWebStream.md +1 -1
  104. package/docs/functions/jsonFilterToWhere.md +1 -1
  105. package/docs/functions/jsonToMarkdownStr.md +1 -1
  106. package/docs/functions/loadAIConfig.md +1 -1
  107. package/docs/functions/loadConfig.md +1 -1
  108. package/docs/functions/loadConfigFile.md +1 -1
  109. package/docs/functions/loadFileFromPaths.md +1 -1
  110. package/docs/functions/loadTextFromPaths.md +1 -1
  111. package/docs/functions/lrucache.md +1 -1
  112. package/docs/functions/makeToolFuncCancelable.md +1 -1
  113. package/docs/functions/matchUrlProtocol.md +1 -1
  114. package/docs/functions/memoize.md +1 -1
  115. package/docs/functions/messagesToText.md +1 -1
  116. package/docs/functions/paramsSizeToScaleStr.md +1 -1
  117. package/docs/functions/parseCommand.md +1 -1
  118. package/docs/functions/parseJsJson.md +1 -1
  119. package/docs/functions/parseJsJsonSimpleSync.md +1 -1
  120. package/docs/functions/parseObjectArgInfo.md +1 -1
  121. package/docs/functions/parseObjectArgumentInfos.md +1 -1
  122. package/docs/functions/parseObjectArguments.md +1 -1
  123. package/docs/functions/parseObjectArgumentsAsArgInfos.md +1 -1
  124. package/docs/functions/parseYaml.md +21 -1
  125. package/docs/functions/quoteStr.md +1 -1
  126. package/docs/functions/readFilenamesRecursiveSync.md +7 -1
  127. package/docs/functions/readTextFileChunks.md +1 -1
  128. package/docs/functions/readTextFileChunksEx.md +1 -1
  129. package/docs/functions/readableFromAsyncIterable.md +1 -1
  130. package/docs/functions/registerCoreTools.md +1 -1
  131. package/docs/functions/registerYamlTag.md +18 -2
  132. package/docs/functions/removeMarkdownBold.md +1 -1
  133. package/docs/functions/removeMarkdownBoldAndItalic.md +1 -1
  134. package/docs/functions/removeMarkdownItalic.md +1 -1
  135. package/docs/functions/replaceWithPlaceholder.md +1 -1
  136. package/docs/functions/restoreFromPlacehoders.md +1 -1
  137. package/docs/functions/sanitizeFilename.md +4 -4
  138. package/docs/functions/sanitizeFilepath.md +4 -4
  139. package/docs/functions/saveConfigFile.md +1 -1
  140. package/docs/functions/scaleStrToParamsSize.md +1 -1
  141. package/docs/functions/shutdown.md +1 -1
  142. package/docs/functions/simplifyObjectArguments.md +1 -1
  143. package/docs/functions/sortedValues.md +1 -1
  144. package/docs/functions/splitChunks.md +1 -1
  145. package/docs/functions/splitParagraph.md +1 -1
  146. package/docs/functions/splitSentence.md +1 -1
  147. package/docs/functions/stringifyYaml.md +21 -1
  148. package/docs/functions/stripConsoleColor.md +1 -1
  149. package/docs/functions/textToDate.md +1 -1
  150. package/docs/functions/toDateTime.md +1 -1
  151. package/docs/functions/trimStartOfStreamHelper.md +1 -1
  152. package/docs/functions/truncTo.md +1 -1
  153. package/docs/functions/truncateByToken.md +1 -1
  154. package/docs/functions/truncateToTokenLimit.md +1 -1
  155. package/docs/functions/truncateToTokenLimitEx.md +1 -1
  156. package/docs/functions/uuid.md +1 -1
  157. package/docs/functions/wait.md +1 -1
  158. package/docs/functions/xxhash.md +1 -1
  159. package/docs/functions/xxhash32.md +1 -1
  160. package/docs/functions/xxhash64.md +1 -1
  161. package/docs/functions/xxhashAsStr.md +1 -1
  162. package/docs/globals.md +0 -23
  163. package/docs/interfaces/AIChatAssistantMessageParam.md +12 -12
  164. package/docs/interfaces/AIChatContentPartImage.md +3 -3
  165. package/docs/interfaces/AIChatContentPartText.md +3 -3
  166. package/docs/interfaces/AIChatMessageParamBase.md +7 -7
  167. package/docs/interfaces/AIChatMessageToolCall.md +4 -4
  168. package/docs/interfaces/AIChatSystemMessageParam.md +9 -9
  169. package/docs/interfaces/AIChatToolChoiceFuncObject.md +3 -3
  170. package/docs/interfaces/AIChatToolChoiceObject.md +2 -2
  171. package/docs/interfaces/AIChatToolFunc.md +5 -5
  172. package/docs/interfaces/AIChatToolFuncParam.md +3 -3
  173. package/docs/interfaces/AIChatToolMessageParam.md +10 -10
  174. package/docs/interfaces/AIChatToolParam.md +2 -2
  175. package/docs/interfaces/AIChatToolTypeObject.md +2 -2
  176. package/docs/interfaces/AIChatUserMessageParam.md +13 -13
  177. package/docs/interfaces/AIChoiceConfig.md +8 -8
  178. package/docs/interfaces/AIResult.md +6 -6
  179. package/docs/interfaces/AIStreamParser.md +2 -2
  180. package/docs/interfaces/AIStreamParserOptions.md +2 -2
  181. package/docs/interfaces/BaseFunc.md +11 -11
  182. package/docs/interfaces/BaseFuncItem.md +10 -10
  183. package/docs/interfaces/BinarySemaphoreAcquireOptions.md +2 -2
  184. package/docs/interfaces/BinarySemaphoreOptions.md +5 -5
  185. package/docs/interfaces/BinarySemaphoreReleaseOptions.md +2 -2
  186. package/docs/interfaces/BinarySemaphoreReleaserFunc.md +3 -3
  187. package/docs/interfaces/CancelableAbilityOptions.md +4 -4
  188. package/docs/interfaces/ClientFuncItem.md +13 -13
  189. package/docs/interfaces/EventClientFuncParams.md +5 -5
  190. package/docs/interfaces/EventServerFuncParams.md +6 -6
  191. package/docs/interfaces/FewShotPromptTemplateOptions.md +12 -12
  192. package/docs/interfaces/FuncItem.md +11 -11
  193. package/docs/interfaces/FuncParam.md +7 -7
  194. package/docs/interfaces/FuncParams.md +1 -1
  195. package/docs/interfaces/Funcs.md +1 -1
  196. package/docs/interfaces/HashAlgoParams.md +4 -4
  197. package/docs/interfaces/IFileMetaInfo.md +8 -8
  198. package/docs/interfaces/IReadTextFileChunksOptions.md +11 -11
  199. package/docs/interfaces/ITruncateToTokenLimitOptions.md +10 -10
  200. package/docs/interfaces/JsonFilter.md +1 -1
  201. package/docs/interfaces/ParseObjectArgumentOptions.md +11 -11
  202. package/docs/interfaces/PromptExampleSelectorOptions.md +3 -3
  203. package/docs/interfaces/PromptTemplateOptions.md +7 -7
  204. package/docs/interfaces/RemoteFuncItem.md +13 -13
  205. package/docs/interfaces/ReplacePlacehoderOptions.md +5 -5
  206. package/docs/interfaces/ResClientFuncParams.md +3 -3
  207. package/docs/interfaces/ResServerFuncParams.md +6 -6
  208. package/docs/interfaces/SanitizeFilenameOptions.md +3 -3
  209. package/docs/interfaces/SectionStringOptions.md +3 -3
  210. package/docs/interfaces/SemaphoreOptions.md +7 -7
  211. package/docs/interfaces/SemaphoreTaskItem.md +5 -5
  212. package/docs/interfaces/ServerFuncItem.md +14 -14
  213. package/docs/interfaces/ServerFuncParams.md +3 -3
  214. package/docs/interfaces/SplitSentenceOptions.md +5 -5
  215. package/docs/interfaces/StreamCallbacksAndOptions.md +5 -5
  216. package/docs/interfaces/TaskAbortControllers.md +1 -1
  217. package/docs/interfaces/TaskPromise.md +2 -2
  218. package/docs/interfaces/ToolFuncPackage.md +4 -4
  219. package/docs/type-aliases/AIChatContentPart.md +1 -1
  220. package/docs/type-aliases/AIChatMessageParam.md +1 -1
  221. package/docs/type-aliases/AIChatRole.md +1 -1
  222. package/docs/type-aliases/AIChatToolChoiceParam.md +1 -1
  223. package/docs/type-aliases/AIMessageType.md +1 -1
  224. package/docs/type-aliases/AIModelNameRule.md +1 -1
  225. package/docs/type-aliases/AIModelNameRuleFn.md +1 -1
  226. package/docs/type-aliases/AIModelNameRules.md +1 -1
  227. package/docs/type-aliases/AITextGenerationFinishReason.md +1 -1
  228. package/docs/type-aliases/ActionName.md +1 -1
  229. package/docs/type-aliases/AsyncTaskId.md +1 -1
  230. package/docs/type-aliases/BeforeShutdownListener.md +1 -1
  231. package/docs/type-aliases/EventErrorListenerFn.md +1 -1
  232. package/docs/type-aliases/EventListenerFn.md +1 -1
  233. package/docs/type-aliases/FuncParamType.md +1 -1
  234. package/docs/type-aliases/PromptExamples.md +1 -1
  235. package/docs/type-aliases/SemaphoreIsReadyFuncType.md +1 -1
  236. package/docs/type-aliases/TFunc.md +1 -1
  237. package/docs/variables/AIChatRoles.md +1 -1
  238. package/docs/variables/AIMessageTypes.md +1 -1
  239. package/docs/variables/AITextGenerationFinishReasons.md +1 -1
  240. package/docs/variables/ActionNames.md +1 -1
  241. package/docs/variables/ClientToolFuncSchema.md +1 -1
  242. package/docs/variables/DEFAULT_CONFIG_NAME.md +1 -1
  243. package/docs/variables/DefaultAsyncSemaphoreCapacity.md +1 -1
  244. package/docs/variables/EventBusName.md +1 -1
  245. package/docs/variables/EventName.md +1 -1
  246. package/docs/variables/FilenameReservedRegex.md +1 -1
  247. package/docs/variables/LLM_TOKENIZER_NAMES.md +1 -1
  248. package/docs/variables/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  249. package/docs/variables/PASSING_SCORE.md +1 -1
  250. package/docs/variables/RStreamErrCode.md +1 -1
  251. package/docs/variables/RemoteToolFuncSchema.md +1 -1
  252. package/docs/variables/ResponseRStreamErrCode.md +1 -1
  253. package/docs/variables/SHUTDOWN_SIGNALS.md +1 -1
  254. package/docs/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
  255. package/docs/variables/SecondaryCache.md +1 -1
  256. package/docs/variables/ServerToolFuncSchema.md +1 -1
  257. package/docs/variables/ToolAsyncCancelableBit.md +1 -1
  258. package/docs/variables/ToolAsyncMultiTaskBit.md +1 -1
  259. package/docs/variables/ToolAsyncPriorityBit.md +1 -1
  260. package/docs/variables/ToolFuncSchema.md +1 -1
  261. package/docs/variables/WindowsReservedNameRegex.md +1 -1
  262. package/docs/variables/base32768.md +1 -1
  263. package/docs/variables/defaultTemplateFormat.md +2 -2
  264. package/docs/variables/event.md +1 -1
  265. package/docs/variables/eventClient.md +1 -1
  266. package/docs/variables/eventServer.md +1 -1
  267. package/docs/variables/lrucache.md +1 -1
  268. package/package.json +5 -3
  269. package/dist/chunk-XLXW6OPN.mjs +0 -1
  270. package/docs/classes/HFEnvironment.md +0 -184
  271. package/docs/classes/HFInterpreter.md +0 -77
  272. package/docs/classes/HFTemplate.md +0 -67
  273. package/docs/classes/HfPromptTemplate.md +0 -1158
  274. package/docs/functions/filenameReservedRegex.md +0 -20
  275. package/docs/functions/hfParse.md +0 -24
  276. package/docs/functions/hfTokenize.md +0 -27
  277. package/docs/functions/interpolateEnv.md +0 -29
  278. package/docs/functions/interpolateFString.md +0 -29
  279. package/docs/functions/interpolateGolangTemplate.md +0 -35
  280. package/docs/functions/parseFString.md +0 -26
  281. package/docs/functions/reControlCharsRegex.md +0 -19
  282. package/docs/interfaces/DotenvExpandOptions.md +0 -43
  283. package/docs/interfaces/DotenvExpandOutput.md +0 -25
  284. package/docs/interfaces/DotenvParseInput.md +0 -13
  285. package/docs/interfaces/DotenvParseOutput.md +0 -13
  286. package/docs/interfaces/DotenvPopulateInput.md +0 -13
  287. package/docs/type-aliases/FStringPromptTemplateNode.md +0 -14
  288. package/docs/type-aliases/PromptTemplateType.md +0 -11
  289. package/docs/type-aliases/PromptType.md +0 -11
  290. package/docs/variables/HFBuiltins.md +0 -122
  291. package/docs/variables/PromptTemplateTypes.md +0 -11
  292. package/docs/variables/PromptTypes.md +0 -14
@@ -0,0 +1 @@
1
+ import{EventEmitter as t}from"events-ex";import{AdvancePropertyManager as e}from"property-manager";import{_createFunction as n}from"util-ex";import{AbortError as i,AbortErrorCode as r,AlreadyExistsError as s,AlreadyExistsErrorCode as o,BaseError as a,CommonError as c,createError as u,ErrorCode as h,InternalErrorCode as f,NotFoundErrorCode as l,NotFoundError as m,NotImplementedErrorCode as p,NotImplementationError as d,throwError as y}from"@isdk/common-error";import{createAbilityInjector as w}from"custom-ability";import{toRegExp as v}from"util-ex";var g=.618,b=["get","post","put","delete","patch","list","res"],k={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,i,r)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}};import{format as $,parse as x,parseISO as E}from"date-fns";import{formatISO as S,parseISO as A,toDate as T}from"date-fns";var j="MMMM d, y 'at' h:m:s b 'GMT'x";function O(t){let e;try{"string"==typeof t?e=E(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function N(t,e=j){return x(t,e,new Date)}function I(t,e=j){return $(t,e)}var C=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],R=["human","ai","generic","system","tool"],M=["user","assistant","system","tool","tool_calls"];function z(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=O(t);n&&(e+=" ["+I(n)+"]")}e+=" "+n.content+"\n"}return e}import{StringTemplate as L,EnvStringTemplate as _,FStringTemplate as X,GolangStringTemplate as F,expandEnv as P,expandObjEnv as D,defaultTemplateFormat as B,getEnvVairables as q,createHfValueFunc as G}from"@isdk/template-engines";import{StringTemplate as U}from"@isdk/template-engines";function J(t){return Object.keys(t).sort().map((e=>t[e]))}var W=class extends U{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 U?t.examplePrompt:U.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=J(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),i=this.templateFormat;return await U.format({template:n,data:t,templateFormat:i})}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}};function H(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}U.register(W,{name:"fewshot",aliases:["few_shot"]});var Z=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{Z=t}));var K=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var i;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(i=t,Z?i:H(i))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}};import{detectTextLanguage as Q}from"@isdk/detect-text-language";var V=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,Y=/([A-Z][a-z]{1,2}\.)\s(\w)/g,tt=/(\.[a-zA-Z]\.)\s(\w)/g,et=new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),nt=new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g"),it=/(```)([\s\S]*?)(```)/g,rt=">>>CODE_BLOCK<<<",st=/([*_`]{1,3})(\S.*?\S)\1/,ot=/>>> INLINE_BLOCK (\d+) <<</,at=1e4;function ct(t,e,n){const i="$1"+e+"$2";let r=t;for(let t=0;t<n.length;t++)r=r.replace(n[t],i);return r}function ut(t,{best:e=!0,completeSentence:n,isMarkdown:i,ignoreEmptyLine:r}={}){const s=[],o=[];let a,c=0;for(;c++<at&&(a=it.exec(t));){const e=a[0];s.push(e),t=t.replace(e,"\n"+rt+(s.length-1)+"\n")}for(c=0;c++<at&&(a=st.exec(t));){const e=a[0];o.push(e),t=t.replace(e,">>> INLINE_BLOCK "+(o.length-1)+" <<<")}if(i){const e=t.split("\n");for(let t=0;t<e.length;t++){const n=e[t];pt(n,{isMarkdown:i,nextLine:e[t+1]})&&(s.push(n),e[t]=rt+(s.length-1))}t=e.join("\n")}const u=(t=(t=(t=(t=(t=t.replace(/([。!??])\1+/g,"$1")).replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let h=[];for(let t=0;t<u.length;t++){let n=u[t].trimEnd();if(!n){!i&&r||h.push("");continue}if(n.startsWith(rt)){h.push(s[Number(n.slice(16))]);continue}if(i&&pt(n,{isMarkdown:i,nextLine:u[t+1]})){h.push(n);continue}if(!e){h.push(n);continue}let a=ct(n,"@",[Y,tt]),c=Array.from(a.matchAll(V)),f=[];if(c.length)for(let t=0;t<c.length;t++)f.push(ct(c[t][0]," ",[et,nt]));else f.push(n);h.push(...f.map((t=>vt(o,t))))}return n&&(h=ht(h,{isMarkdown:i,ignoreEmptyLine:r})),h}function ht(t,{isMarkdown:e,ignoreEmptyLine:n}={}){const i=[];let r=0,s="";for(n=!e&&n;r<t.length;){let c=t[r];if(c){let u;if(n){const n=bt(t,r+1);u=mt(t[n],{isMarkdown:e,nextLine:-1===n?"":t[n+1]})}else u=mt(t[r+1],{isMarkdown:e,nextLine:t[r+2]});o=c,a={isMarkdown:e,nextLine:t[r+1]},lt(o)||mt(o,a)||""===t[r+1]||u?(s&&(c=ft(s,c),s=""),i.push(c)):(s&&(c=ft(s,c)),s=c)}else n||i[i.length-1]&&i.push(c);r++}var o,a;return s&&i.push(s),i}function ft(t,e){const n=t+" "+e,i=Q(n,{isoCode:!0});return i&&!gt(i)?(wt(t)&&(t+=" "),e=t+e):e=t.endsWith("-")?(t=t.slice(0,-1))+e:n,e}function lt(t){if(!t)return!1;return/(([.。!!??]\s*['"”’]?)|```)\s*$/.test(t)}function mt(t,e){let n=pt(t,e);return n||(n=dt(t)),n||(n=yt(t)),n}function pt(t,e){if(!t)return null;let n=/^\s*第?\s*[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十百千萬万\d]+\s*([章節节编回部篇卷幕场場辑集段册冊期片題]|片段|段落|篇[章目]|小[节節]|(子)?部分|卷[册冊]|[单單]元|章[节節回]|[.、])[ \t]*(?<title>.*)(?=\n|$)/.exec(t);if(n||(n=/^\s*(Chapter|Book|Article|Part|Paragraph|Subsection|Subpart|Volume|Episode|Issue|Unit|Section|Segment|Act|Scene)\s*\d+.*(?=\n|$)/i.exec(t)),!n&&e?.isMarkdown){n=/^[ \t]{0,3}(#+)\s+(?<title>\S.*)$/.exec(t);const i=/^[ \t]{0,3}([-=]+)(?=\n|$)/;!n&&e.nextLine&&!i.test(t)&&/^[ \t]{0,3}\S/.test(t)&&i.test(e.nextLine)&&(n=/^\s*(?<title>.*)(?=\n|$)/.exec(t))}return n}function dt(t){return/^\s*([*+-]|\d+[.、])\s*(?<item>.*)(?=\n|$)/.exec(t)}function yt(t){return/^[-=_]{3,}$/.exec(t)}function wt(t){return/[。!??,、;;::'""“”‘’~~《》<>〈〉【】(){}【】\[\]\(\)…·]$/.test(t)}function vt(t,e){let n,i=0;for(;i++<at&&(n=ot.exec(e));){const i=Number(n[1]);e=e.replace(n[0],t[i])}return e}function gt(t){return!["zh","ja","th","lo","ta","ko"].includes(t)}function bt(t,e=0){for(let n=e;n<t.length;n++){const e=t[n];if(null!=e&&""!==e)return n}return-1}function kt(t,e){const n=/(?!\\)([*_])\1(?![ \t]|\1)(.+?)(?<!\\)\1{2}/;let i;for(;(i=n.exec(t))&&(t=t.slice(0,i.index)+i[2]+t.slice(i.index+i[0].length),!e););return t}function $t(t,e){const n=/(?!\\)([*_])(?![ \t]|\1)(.+?)(?<!\\)\1/;let i;for(;(i=n.exec(t))&&(t=t.slice(0,i.index)+i[2]+t.slice(i.index+i[0].length),!e););return t}function xt(t,e){return t=$t(t=kt(t,e),e)}function Et(t,e){const n=[],i=[],r=t.split("\n");for(let t=0;t<r.length;t++){let s=r[t];const o=0===s.trim().length;o||pt(s,{...e,nextLine:r[t+1]})?(i.length&&n.push([...i]),i.length=0,o||i.push(s)):i.push(s)}return i.length&&n.push([...i]),n}function St(t,e=2,n=.5){const i=10**e;return Math.trunc((t+Number.EPSILON+n/i)*i)/i}async function At(t){return new Promise((e=>setTimeout(e,t)))}import{createAbilityInjector as Tt}from"custom-ability";import{EventEmitter as jt,eventable as Ot,states as Nt,wrapEventEmitter as It}from"events-ex";var Ct="event",Rt="event-bus";var Mt=Tt((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Rt)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.on(e,n)}once(e,n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.once(e,n)}off(e,n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.off(e,n)}emit(e,...n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):i.emit.call(this,e,this.name,...n)}emitError(e,...n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emitAsync.call(this,e,this.name,...n)}}}),!0);function zt(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Lt=498,_t=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let n,i;this.active||y("Channel closed","SSEChannel",498);let r=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(r=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",n="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:r,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!r||zt(t.events,r))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e,n){this.active||y("Channel closed","SSEChannel",498);const i={req:t,res:e,events:n},r=this.options.maxStreamDuration;let s="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";r>0&&(s+=", s-maxage="+(Math.floor(r/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":s,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),i.req.socket.setNoDelay(!0),i.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=>zt(i.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),i.res.write(a),this.clients.add(i),r>0&&setTimeout((()=>{i.res.writableEnded||this.unsubscribe(i)}),r),i.res.on("close",(()=>this.unsubscribe(i))),i}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++})),t}getSubscriberCount(){return this.clients.size}};function Xt(t){return t instanceof ReadableStream||t instanceof WritableStream}var Ft=600,Pt=601,Dt=class extends a{constructor(t,e=600){super(t,500)}};function Bt(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:i}=await e.read();if(!n){const e=(new TextDecoder).decode(i);t.error(new Dt(`Response error: ${e}`,601))}}})}return new ReadableStream({start(t){t.error(new Dt("Response error: No response body",601))}})}function qt(){return new ReadableStream({start(t){t.close()}})}import{createParser as Gt}from"eventsource-parser";function Ut(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Gt({onEvent:n=>{if("data"in n&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const i=t?t(n.data,{event:n.event}):n.data;i&&e.enqueue(i)}}})},transform(t){n.feed(e.decode(t))}})}function Jt(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Wt(t,e){if(!t.ok)return Bt(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Ut(e))}function Ht(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:i}=await e.next();n?t.close():t.enqueue(i)},async cancel(t){await(e.return?.(t))}})}function Zt(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=i=>{n.call(t,i),e.onError&&e.onError(i)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let i;e.onTransform&&(i=await e.onTransform(t,n)),i||(i=t),n.enqueue(i)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}import{v1 as Kt,v5 as Qt,v4 as Vt}from"uuid";import*as Yt from"base32768";import{v1 as te,v4 as ee,v5 as ne,stringify as ie,parse as re,validate as se,version as oe,NIL as ae}from"uuid";var ce={1:Kt,4:Vt,5:Qt};function ue(t=1,e){const n=ce[t];return e?Yt.encode(n(null,[])):n()}import he from"xxhashjs";import*as fe from"base32768";import{canonicalize as le}from"json-canonicalize";import{createMD5 as me,createRIPEMD160 as pe,createSHA1 as de,createSHA224 as ye,createSHA256 as we,createSHA512 as ve,createXXHash128 as ge,createXXHash32 as be,createXXHash64 as ke}from"hash-wasm";var $e=588213,xe=(t=>(t[t.md5=1]="md5",t[t.sha1=2]="sha1",t[t.ripemd=3]="ripemd",t[t.sha256=8]="sha256",t[t.sha384=9]="sha384",t[t.sha512=10]="sha512",t[t.sha224=11]="sha224",t[t.xxhash=111]="xxhash",t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t[t.xxhash128=113]="xxhash128",t))(xe||{}),Ee={1:me,2:de,8:we,10:ve,11:ye,3:pe,112:be,111:ke,113:ge},{h32:Se,h64:Ae}=he;function Te(t,e=16){return"object"==typeof t&&(t=le(t)),Se(t.normalize(),$e).toString(e)}function je(t,e=16){return"object"==typeof t&&(t=le(t)),Ae(t.normalize(),$e).toString(e)}function Oe(t,e=111,n=$e){let i;return t.buffer&&(t=t.buffer),112!==e?(i=Ae(t,n),i=new Uint16Array([i._a00,i._a16,i._a32,i._a48]),i=new Uint8Array(i.buffer)):(i=Se(t,n),i=new Uint16Array([i._low,i._high]),i=new Uint8Array(i.buffer)),i}function Ne(t,e=111,n=$e){return fe.encode(Oe(t,e,n))}import{canonicalize as Ie}from"json-canonicalize";import*as Ce from"base32768";var Re=Ce;async function Me(t,{hashAlgo:e=111,seed:n=$e,outputType:i="string"}={}){const r=await Ee[e](n);r.init();const s=t.getReader();for(;;){const{done:t,value:e}=await s.read();if(t)break;r.update(e)}return"string"!==i?r.digest(i):Ce.encode(r.digest("binary"))}async function ze(t,{hashAlgo:e=111,seed:n=$e,outputType:i="string"}={}){const r=await Ee[e](n);r.init(),r.update(t);return"string"!==i?r.digest(i):Ce.encode(r.digest("binary"))}import{extNameLevel as Le,FilenameReservedRegex as _e,getMultiLevelExtname as Xe,isValidFilename as Fe,isValidFilepath as Pe,sanitizeFilename as De,sanitizeFilepath as Be,WindowsReservedNameRegex as qe}from"@isdk/util";import{isRegExpStr as Ge,toRegExp as Ue}from"util-ex";function Je(t,e){if("string"!=typeof t)throw new c("modelName must be a string","isModelNameMatched",h.InvalidArgument);switch(typeof e){case"string":if(Ge(e)){const n=(e=Ue(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if(Ge(n)){const i=(e=Ue(n)).exec(t);if(i)return i}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function We(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}import{pick as He}from"lodash-es";import{newFunction as Ze}from"util-ex";import{get as Ke,omitBy as Qe}from"lodash-es";import{newFunction as Ve}from"util-ex";async function Ye(t,e,n){return rn(yn(t,e,n),e,n)}function tn(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function en(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t),i=n.filter((t=>!isNaN(parseInt(t))));if(1===e.length)void 0!==t[0]&&(t=[t[0]]);else if(n.every((t=>!isNaN(parseInt(t))))&&tn(n.map((t=>parseInt(t)))))t=Object.values(t);else if("0"===i[0]&&tn(i.map((t=>parseInt(t))))){const n=e.filter((([t,e])=>isNaN(parseInt(t))));t=e.filter((([t,e])=>!isNaN(parseInt(t)))).map((([t,e])=>e));let i=0;const r=[];for(;i<n.length&&n[i][1]===t[i];)r.push(i),i++;for(;r.length;)n.splice(r.pop(),1);t={args:t,kvArgs:Object.fromEntries(n)}}else t={args:[],kvArgs:t}}return Array.isArray(t)&&(t={args:t}),t}function nn(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t);1===e.length&&void 0!==t[0]?t=t[0]:n.every((t=>!isNaN(parseInt(t))))?t=n.sort(((t,e)=>parseInt(t)-parseInt(e))).map((e=>t[e])):2===e.length&&"0"===e[0][0]&&e[0][1]===e[1][1]&&(t=t[0])}return t}async function rn(t,e,n){if(t.length){const i=await Promise.all(t.map(((t,i)=>dn(t,i,e,n)))),r=n?.returnArrayOnly;let s;if(i?.length){s=Sn(`{${i.map((t=>t)).join(",")}}`,e)}return s&&!r&&(s=nn(s)),s}}function sn(t,e,n,i){const[r,s]=t;if(!r&&"|"===s[0])return"choice: {"+function(t,e,n){const i=yn(t,e,{...n,delimiter:":"}),r={},s=i.map((([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(r[n])throw new Error("Only one "+n+" is allowed");return r[n]=!0,e}{if("|"===e[0]){if(r.items)throw new Error("Only one items is allowed");return r.items=!0,"items:["+function(t,e='"'){return t.map((t=>hn(t,e)))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(r.maxPick)throw new Error("Only one maxPick is allowed");return r.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return r.type=!0,'type:"'+e+'"';if(cn(e)){if(r.separator)throw new Error("Only one separator is allowed");return r.separator=!0,"separator:"+e}}}));return s}(s,n,i)+"}"}async function on([t,e],n,i,r){let s,o;if(i||(i={}),t){const t=e.split(":");s=t[0].trim(),o=t[1].trim()}else o=e,s=n+"";const a={template:o,data:{...Qe(i,((t,e)=>!e||"_"===e[0]||"function"==typeof t)),...r?.templateData}};r?.templateFormat&&(a.templateFormat=r.templateFormat);const c=await L.formatIf(a);if(c)return o=cn(c)?c:JSON.stringify(c),s+":"+o}async function an(t,e,n,i){let r=sn(t,0,n,i);return r||(r=await on(t,e,n,i)),r}function cn(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function un(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}function hn(t,e='"'){return cn(t)?t:e+t+e}function fn(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var ln=["true","false","null","undefined","NaN","Infinity"];async function mn(t,e,n){const i=Ve("async expression",[],`return ${t};`,jn(e));let r;try{r=await i.call(this)}catch(t){if(n||!(t instanceof ReferenceError))throw t}switch(typeof r){case"number":case"boolean":case"undefined":return r;case"function":return i.toString();default:return JSON.stringify(r)}}async function pn(t,e,n){let i=t;if(["true","false"].includes(t.toLowerCase()))i=i.toLowerCase();else if(!(r=t,un(r)||!Number.isNaN(parseFloat(r))||ln.includes(r)||xn(r)||e&&void 0!==Ke(e,t)||xn(t)))try{i=n?.skipExpression?fn(t):await mn.call(this,t,e,n?.preserveUnresolvedName)}catch(e){i=fn(t)}var r;return i}async function dn(t,e,n,i){const[r,s]=t,o=i?.argProcessor,a=i?.ignoreIndexNamed;if("function"==typeof o){const r=await o(t,e,n,i);if(r)return r}if(r){const t=s.indexOf(":");return s.slice(0,t).trim()+":"+await pn(s.slice(t+1).trim(),n,i)}{const t=s.trim();if(n&&void 0!==Ke(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await pn(s.trim(),n,i)}}function yn(t,e,n){const i=n?.delimiter??",",r=n?.assigner??"=";let s=[],o=!1,a="",c="",u=!1,h="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==i||o||h)if("\\"===n)c+=n,e++,c+=t[e];else if("("!==n&&"["!==n||o)if(h&&n===h)h="",c+=n;else if("{"!==n||o)'"'===n||"'"===n?(o&&n===a?o=!1:o||(o=!0,a=n),c+=n):n!==r||o||u||!/^[\p{L}\p{N}_ ]+$/u.test(c)?c+=n:(c+=":",u=!0);else{let i,r=e,s=!1,o="",a=-1;for(;r<t.length&&("}"!==(i=t[r])||s||a>0);)"\\"===i?r++:"{"!==i||s?"}"!==i||s?'"'!==i&&"'"!==i||(s&&n===o?s=!1:s||(s=!0,o=n)):a--:a++,r++;r<t.length&&(c+=t.substring(e,r+1),e=r)}else h="("===n?")":"]",c+=n;else c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c]),c="",u=!1}return c&&(c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c])),s}async function wn(t,e,n){const i=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!i){if(n?.raiseError)throw new Error("Invalid command format");return}const[,r,s]=i;let o;return s&&(o=await Ye(s,e,n)),{command:r.trim(),args:o}}var vn="__PlacEhoLdeR_";function gn(t,e){let n=e?.startChar?Array.isArray(e.startChar)?e.startChar:[e.startChar]:['"',"'"],i=e?.endChar?Array.isArray(e.endChar)?e.endChar:[e.endChar]:n;if(n.length!==i.length)throw new Error("start and end characters must have the same length");const r=e?.placeholder??vn,s=n.every(((t,e)=>t===i[e])),o=e?.placehoders??[];if(s){n=n.map((t=>"\\"+t));const e=new RegExp(`(?<!\\\\)(${n.join("|")}).*?(?<!\\\\)\\1`);let i;for(;null!==(i=e.exec(t));){const e=`${r}${o.length}`;t=t.replace(i[0],e),o.push(i[0])}}else{n=n.map((t=>"\\"+t)),i=i.map((t=>"\\"+t));for(let e=0;e<n.length;e++){const s=new RegExp(`(?<!\\\\)${n[e]}.*?(?<!\\\\)${i[e]}`);let a;for(;null!==(a=s.exec(t));){const e=`${r}${o.length}`;t=t.replace(a[0],e),o.push(a[0])}}}return[t,o]}function bn(t,e,n){const i=n?.placeholder??vn;return e.reduce(((t,e,n)=>t.replace(new RegExp(i+n,"g"),e)),t)}var kn="[a-zA-Z_$][a-zA-Z_\\d$]*",$n=new RegExp(`^\\s*(\\(\\s*\\)|${kn}|\\(${`${kn}\\s*(,\\s*${kn})*`}\\))\\s*=>`);function xn(t){return $n.test(t)}async function En(t,e){if(e&&(e=jn(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await Ye(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return Sn(t,e)}function Sn(t,e){if(e&&(e=jn(e)),e){const n=Object.keys(e);if(n.length){const i=Object.values(e);let r=0;for(;r++<100;)try{return Ze("expression",n,`return ${t}`)(...i)}catch(t){if(!(t instanceof ReferenceError))throw t;{const e=/(.+)\s+is not defined/.exec(t.message);if(!e)throw t;n.push(e[1]),i.push(void 0)}}}}return Ze("expression",[],`return ${t}`)()}var An=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Tn=t=>An.test(t);function jn(t){if(t){const e=Object.keys(t),n=e.length,i=e.filter((e=>Tn(e)&&null!==t[e]));if(n===i.length)return t;if(i.length)return t=He(t,i)}}function On(t){return t?Nn(t,[],{dot:""}):[]}function Nn(t,e,{dot:n=".",visited:i=new Set}={}){return i.has(t)?[e.join("")]:Array.isArray(t)?(i.add(t),t.flatMap(((t,n)=>Nn(t,[...e,`[${n}]`],{dot:".",visited:i})))):(r=t)&&r.constructor===Object?(i.add(t),Object.entries(t).flatMap((([t,r])=>Nn(r,[...e,n+t],{dot:".",visited:i})))):[e.join("")];var r}function In(t){if(t<2)throw new c("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",h.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}import Cn from"path";import*as Rn from"fs";import Mn from"mime-type/with-db";import zn from"jschardet";function Ln(t){const e=Rn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function _n(t,e,n,i){const r=i?.signal,s=i?.exclude;let o;if(Cn.isAbsolute(t)?o=Ln(t)?t:Xn(Cn.basename(t),[Cn.dirname(t)],{extNames:n,exclude:s,signal:r}):(e||(e=["."]),o=Xn(t,e,{extNames:n,exclude:s,signal:r})),!o)throw new m(t,"loadFileFromPaths");{const t=o;o=Rn.readFileSync(o),i&&(i.filepath=t)}return o}function Xn(t,e,{extNames:n,signal:i,exclude:r=[]}){let s;const o=n?n.map((e=>Xe(t,Le(e)))):void 0;"string"==typeof r&&(r=[r]);for(const a of e){if(i?.aborted)throw i.reason;const e=Cn.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const i=e+(o[t]!==n[t]?n[t]:"");if(!r.includes(i)&&Ln(i)){s=i;break}}else if(!r.includes(e)&&Ln(e)){s=e;break}}return s}function Fn(t,e,n,i,r){let s;"string"==typeof i?(s=i,i=void 0):s=i?.encoding;return Pn(_n(t,e,n,i),s)}function Pn(t,e){void 0===e&&(e=Jn(t)??"utf8");return new TextDecoder(e).decode(t)}function Dn(t,e){const n=[],i="string"==typeof t?[{dir:t,level:0}]:[...t.map((t=>({dir:t,level:0})))],r=new Set,s=e?.signal,o=e?.isFileMatched,a=e?.level,c=e?.resolveSymlinks??!0;let u=0;for(;i.length>0;){if(s?.aborted)throw s.reason;const t=i.pop(),e=c?Bn(t.dir):t.dir,h=Cn.resolve(e);if(r.has(h))continue;r.add(h);const f=Rn.statSync(e,{throwIfNoEntry:!1});if(f?.isDirectory()){u=t.level+1;const r=Rn.readdirSync(e,{withFileTypes:!0});for(let t=0;t<r.length;t++){let s=r[t],h=Cn.join(e,s.name);const f=h;if(s.isSymbolicLink()){const t=Cn.dirname(h);h=Rn.readlinkSync(h),h=Cn.resolve(t,h),s=Rn.statSync(h)}if(s.isDirectory())(!a||u<a)&&(o&&!o(h,s)||i.push({dir:h,level:u}));else if(s.isFile()&&(!o||o(h,s))){const t=c?h:f;n.includes(t)||n.push(t)}}}}return n}function Bn(t){const e=Rn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Rn.readlinkSync(t)),t}async function qn(t,e){return Me(ReadableStream.from(Rn.createReadStream(t)),e)}async function Gn(t){const e=Cn.basename(t);t=Cn.resolve(t);const n=await Rn.promises.stat(t),i=n.mtime,r=n.ctime,s=n.size,o=Un(s),a=await qn(t,{hashAlgo:o}),c=Mn.lookup(t);return{name:e,mtime:i,ctime:r,size:s,hash:xe[o]+":"+a,mimeType:c,id:"file://"+t}}function Un(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function Jn(t,e){return zn.detect(t,e).encoding}import{statSync as Wn}from"fs";import Hn from"path";import{ConfigFile as Zn,registerYamlTag as Kn,traverseFolderSync as Qn}from"@isdk/util";import{regexp as Vn}from"yaml-types";import{mimeType as Yn}from"mime-type/with-db";import{ConfigFile as ti,registerYamlTag as ei,parseYaml as ni,stringifyYaml as ii}from"@isdk/util";function ri(t,e){const n=[],i=e?.after,r=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,s=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return Qn(t,((t,e)=>{if(r?.includes(t)||!e.isFile())return;const o=Hn.extname(t),a=Wn(t);if(s.includes(o)){if(i?.hasOwnProperty(t)&&a.mtimeMs<=i[t])return;n.push(t)}})),n}function si(t,e){return ri(t,e).map((t=>Zn.loadSync(t))).filter((t=>void 0!==t))}function oi(t,e,n=1){return Zn.saveSync(t,e,{extLevel:n})}function ai(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function ci(t,e){return t.map((t=>fi(t,e))).join(" AND ")}function ui(t,e){return t.map((t=>fi(t,e))).join(" OR ")}function hi(t,e){const n=[];return Object.keys(e).forEach((i=>{const r=e[i];switch(i){case"$lt":case"<":n.push(`${t} < ${ai(r)}`);break;case"<=":case"$lte":n.push(`${t} <= ${ai(r)}`);break;case"$gt":case">":n.push(`${t} > ${ai(r)}`);break;case"$gte":case">=":n.push(`${t} >= ${ai(r)}`);break;case"$ne":case"!=":n.push(`${t} != ${ai(r)}`);break;case"=":case"$eq":n.push(`${t} = ${ai(r)}`);break;case"$in":n.push(`${t} IN (${r.map((t=>ai(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${r.map((t=>ai(t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${r.source}'`);break;case"$like":n.push(`${t} LIKE '${r}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${r}'`);break;case"$glob":n.push(`${t} GLOB '${r}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${r}'`);break;default:throw new Error(`Unsupported condition operator: ${i}`)}})),n.join(" AND ")}function fi(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(ci(t,e));else for(const[i,r]of Object.entries(t))if("$and"===i)n.push(`(${ci(t[i],e)})`);else if("$or"===i)n.push(`(${ui(t[i],e)})`);else{const t=typeof r;if(null==r)n.push(`${e(i)} IS NULL`);else if(r instanceof Date)n.push(`${e(i)}='${r.toISOString()}'`);else if("object"!==t||Array.isArray(r))if("string"===t)n.push(`${e(i)}='${r}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${i}`);n.push(`${e(i)}=${r}`)}else n.push(hi(e(i),r))}return n.length>1?n.join(" AND "):n[0]}function li(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function mi(t,e=0){let n,i=t*10**e;return t>=1e12?(i=Math.round(i/1e12),n="T"):t>=1e9?(i=Math.round(i/1e9),n="B"):t>=1e6?(i=Math.round(i/1e6),n="M"):t>=1e3?(i=Math.round(i/1e3),n="K"):(i=Math.round(i),n=""),i/=10**e,i.toFixed(e)+n}function pi(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new c("Invalid formatted parameter size string.","scaleToSize",h.InvalidArgument);const n=parseFloat(e[1]),i=e[2]?.toLowerCase();switch(i){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function di(t,e){const n=e?.level||0,i=e?.visiting||new Set,r=e?.objectTag||"*",s=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":i.has(t)?o=["[Circular]"]:(i.add(t),o=Array.isArray(t)?t.map((t=>s+c(t))):Object.entries(t).map((([t,e])=>r+" `"+t+"`:"+c(e))));break;case"string":return t;default:return JSON.stringify(t)}else o=["null"];return o.length?a+o.join("\n"+a):"";function c(t){return(null!=t&&"object"==typeof t?"\n":" ")+di(t,{level:n+1,visiting:i})}}Kn(Vn);var yi=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}};import{isAsync as wi}from"util-ex";import{EventEmitter as vi}from"events-ex";function gi(t=0){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 bi=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=gi(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this[n]=t,++e<=this._capacity&&(this._length=e),n}unshift(t){let e=this._length;this.checkCapacity(++e);const n=this._capacity,i=(this._front-1&n-1^n)-n;return this[i]=t,this._front=i,e<=this._capacity&&(this._length=e),i}pop(t){let e=this._length;if(0===e)return;let n=this._front+e-1&this._capacity-1,i=this[n];for(;--e>0&&t&&null==i;)n--,i=this[n];return this[n]=void 0,this._length=e,i}shift(t){let e=this._length;if(0===e)return;let n=this._front,i=this[n];for(;--e>0&&t&&null==i;)n=n+1&this._capacity-1,i=this[n];return this[n]=void 0,this._front=n+1&this._capacity-1,this._length=e,i}get size(){return this._length}get(t){let e;if(t===(0|t)){const n=this._length;t<0&&(t+=n),t>=0&&t<n&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,n=this._capacity;for(let i=0;i<t;++i)this[e+i&n-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const n=this._front,i=this._capacity-1,r=n+t&i,s=this[r];if(t<e/2)this.copyWithin(n+1&i,n,n+t&i),this[n]=void 0,this._front=n+1&i;else{this.copyWithin(r,r+1&i,n+e&i);this[n+e-1&i]=void 0}return this._length=e-1,s}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(gi(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,i=this._length;if(n+i>e){!function(t,e,n,i,r){for(let s=0;s<r;++s)n[s+i]=t[s+e],t[s+e]=void 0}(this,0,this,e,n+i&e-1)}}};import{AbortError as ki}from"@isdk/common-error";var $i=32;function xi(t){return"function"==typeof t}function Ei(){return"1"}var Si=class{constructor(t={}){const{initFn:e=Ei,pauseFn:n,resumeFn:i,capacity:r=$i}=t;if(xi(n)!==xi(i))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new bi(r),this.emitter=new vi,this.useDefaultTokens=e===Ei,this.pauseFn=n,this.resumeFn=i,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,n=this.waiting.shift(!0);n?this._dispatchTask(n,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",(t=>{this.onReleased(t)}))}_newReleaser(t){let e=!1;const n=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(n,t),n}_dispatchTask(t,e){const{resolve:n}=t;n(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,n=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push(t),i=t.reject;return e&&e.addEventListener("abort",(()=>{this.waiting[n]=void 0;const t=e.reason instanceof Error?e.reason:new ki(e.reason||"aborted");e.alreadyRejected=!0,i(t)})),n};let i=this.tryAcquire(t);const r=i&&wi(i),s=e=>new Promise(((i,r)=>{const s={...t,resolve:i,reject:r,token:e};void 0===e?n(s):this._dispatchTask(s,{...t,token:e})}));return r?i.then((t=>s(t))):s(i)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new ki(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},Ai=class extends Si{constructor(t,e){if("number"==typeof t)(e=e||{}).maxConcurrency=t;else{if("number"!=typeof(e=t).maxConcurrency)throw new Error("maxConcurrency must be set");t=e.maxConcurrency}super(e),this.maxConcurrency=e.maxConcurrency,e.isReadyFn&&(this.isReady=e.isReadyFn)}initFree(t){const e=t.maxConcurrency=Math.max(1,t.maxConcurrency);this.free=new bi(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&wi(e)){return e instanceof Promise||(e=e()),e.then((e=>{if(e)return this.lock(t)}))}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}};function Ti(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const i=new Ai(n?1:t),r=n?e/t:e;return async function(){await i.acquire(),setTimeout((()=>i.release()),r)}}import{AbortError as ji}from"@isdk/common-error";var Oi=class{constructor(){this._isSignaled=!1,this.waitQueue=[]}get signaled(){return this._isSignaled}signal(t){if(this._isSignaled)return;this._isSignaled=!0,this._signalValue=t;const e=this.waitQueue.slice();for(this.waitQueue.length=0;e.length>0;){const t=e.shift();t?.resolve(this._signalValue)}}reset(){this._isSignaled=!1,this._signalValue=void 0,this.waitQueue.length=0}abort(t){if(this.waitQueue.length){const e=this.waitQueue.slice();this.waitQueue.length=0;const n=new ji(t);for(;e.length>0;){const{reject:t}=e.shift();t(n)}}}async wait(){return new Promise(((t,e)=>{this._isSignaled?t(this._signalValue):this.waitQueue.push({resolve:t,reject:e})}))}};import{createAbilityInjector as Ni}from"custom-ability";import{defineProperty as Ii}from"util-ex";var Ci,Ri=0,Mi=1,zi=2,Li=(t=>(t[t.MultiTask=0]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(Li||{}),_i=((Ci=_i||{})[Ci.MultiTask=1]="MultiTask",Ci[Ci.Cancelable=2]="Cancelable",Ci[Ci.Priority=4]="Priority",Ci),Xi=class extends AbortController{constructor(t){super(),Ii(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new i(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 i(e.reason||"aborted")}}},Fi=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,n=this.__task_semaphore;return e>0&&!n&&(t&&(t=t.bind(this)),n=this.__task_semaphore=new Ai(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),yi.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),yi.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new c("Missing taskId",this.name+".isAborted",h.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new c("Missing taskId",this.name+".getRunningTask",h.InvalidArgument);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(0)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,n])=>{if(!n?.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 n=this.super,i=this.self||this;return t=n?n.call(i,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const i=this.hasAsyncFeature(0);if(!i&&n&&this.getRunningTask())throw new c("The task is running",this.name,h.TooManyRequests);const r=t?.aborter||new Xi(this);if(!(r instanceof Xi)){if(!(r instanceof AbortController))throw new c("aborter should be an AbortController",this.name,h.InvalidArgument);Object.setPrototypeOf(r,new Xi(this))}if(i){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),r.id=e,t[e]=r}else this.__task_aborter=r;const s=t?.timeout;return s>0&&(r.timeoutId=setTimeout((()=>{r.timeoutId=void 0,this.abort("timeout",{timeout:s})}),s)),r.signal.addEventListener("abort",(()=>{const t=r.timeoutId;t&&(r.timeoutId=void 0,clearTimeout(t));const e=r.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{r.streamController?.error(e.reason)}})),r}$cleanMultiTaskAborter(t,e){const n=this.super,i=this.self||this;n?n.call(i,t,e):i._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(0)){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,n){const i=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=i);let r=t(e,i).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(i)},n=Zt({onStart:t=>{Ii(i,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=i.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(i);return t})).catch((t=>{throw this.cleanTaskAborter(i),t})).finally((()=>{i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=void 0)}));return r.task=i,r}runAsyncCancelableTask(t={},e,n){let i=this.createTaskPromise(e,t,n);const r=this.getSemaphore(n?.isReadyFn);if(r){const t=i,e=t.task;i=r.acquire({signal:e.signal}).then((()=>t)).finally((()=>{r.release()})),i.task=e}return i}abort(t,e){let n=this.__task_aborter;if(n){const i=n;if(this.hasAsyncFeature(0)){const t=e?.taskId;if(null==t)throw new c("Missing data.taskId",this.name+".abort",h.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,i)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};Fi.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Fi.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Pi=Ni(Fi,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=_i.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=n}});function Di(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let i,r=0;for(;null!==(i=n.exec(t));)r++;return r}import Bi from"memoizee";import{canonicalize as qi}from"json-canonicalize";function Gi(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const i=e?.normalizer;return Bi(t,{...e,normalizer:t=>{if(i){const e=i(t);if("string"===e)return e;e&&(t=e)}return Ne(qi(t))}})}import Ui from"path";import{packageDirectorySync as Ji}from"pkg-dir";function Wi(t){const e=Ji({cwd:t});if(e)return e;const n=t.split(Ui.sep);let i=n.lastIndexOf("dist");if(i>0)return n.slice(0,i).join(Ui.sep);if(i=n.lastIndexOf("src"),i>0)return n.slice(0,i).join(Ui.sep);throw new Error("can not find package directory")}import Hi from"path";function Zi(t,e){try{const n=Hi.relative(Hi.resolve(t),Hi.resolve(e));return!n.startsWith("..")&&!Hi.isAbsolute(n)}catch{return!1}}function Ki(t,e){return e?.some((e=>Zi(e,t)))}function Qi(t,e){for(const n of e)Ki(n,t)||t.push(n);return t}import{isRegExp as Vi,isRegExpStr as Yi}from"util-ex";function tr(t){return Yi(t)||Vi(t)}function er(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}import nr from"path";import{fileURLToPath as ir}from"url";import{AutoTokenizer as rr}from"@xenova/transformers";var sr=ir(import.meta.url),or=nr.dirname(sr),ar=nr.join(Wi(or),".cache"),cr=new Map,ur={"deepseek-ai/DeepSeek-V2-Lite-Chat":"deepseek2","Qwen/Qwen2.5-0.5B":"Qwen2.5","Xenova/gpt-4":"gpt-4 / gpt-3.5-turbo / text-embedding-ada-002","Xenova/text-davinci-003":"text-davinci-003 / text-davinci-002","Xenova/gpt-3":"gpt-3","Xenova/grok-1-tokenizer":"Grok-1","Xenova/claude-tokenizer":"Claude","Xenova/mistral-tokenizer-v3":"Mistral v3","Xenova/mistral-tokenizer-v1":"Mistral v1","Xenova/gemma-tokenizer":"Gemma","Xenova/gemma2-tokenizer":"Gemma2","Xenova/llama3-tokenizer-new":"Llama 3","unsloth/Llama-3.2-1B-Instruct":"Llama 3.2","Xenova/llama-tokenizer":"LLaMA / Llama 2","Xenova/c4ai-command-r-v01-tokenizer":"Cohere Command-R","Xenova/t5-small":"T5","Xenova/bert-base-cased":"bert-base-cased"},hr={deepseek2:"deepseek-ai/DeepSeek-V2-Lite-Chat","qwen2.5":"Qwen/Qwen2.5-0.5B","gpt-4":"Xenova/gpt-4","gpt-3.5-turbo":"Xenova/gpt-4","text-embedding-ada-002":"Xenova/gpt-4","text-davinci-003":"Xenova/text-davinci-003","text-davinci-002":"Xenova/text-davinci-003","gpt-3":"Xenova/gpt-3","grok-1":"Xenova/grok-1-tokenizer",claude:"Xenova/claude-tokenizer",mistral:"Xenova/mistral-tokenizer-v3",mistral3:"Xenova/mistral-tokenizer-v3",mistral1:"Xenova/mistral-tokenizer-v1",gemma:"Xenova/gemma-tokenizer",gemma2:"Xenova/gemma2-tokenizer",llama3:"Xenova/llama3-tokenizer-new",llama2:"Xenova/llama-tokenizer",llama:"Xenova/llama-tokenizer","llama3.2":"unsloth/Llama-3.2-1B-Instruct","cohere-command-r":"Xenova/c4ai-command-r-v01-tokenizer",t5:"Xenova/t5-small","bert-cased":"Xenova/bert-base-cased"};async function fr(t){let e=cr.get(t);return e||(e=rr.from_pretrained(t,{cache_dir:ar}),cr.set(t,e)),e}async function lr(t,e="qwen2.5"){hr[e]&&(e=hr[e]);return(await fr(e)).encode(t)}async function mr(t,e="qwen2.5"){return(await lr(t,e)).length}function pr(t,e){const n=e?.capitalize??!0;let i=e?.delimiter??/[_-]/g;i instanceof RegExp&&(i.flags.includes("g")||(i=new RegExp(i.source,i.flags+"g")));let r=(t=t.replace(i," ")).split(" ").map((t=>t.trim())).filter(Boolean);return n&&(r=r.map((t=>t.charAt(0).toUpperCase()+t.slice(1)))),t=r.join(" ")}async function dr(t,e){let n,i=1984,r=!0,s=!1,o=!0,a=mr,u=!0;if(e&&(n=e.modelId,e.size>=0&&(i=e.size),void 0!==e.corrected&&(r=e.corrected),void 0!==e.completeSentence&&(s=e.completeSentence),void 0!==e.truncLastSection&&(o=e.truncLastSection),"function"==typeof e.countLLMTokens&&(a=e.countLLMTokens),void 0!==e.bySentence&&(u=e.bySentence)),!u)throw new d("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(i>0){let u=await a(t,n);const h=e?.sentences??ut(t,e);if(u>i)for(u=await a(h.join("\n"),n);u>i&&h.length;){const e=h.pop();if(e){if(u-=await a(e+"\n",n),s||r)t=h.join("\n");else{const n=t.lastIndexOf(e);if(-1===n)throw new c(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n)}if(u<=1)throw new c(`Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");if(u<=i&&o){const e=h[h.length-1];if(e&&mt(e)){if(u-await a(e,n)>9){const n=t.lastIndexOf(e);if(-1===n)throw new c(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n).trimEnd()}}}}else u--}else t=h.join("\n")}if(!t)throw new c(`Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");return t}async function yr(t,e){let n,i=1984,r=!0,s=mr,o=!0;if(e&&(n=e.modelId,e.size>=0&&(i=e.size),void 0!==e.truncLastSection&&(r=e.truncLastSection),"function"==typeof e.countLLMTokens&&(s=e.countLLMTokens),void 0!==e.bySentence&&(o=e.bySentence)),!o)throw new d("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(i>0){const e=(t=t.slice()).join("\n");let o=await s(e,n);if(o>i)for(;o>i&&t.length;){const e=t.pop();if(e){if(o-=await s(e,n),o<=1)throw new c(`Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");if(o<=i&&r){const e=t[t.length-1];if(e&&mt(e)){o-await s(e,n)>9&&t.pop()}}}}}if(!t.length)throw new c(`Empty. Can not truncate content to fit within the token limit: ${i}`,"truncateContentToTokenLimit");return t}async function wr(t,e){let n,i=1984,r=mr;if(e&&(n=e.modelId,"function"==typeof e.countLLMTokens&&(e.size>=0&&(i=e.size),r=e.countLLMTokens)),i>0){await r(t,n)}}import vr from"fs";async function*gr(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,i=e.modelId,r=e.metaInfo?.size??(await vr.promises.stat(t)).size;let s=Math.trunc(r/2);if(s<=n){let r=Pn(await vr.promises.readFile(t));if(s=await mr(r,i),s<=n)yield r;else do{const t=await dr(r,{...e,modelId:i,size:n});yield t,r=r.slice(t.length)}while(r)}else{const r=ReadableStream.from(vr.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await r.read();if(t)break;s+=Pn(o);const a=ut(s,e);let c=a.pop();if(c){const t=s.lastIndexOf(c);c=s.slice(t),s=s.slice(0,t)}if(s.length>=n){const t=await dr(s,{...e,modelId:i,size:n,sentences:a});s=s.slice(t.length),yield t}for(;s.length>n;){const t=ut(s,e),r=await dr(s,{...e,modelId:i,size:n,sentences:t});s=s.slice(r.length),yield r}void 0!==c&&(s+=c)}for(;s;){const t=ut(s,e),r=await dr(s,{...e,modelId:i,size:n,sentences:t});s=s.slice(r.length),yield r}}}async function*br(t,e){const n=e?.size??1984,i=e?.modelId,r=e?.metaInfo?.size??(await vr.promises.stat(t)).size;let s=Math.trunc(r/2);if(s<=n){let r=Pn(await vr.promises.readFile(t));if(s=await mr(r,i),s<=n)yield ut(r,e);else{let t=ut(r,e);do{const r=await yr(t,{...e,modelId:i,size:n});yield r,t=t.slice(r.length)}while(t.length)}}else{const r=ReadableStream.from(vr.createReadStream(t)).getReader();let s="";const o=e?.completeSentence,a=e?.corrected,c=!o&&!a;let u;for(;;){const{done:t,value:o}=await r.read();if(t)break;s+=Pn(o),u=ut(s,e);let a=u.pop();if(s.length>=n){const t=await yr(u,{...e,modelId:i,size:n});s=c?s.slice(t.length):u.join("\n"),u=u.slice(t.length),s=u.join("\n"),yield t}for(;s.length>n;){const t=await yr(u,{...e,modelId:i,size:n});u=u.slice(t.length),s=u.join("\n"),yield t}a&&u.push(a)}if(u)for(;u.length;){const t=await yr(u,{...e,modelId:i,size:n});u=u.slice(t.length),yield t}}}async function kr(t,e){const n=e?.size??1984,i=e?.modelId;let r=ut(t,e);const s=[];if(await mr(t,i)<=n)s.push(r);else do{const t=await yr(r,{...e,modelId:i,size:n});s.push(t),r=r.slice(t.length)}while(r.length);return s}import{YAMLMap as $r}from"yaml";var xr=class{constructor(t){t&&Object.assign(this,t)}};function Er(t,e){const n={tag:t,collection:"map",nodeClass:class extends $r{constructor(){super(...arguments),this.tag=t}toJSON(t,n){n={...n,mapAsMap:!1};const i=super.toJSON(t,n);return new e(i)}},identify:t=>t instanceof e};return n}function Sr(t,e){let n=t.length===e.length;if(n){const i=Oe(t),r=Oe(e);n=i.every(((t,e)=>t===r[e]))}return n}import{defaultsDeep as Ar,omit as Tr}from"lodash-es";import jr from"path";var Or=".ai";function Nr(t,e=["."]){if(jr.isAbsolute(t))return ti.loadSync(t);const n=e.map((e=>ti.loadSync(jr.resolve(e,t)))).filter(Boolean);return Ar({},...n.reverse())}function Ir(t,e){const n={...process.env,...e};return D(t,{processEnv:n,parsed:n})}function Cr(t,e){let n=ti.loadSync(jr.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:[jr.join(e.dataDir,"brain")],agentDirs:[jr.join(e.dataDir,"agent")],promptDirs:[jr.join(e.dataDir,"prompt")],chatsDir:jr.join(e.dataDir,"log","chats"),inputsDir:jr.join(e.dataDir,"log","inputs")});const i=Mr(e);for(const[t,e]of Object.entries(i))n[t]=e;Ir(n,n);const r=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Ir(Nr(t,r),n);return Ar(s,Tr(n,Object.keys(i)))}function Rr(t){return Cr(".ai",t)}function Mr(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:jr.dirname(t.options.root)}}function zr(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Ir(t,e)}var{exit:Lr}=process,_r=!1,Xr=!1,Fr=["SIGINT","SIGTERM","exit"],Pr=[],Dr=(t,e)=>t.forEach((t=>process.once(t,e)));async function Br(t="shutdown",e=0){if(!_r){_r=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of Pr)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return Lr(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function qr(t){if(Xr||Gr(),!Pr.some((e=>e===t)))return Pr.push(t),t}function Gr(){var t;Xr||(Xr=!0,process.exit=t=>{_r||Br(void 0,t).then()},Dr(Fr,(t=3e5,()=>{setTimeout((()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),Lr(1))),t).unref()})),Dr(Fr,Br))}var Ur=class t extends e{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const i=this.get(n);let r=i.tags;if("string"==typeof r){if(r===t){e=i;break}}else if(Array.isArray(r)&&r.indexOf(t)>=0){e=i;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const i=this.get(n);let r=i.tags;"string"==typeof r?r===t&&e.push(i):Array.isArray(r)&&r.indexOf(t)>=0&&e.push(i)}return e}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),yi.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new m(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new m(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const n=this.get(t);if(n)return n.runWithPos(...e);throw new m(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new m(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let i=!!this.get(e);if(i)i=!1;else{if(!(n instanceof t))return i=new this(n),i.register();if(this.items[e]=n,n.alias){const t=n.alias;if("string"==typeof t)this.aliases[t]&&y(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const n of t)this.aliases[n]&&y(`Alias ${n} already exists for ${e}`),this.aliases[n]=e}i=n}return i}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,n=this.depends;if(n){const e=Object.keys(n);for(const i of e){const e=n[i];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},n=Object.keys(this.params);let i=Math.min(n.length,t.length);for(let r=0;r<i;r++)e[n[r]]=t[r];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let i=Math.min(n.length,this.params.length);for(let r=0;r<i;r++)e.push(t[n[r]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);y("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),yi.has(e,t)}isStream(t){return this.stream}},Jr={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,i,r,s){let o=t;const a=typeof t;return s.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=n(t,e.scope)),o}},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"},alias:{type:["array","string"]}};Ur.defineProperties(Ur,Jr);var Wr=class extends Ur{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Hr=new Wr(Rt);import{Cache as Zr}from"secondary-cache";import{LRUCache as Kr}from"secondary-cache";var Qr=Zr;function Vr({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function Yr(t,e){let n=Ur.get(t);return n||(n=new Ur(t,{func:Vr,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),n.cache=new Zr(e)),n}var ts=Yr("lrucache"),es=class t extends Ur{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 y("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const n in e){const i=this.get(n),r=e[n];i?i instanceof t?i.assign(r):y(`${n} already registered as ${i.constructor.name}`,"ClientTools"):this.register(r)}}static async fetch(t,e){const n=this.get(t);if(n&&n.fetch)return n.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,n){const i={...this.fetchOptions},r=["post","put","patch"];let s;e||(e=this.action||"post"),"res"===e&&(e="get"),i.headers&&i.headers["Content-Type"]||!r.includes(e)||(i.headers={"Content-Type":"application/json",...i.headers}),t?.stream&&!i.headers.Connection&&(i.headers.Connection="keep-alive"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,i.method=e.toUpperCase(),"get"===e||"delete"===e?s=n+this.getUrlParams(t):(i.body=JSON.stringify(t),s=n),i.headers&&!r.includes(e)&&delete i.headers["Content-Type"];const o=await fetch(`${this.apiRoot}/${s}`,i);if(!o.ok){throw await this.errorFrom(o)}return o}async errorFrom(t){let e,n=t.status,i=t.statusText,r=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(i=t.error),t.name&&(r=t.name),t.data&&(e=t.data,e.name=r,e.what&&(e.msg=i,i=e.what)),t.message&&(i=i+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return u(i,r,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},ns={...k};es.defineProperties(es,ns);var is=class extends es{async _func(t,e){const n=await this.fetch(e,t);if(e?.stream)return n;return await n.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},rs={methods:{type:"array",assign(t,e,n,i,r){r?.isExported||e.assignMethods(t)}}};is.defineProperties(is,rs);var ss=class extends is{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||y("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},os=class extends ss{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Ct,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",n=`${this.apiRoot}/${this.name}${e}`,i=this._es=new EventSource(n);return Object.entries(this._sseEvents).forEach((([t,e])=>{i.addEventListener(t,e)})),this._esEvents=t,i}esListener(t){const e=t.data?JSON.parse(t.data):void 0,n=t.type;if(!this._forwardEvents.has(n)){const t=this.emitter;t&&e&&n&&(Array.isArray(e)?t.emit(n,...e):t.emit(n,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);n.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},as=new os(Ct);import{getAllNames as cs}from"util-ex";var us=class t extends Ur{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let i=this.items[n];(i instanceof t||i.isApi)&&(i.allowExportFunc||(i=i.toJSON(),delete i.func),e[n]=i)}return e}func({}){}},hs={...k};us.defineProperties(us,hs);var fs=class extends us{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);cs(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(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 m(e,this.name)}};fs.defineProperties(fs,{methods:{type:"array"}});var ls=class extends fs{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=b}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}},ms=Hr.runSync(),ps=class t extends ls{constructor(){super(...arguments),this.name=Ct,this.description="subscribe server sent event",this.result="event",this.depends={[Rt]:Hr}}static get sse(){return this._sse||(this._sse=new _t),this._sse}get sse(){return this.constructor.sse}static publish(e,n){return t.sse.publish(e,n)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,n,i){return t.sse.subscribe(e,n,i)}static alreadyForward(e){const n=ms.listeners(e);for(const e of n)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);for(const n of e)t.alreadyForward(n)||ms.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)ms.off(n,t.ebListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};y("event is required","sub",h.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};y("event is required","unsub",h.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}y("event or data is required","pub",h.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},ds=new ps(Ct);function ys(){Hr.register(),ts.register()}export{g as PASSING_SCORE,b as ActionNames,k as RemoteToolFuncSchema,i as AbortError,r as AbortErrorCode,s as AlreadyExistsError,o as AlreadyExistsErrorCode,a as BaseError,c as CommonError,u as createError,h as ErrorCode,f as InternalErrorCode,l as NotFoundErrorCode,m as NotFoundError,p as NotImplementedErrorCode,d as NotImplementationError,y as throwError,x as parseDateFormat,O as toDateTime,N as textToDate,I as dateToText,S as formatISO,A as parseISO,T as toDate,C as AITextGenerationFinishReasons,R as AIMessageTypes,M as AIChatRoles,z as messagesToText,J as sortedValues,W as FewShotPromptTemplate,K as PromptExampleSelector,L as StringTemplate,_ as EnvStringTemplate,X as FStringTemplate,F as GolangStringTemplate,P as expandEnv,D as expandObjEnv,B as defaultTemplateFormat,q as getEnvVairables,G as createHfValueFunc,ut as splitSentence,ht as completeSentences,ft as concatText,lt as isSentenceEnding,mt as isSectionString,pt as isTitleString,dt as isListItemString,yt as isSepLineString,wt as isPunctuationChar,gt as isLangUsingSpaces,bt as findIndexNonEmptyFrom,kt as removeMarkdownBold,$t as removeMarkdownItalic,xt as removeMarkdownBoldAndItalic,Et as splitParagraph,St as truncTo,At as wait,Ct as EventName,Rt as EventBusName,Mt as backendEventable,jt as EventEmitter,Ot as eventable,Nt as states,It as wrapEventEmitter,Lt as SSEChannelAlreadyClosedErrCode,_t as SSEChannel,Xt as isWebStream,Ft as RStreamErrCode,Pt as ResponseRStreamErrCode,Dt as ReadableStreamError,Bt as getResponseErrorReadableStream,qt as createEmptyReadableStream,Ut as createEventStreamTransformer,Jt as trimStartOfStreamHelper,Wt as AIStream,Ht as readableFromAsyncIterable,Zt as createCallbacksTransformer,ue as uuid,te as v1,ee as v4,ne as v5,ie as stringify,re as parse,se as validate,oe as version,ae as NIL,xe as HashAlgorithm,Te as xxhash32,je as xxhash64,Oe as xxhash,Ne as xxhashAsStr,Ie as canonicalize,Re as base32768,Me as hashStream,ze as hash,Le as extNameLevel,_e as FilenameReservedRegex,Xe as getMultiLevelExtname,Fe as isValidFilename,Pe as isValidFilepath,De as sanitizeFilename,Be as sanitizeFilepath,qe as WindowsReservedNameRegex,Je as isModelNameMatched,We as getAllEnumKeys,Ye as parseObjectArguments,en as ObjectArgsToArgsInfo,nn as simplifyObjectArguments,rn as parseObjectArgumentInfos,sn as ChoiceArgProcessor,on as TemplateArgProcessor,an as AIArgProcessor,cn as isQuoted,un as isStrWrapped,hn as ensureQuoted,fn as quoteStr,dn as parseObjectArgInfo,yn as parseObjectArgumentsAsArgInfos,wn as parseCommand,gn as replaceWithPlaceholder,bn as restoreFromPlacehoders,En as parseJsJson,Sn as parseJsJsonSimpleSync,jn as filterValidFnScope,On as getKeysPath,In as createEndWithRepetitionDetector,Ln as fileIsExists,_n as loadFileFromPaths,Fn as loadTextFromPaths,Pn as decodeCharset,Dn as readFilenamesRecursiveSync,Bn as getRealFilepath,qn as hashFile,Gn as getFileMetaInfo,Un as getHashAlgoBySize,Jn as detectCharset,ri as getConfigFileNames,si as getConfigs,oi as saveConfigFile,Yn as mimeType,ti as ConfigFile,ei as registerYamlTag,ni as parseYaml,ii as stringifyYaml,fi as jsonFilterToWhere,li as matchUrlProtocol,mi as paramsSizeToScaleStr,pi as scaleStrToParamsSize,di as jsonToMarkdownStr,yi as IntSet,$i as DefaultAsyncSemaphoreCapacity,Si as BinarySemaphore,Ai as Semaphore,Ti as RateLimit,Oi as SignalGate,Ri as ToolAsyncMultiTaskBit,Mi as ToolAsyncCancelableBit,zi as ToolAsyncPriorityBit,Li as AsyncFeatureBits,_i as AsyncFeatures,Xi as TaskAbortController,Fi as CancelableAbility,Pi as makeToolFuncCancelable,Di as countRegexMatches,Gi as memoize,Wi as getPackageDir,Zi as isSubdirectory,Ki as hasDirectoryIn,Qi as assignDirs,tr as isRegExp,er as stripConsoleColor,ur as LLM_TOKENIZER_NAMES,hr as LLM_TOKENIZER_NAMES_MAP,fr as getLLMTokenizer,lr as encodeLLMTokens,mr as countLLMTokens,pr as formatTextWithSpace,dr as truncateToTokenLimit,yr as truncateToTokenLimitEx,wr as truncateByToken,gr as readTextFileChunks,br as readTextFileChunksEx,kr as splitChunks,xr as YamlTypeBaseObject,Er as createYamlObjectTag,Sr as isSameString,Or as DEFAULT_CONFIG_NAME,Nr as loadConfigFile,Ir as expandConfig,Cr as loadConfig,Rr as loadAIConfig,Mr as getXDGConfigs,zr as expandPath,Fr as SHUTDOWN_SIGNALS,Br as shutdown,qr as beforeShutdown,Gr as initShutdown,w as createAbilityInjector,v as toRegExp,Ur as ToolFunc,Jr as ToolFuncSchema,es as ClientTools,ns as ClientToolFuncSchema,us as ServerTools,hs as ServerToolFuncSchema,Wr as EventToolFunc,Hr as event,Qr as SecondaryCache,Vr as _lrucache,Yr as createLRUCache,ts as lrucache,Kr as LRUCache,ss as ResClientTools,os as EventClient,as as eventClient,ls as ResServerTools,ps as EventServer,ds as eventServer,ys as registerCoreTools};
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:()=>Te,EventServer:()=>_e,EventToolFunc:()=>ge,LRUCache:()=>Ee.LRUCache,SecondaryCache:()=>ve,_lrucache:()=>ke,createLRUCache:()=>Se,event:()=>be,eventClient:()=>Me,eventServer:()=>Be,lrucache:()=>$e,registerCoreTools:()=>Le}),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 g="default",b=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||g,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||g);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 x=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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:x.Set,for:x.For,in:x.In,is:x.Is,if:x.If,else:x.Else,endif:x.EndIf,elif:x.ElseIf,endfor:x.EndFor,and:x.And,or:x.Or,not:x.Not,"not in":x.NotIn,macro:x.Macro,endmacro:x.EndMacro,true:x.BooleanLiteral,false:x.BooleanLiteral,none:x.NullLiteral,True:x.BooleanLiteral,False:x.BooleanLiteral,None:x.NullLiteral}),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 $=[["{%",x.OpenStatement],["%}",x.CloseStatement],["{{",x.OpenExpression],["}}",x.CloseExpression],["(",x.OpenParen],[")",x.CloseParen],["{",x.OpenCurlyBracket],["}",x.CloseCurlyBracket],["[",x.OpenSquareBracket],["]",x.CloseSquareBracket],[",",x.Comma],[".",x.Dot],[":",x.Colon],["|",x.Pipe],["<=",x.ComparisonBinaryOperator],[">=",x.ComparisonBinaryOperator],["==",x.ComparisonBinaryOperator],["!=",x.ComparisonBinaryOperator],["<",x.ComparisonBinaryOperator],[">",x.ComparisonBinaryOperator],["+",x.AdditiveBinaryOperator],["-",x.AdditiveBinaryOperator],["*",x.MultiplicativeBinaryOperator],["/",x.MultiplicativeBinaryOperator],["%",x.MultiplicativeBinaryOperator],["=",x.Equals]],j=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);var A=class{constructor(){this.type="Statement"}},O=class extends A{constructor(t){super(),this.body=t,this.type="Program"}},C=class extends A{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},q=class extends A{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},T=class extends A{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},M=class extends A{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},N=class extends A{constructor(){super(...arguments),this.type="Expression"}},I=class extends N{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},V=class extends N{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},P=class extends N{constructor(t){super(),this.value=t,this.type="Identifier"}},U=class extends N{constructor(t){super(),this.value=t,this.type="Literal"}},F=class extends U{constructor(){super(...arguments),this.type="NumericLiteral"}},_=class extends U{constructor(){super(...arguments),this.type="StringLiteral"}},B=class extends U{constructor(){super(...arguments),this.type="BooleanLiteral"}},L=class extends U{constructor(){super(...arguments),this.type="NullLiteral"}},R=class extends U{constructor(){super(...arguments),this.type="ArrayLiteral"}},z=class extends U{constructor(){super(...arguments),this.type="TupleLiteral"}},J=class extends U{constructor(){super(...arguments),this.type="ObjectLiteral"}},W=class extends N{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},K=class extends N{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},D=class extends N{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},Z=class extends N{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},H=class extends N{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},G=class extends N{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},Q=class extends N{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function X(t){const e=new O([]);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 x.Text:e=new _(n(x.Text,"Expected text token").value);break;case x.OpenStatement:e=function(){let e;switch(n(x.OpenStatement,"Expected opening statement token"),t[r].type){case x.Set:++r,e=a(),n(x.CloseStatement,"Expected closing statement token");break;case x.If:++r,e=c(),n(x.OpenStatement,"Expected {% token"),n(x.EndIf,"Expected endif token"),n(x.CloseStatement,"Expected %} token");break;case x.Macro:++r,e=function(){const t=v();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();n(x.CloseStatement,"Expected closing statement token");const r=[];for(;i(x.OpenStatement,x.EndMacro);)r.push(s());return new M(t,e,r)}(),n(x.OpenStatement,"Expected {% token"),n(x.EndMacro,"Expected endmacro token"),n(x.CloseStatement,"Expected %} token");break;case x.For:++r,e=function(){const t=u(!0);if(!(t instanceof P||t instanceof z))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(x.In,"Expected `in` keyword following loop variable");const e=h();n(x.CloseStatement,"Expected closing statement token");const a=[];for(;i(x.OpenStatement,x.EndFor)&&i(x.OpenStatement,x.Else);)a.push(s());const c=[];if(o(x.OpenStatement,x.Else))for(++r,++r,n(x.CloseStatement,"Expected closing statement token");i(x.OpenStatement,x.EndFor);)c.push(s());return new q(t,e,a,c)}(),n(x.OpenStatement,"Expected {% token"),n(x.EndFor,"Expected endfor token"),n(x.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case x.OpenExpression:e=function(){n(x.OpenExpression,"Expected opening expression token");const t=h();return n(x.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(x.Equals)){++r;const e=a();return new T(t,e)}return t}function c(){const e=h();n(x.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==x.OpenStatement||t[r+1]?.type!==x.ElseIf&&t[r+1]?.type!==x.Else&&t[r+1]?.type!==x.EndIf;)i.push(s());if(t[r]?.type===x.OpenStatement&&t[r+1]?.type!==x.EndIf)if(++r,o(x.ElseIf))n(x.ElseIf,"Expected elseif token"),a.push(c());else for(n(x.Else,"Expected else token"),n(x.CloseStatement,"Expected closing statement token");t[r]?.type!==x.OpenStatement||t[r+1]?.type!==x.EndIf;)a.push(s());return new C(e,i,a)}function u(t=!1){const e=t?v:h,n=[e()],s=o(x.Comma);for(;s&&(++r,n.push(e()),o(x.Comma)););return s?new z(n):n[0]}function h(){return function(){const t=l();if(o(x.If)){++r;const e=l();if(o(x.Else)){++r;const n=l();return new C(e,[t],[n])}return new D(t,e)}return t}()}function l(){let e=f();for(;o(x.Or);){const n=t[r];++r;const s=f();e=new W(n,e,s)}return e}function f(){let e=w();for(;o(x.And);){const n=t[r];++r;const s=w();e=new W(n,e,s)}return e}function w(){let e;for(;o(x.Not);){const n=t[r];++r;const s=w();e=new H(n,s)}return e??function(){let e=p();for(;o(x.ComparisonBinaryOperator)||o(x.In)||o(x.NotIn);){const n=t[r];++r;const s=p();e=new W(n,e,s)}return e}()}function p(){let e=b();for(;o(x.AdditiveBinaryOperator);){const n=t[r];++r;const s=b();e=new W(n,e,s)}return e}function d(t){let e=new V(t,y());return e=g(e),o(x.OpenParen)&&(e=d(e)),e}function y(){n(x.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(x.CloseParen);){let e=h();if(o(x.Equals)){if(++r,!(e instanceof P))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new Q(e,t)}t.push(e),o(x.Comma)&&++r}return t}();return n(x.CloseParen,"Expected closing parenthesis for arguments list"),t}function m(){const t=[];let e=!1;for(;!o(x.CloseSquareBracket);)o(x.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(x.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 G(...t)}return t[0]}function g(e){for(;o(x.Dot)||o(x.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==x.Dot;if(o)i=m(),n(x.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}function b(){let e=E();for(;o(x.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=E();e=new W(n,e,s)}return e}function E(){let t=function(){let t=function(){const t=g(v());return o(x.OpenParen)?d(t):t}();for(;o(x.Pipe);){++r;let e=v();if(!(e instanceof P))throw new SyntaxError("Expected identifier for the filter");o(x.OpenParen)&&(e=d(e)),t=new K(t,e)}return t}();for(;o(x.Is);){++r;const e=o(x.Not);e&&++r;let n=v();if(n instanceof B?n=new P(n.value.toString()):n instanceof L&&(n=new P("none")),!(n instanceof P))throw new SyntaxError("Expected identifier for the test");t=new Z(t,e,n)}return t}function v(){const e=t[r];switch(e.type){case x.NumericLiteral:return++r,new F(Number(e.value));case x.StringLiteral:return++r,new _(e.value);case x.BooleanLiteral:return++r,new B("true"===e.value.toLowerCase());case x.NullLiteral:return++r,new L(null);case x.Identifier:return++r,new P(e.value);case x.OpenParen:{++r;const e=u();if(t[r].type!==x.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case x.OpenSquareBracket:{++r;const t=[];for(;!o(x.CloseSquareBracket);)t.push(h()),o(x.Comma)&&++r;return++r,new R(t)}case x.OpenCurlyBracket:{++r;const t=new Map;for(;!o(x.CloseCurlyBracket);){const e=h();n(x.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(x.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 Y(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 tt(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 et(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var rt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new it(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},nt=class extends rt{constructor(){super(...arguments),this.type="NumericValue"}},st=class t extends rt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new ht((()=>new t(this.value.toUpperCase())))],["lower",new ht((()=>new t(this.value.toLowerCase())))],["strip",new ht((()=>new t(this.value.trim())))],["title",new ht((()=>new t(et(this.value))))],["length",new nt(this.value.length)],["rstrip",new ht((()=>new t(this.value.trimEnd())))],["lstrip",new ht((()=>new t(this.value.trimStart())))],["split",new ht((e=>{const r=e[0]??new lt;if(!(r instanceof t||r instanceof lt))throw new Error("sep argument must be a string or null");const n=e[1]??new nt(-1);if(!(n instanceof nt))throw new Error("maxsplit argument must be a number");let s=[];if(r instanceof lt){const t=this.value.trimStart();for(const{0:e,index:r}of t.matchAll(/\S+/g)){if(-1!==n.value&&s.length>=n.value&&void 0!==r){s.push(e+t.slice(r+e.length));break}s.push(e)}}else{if(""===r.value)throw new Error("empty separator");s=this.value.split(r.value),-1!==n.value&&s.length>n.value&&s.push(s.splice(n.value).join(r.value))}return new ct(s.map((e=>new t(e))))}))]])}},it=class extends rt{constructor(){super(...arguments),this.type="BooleanValue"}},ot=class extends rt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new ht((([t,e])=>{if(!(t instanceof st))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new lt}))],["items",new ht((()=>new ct(Array.from(this.value.entries()).map((([t,e])=>new ct([new st(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 it(this.value.size>0)}},at=class extends ot{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},ct=class extends rt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new nt(this.value.length)]])}__bool__(){return new it(this.value.length>0)}},ut=class extends ct{constructor(){super(...arguments),this.type="TupleValue"}},ht=class extends rt{constructor(){super(...arguments),this.type="FunctionValue"}},lt=class extends rt{constructor(){super(...arguments),this.type="NullValue"}},ft=class extends rt{constructor(){super(...arguments),this.type="UndefinedValue"}},wt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new ht((t=>{if(0===t.length)return new ot(new Map);if(1!==t.length||!(t[0]instanceof ot))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 ht],["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 ct||t instanceof st],["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,dt(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 ft}catch{return new ft}}},pt=class{constructor(t){this.global=t??new wt}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 it(r.value==n.value);case"!=":return new it(r.value!=n.value)}if(r instanceof ft||n instanceof ft)throw new Error("Cannot perform operation on undefined values");if(r instanceof lt||n instanceof lt)throw new Error("Cannot perform operation on null values");if(r instanceof nt&&n instanceof nt)switch(t.operator.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);case"%":return new nt(r.value%n.value);case"<":return new it(r.value<n.value);case">":return new it(r.value>n.value);case">=":return new it(r.value>=n.value);case"<=":return new it(r.value<=n.value)}else if(r instanceof ct&&n instanceof ct){if("+"===t.operator.value)return new ct(r.value.concat(n.value))}else if(n instanceof ct){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new it(e);case"not in":return new it(!e)}}if((r instanceof st||n instanceof st)&&"+"===t.operator.value)return new st(r.toString()+n.toString());if(r instanceof st&&n instanceof st)switch(t.operator.value){case"in":return new it(n.value.includes(r.value));case"not in":return new it(!n.value.includes(r.value))}if(r instanceof st&&n instanceof ot)switch(t.operator.value){case"in":return new it(n.value.has(r.value));case"not in":return new it(!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 ht)return s.value([r],e);if(r instanceof ct)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 nt(r.value.length);case"reverse":return new ct(r.value.reverse());case"sort":return new ct(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}`)}})));case"join":return new st(r.value.map((t=>t.value)).join(""));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof st)switch(n.value){case"length":return new nt(r.value.length);case"upper":return new st(r.value.toUpperCase());case"lower":return new st(r.value.toLowerCase());case"title":return new st(et(r.value));case"capitalize":return new st(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new st(r.value.trim());case"trimStart":return new st(r.value.trimStart());case"trimEnd":return new st(r.value.trimEnd());case"indent":return new st(r.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"join":case"string":return r;default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else{if(r instanceof nt){if("abs"===n.value)return new nt(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof ot)switch(n.value){case"items":return new ct(Array.from(r.value.entries()).map((([t,e])=>new ct([new st(t),e]))));case"length":return new nt(r.value.size);case"string":return new st(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 ht){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new at(s)),i.value([r,...t],e)}if(r instanceof ct){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof ot))))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 ct(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof st))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof ot))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new ft}));return new ct(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof st){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new nt(4);if(!(i instanceof nt))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new it(!1),a=t.at(2)??s.get("blank")??new it(!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 st(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 it(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new it(!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 st(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 at(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 ct||t instanceof st))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 nt||n instanceof ft))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof nt||s instanceof ft))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof nt||i instanceof ft))throw new Error("Slice step must be numeric or undefined");return t instanceof ct?new ct(tt(t.value,n.value,s.value,i.value)):new st(tt(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 st(t.property.value);if(r instanceof ot){if(!(n instanceof st))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 ct||r instanceof st)if(n instanceof nt)s=r.value.at(n.value),r instanceof st&&(s=new st(r.value.at(n.value)));else{if(!(n instanceof st))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof st))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof rt?s:new ft}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 ot))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 lt}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 wt(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 ct))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 wt(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 nt(e+1)],["index0",new nt(e)],["revindex",new nt(i.length-e)],["revindex0",new nt(i.length-e-1)],["first",new it(0===e)],["last",new it(e===i.length-1)],["length",new nt(i.length)],["previtem",e>0?i[e-1]:new ft],["nextitem",e<i.length-1?i[e+1]:new ft]]);r.setVariable("loop",new ot(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new st(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new ht(((e,r)=>{const n=new wt(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 lt}evaluate(t,e){if(void 0===t)return new ft;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 nt(Number(t.value));case"StringLiteral":return new st(t.value);case"BooleanLiteral":return new it(t.value);case"NullLiteral":return new lt(t.value);case"ArrayLiteral":return new ct(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new ut(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 st))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new ot(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 dt(t){switch(typeof t){case"number":return new nt(t);case"string":return new st(t);case"boolean":return new it(t);case"undefined":return new ft;case"object":return null===t?new lt:Array.isArray(t)?new ct(t.map(dt)):new ot(new Map(Object.entries(t).map((([t,e])=>[t,dt(e)]))),t);case"function":return new ht(((e,r)=>{const n=e.map((t=>yt(t)));return dt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function yt(t){let e=t;if(Array.isArray(t))e=t.map((t=>yt(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=yt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>yt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:yt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function mt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var gt={randomInt:mt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=mt(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[mt(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)},join:function(t,e=","){return Array.isArray(t)?t.join(e):t}};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 xt=class extends wt{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 xt}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===x.CloseStatement||t===x.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,x.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===x.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case x.Identifier:case x.NumericLiteral:case x.BooleanLiteral:case x.NullLiteral:case x.StringLiteral:case x.CloseParen:case x.CloseSquareBracket:break;default:{++s;const t=i(S);r.push(new v(`${e}${t}`,t.length>0?x.NumericLiteral:x.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,x.NumericLiteral))}else{if(!k(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(k),e=Object.hasOwn(E,t)?E[t]:x.Identifier;e===x.In&&r.at(-1)?.type===x.Not?(r.pop(),r.push(new v("not in",x.NotIn))):r.push(new v(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new v(t,x.StringLiteral)),++s}}return r}(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=X(r)}render(e){const r=new wt(t.global);if(r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",Y),e)for(const[t,n]of Object.entries(e))r.set(t,n);return new pt(r).run(this.parsed).toString()}};function vt(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=vt(t.object,e);break;case"FilterExpression":r=vt(t.operand,e);break;case"Set":{e||(e=[]);const n=vt(t.assignee);n&&e.push(n),r=vt(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function kt(t){let e;if("Program"===t.type)e=t.body.some((t=>kt(t)));else e=t.isStatement;return e}function St(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>St(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>St(t,e))).filter(Boolean).flat();break;case"If":r=[vt(t.test,e),...St(t.body,e),...St(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[vt(t.left,e),vt(t.right,e)].filter(Boolean);break;case"For":{const n=vt(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[vt(t.iterable,e),...St(t.body,e)].filter(Boolean);break}case"CallExpression":r=[vt(t.callee,e),...St(t.args,e)].filter(Boolean);break;default:r=[vt(t,e)].filter(Boolean)}return r}Et.global.assign(gt);function $t(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 jt(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 Et(r)}catch(t){}return e&&(n=kt(e.parsed)),n}getVariables(t=this.compiledTemplate){return St(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 At(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 At(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):At(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=At(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=At(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):At(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=At(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=$t(r)}catch(t){}if(e){n=jt(e).length>0}return n}getVariables(t=this.compiledTemplate){return jt(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=$t(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"]});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 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"]});var Ct=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function qt(t){const e=new Set;let r;for(;r=Ct.exec(t);){const t=r[3],n=r[6];if(t&&n||!t&&!n){const t=r[4];e.add(t)}}return[...e]}function Tt(t,e,r){return t.replace(Ct,((n,s,i,o,a,c,u)=>o&&!u?n:"\\"===s?n.slice(1):e[a]?e[a]===r?.[a]?e[a]:Tt(e[a],e,r):r?.[a]?r[a]===t?r[a]:Tt(r[a],e,r):c?c.startsWith("$")?Tt(c,e,r):c:""))}function Mt(t){return Object.keys(t).sort().map((e=>t[e]))}b.register(class extends b{static isTemplate(t){let e,r=!1;e="object"==typeof t?t.template:t;return r=qt(e).length>0,r}getVariables(t=this.template){return qt(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.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){const e={...process.env};return Tt(this.template,e,t)}},{name:"env",aliases:["js","javascript"]});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=Mt(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"]});require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var Nt=require("custom-ability"),It=(require("events-ex"),"event"),Vt="event-bus";(0,Nt.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Vt)?.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 Pt(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Ut=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||Pt(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=>Pt(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 Ft=c(require("xxhashjs")),{h32:_t,h64:Bt}=(c(require("base32768")),require("json-canonicalize"),require("hash-wasm"),Ft.default),Lt=(require("json-canonicalize"),c(require("base32768")),require("util-ex"),require("lodash-es"),require("util-ex"),require("lodash-es"),require("util-ex"),"[a-zA-Z_$][a-zA-Z_\\d$]*"),Rt=(new RegExp(`^\\s*(\\(\\s*\\)|${Lt}|\\(${`${Lt}\\s*(,\\s*${Lt})*`}\\))\\s*=>`),c(require("mime-type/with-db")),c(require("jschardet")),require("load-config-file")),zt=require("yaml"),Jt=require("yaml-types"),Wt=(require("mime-type/with-db"),[Jt.regexp]);Rt.Config.register([".yml",".yaml"],(function(t,e){if(e)if(e.customTags){if(Array.isArray(e.customTags))e.customTags=Wt.concat(e.customTags);else if("function"==typeof e.customTags){const t=e.customTags;e.customTags=e=>t(Wt.concat(e))}}else e.customTags=Wt;else e={customTags:Wt};return(0,zt.parse)(t,e)})),Rt.Config.register([".json"],(function(t){return JSON.parse(t)}));var Kt=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}},Dt=require("util-ex"),Zt=require("events-ex");function Ht(t=0){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 Gt=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=Ht(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const r=this._front+e&this._capacity-1;return this[r]=t,++e<=this._capacity&&(this._length=e),r}unshift(t){let e=this._length;this.checkCapacity(++e);const r=this._capacity,n=(this._front-1&r-1^r)-r;return this[n]=t,this._front=n,e<=this._capacity&&(this._length=e),n}pop(t){let e=this._length;if(0===e)return;let r=this._front+e-1&this._capacity-1,n=this[r];for(;--e>0&&t&&null==n;)r--,n=this[r];return this[r]=void 0,this._length=e,n}shift(t){let e=this._length;if(0===e)return;let r=this._front,n=this[r];for(;--e>0&&t&&null==n;)r=r+1&this._capacity-1,n=this[r];return this[r]=void 0,this._front=r+1&this._capacity-1,this._length=e,n}get size(){return this._length}get(t){let e;if(t===(0|t)){const r=this._length;t<0&&(t+=r),t>=0&&t<r&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,r=this._capacity;for(let n=0;n<t;++n)this[e+n&r-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const r=this._front,n=this._capacity-1,s=r+t&n,i=this[s];if(t<e/2)this.copyWithin(r+1&n,r,r+t&n),this[r]=void 0,this._front=r+1&n;else{this.copyWithin(s,s+1&n,r+e&n);this[r+e-1&n]=void 0}return this._length=e-1,i}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(Ht(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){!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,0,this,e,r+n&e-1)}}},Qt=require("@isdk/common-error"),Xt=32;function Yt(t){return"function"==typeof t}function te(){return"1"}var ee,re=class{constructor(t={}){const{initFn:e=te,pauseFn:r,resumeFn:n,capacity:s=Xt}=t;if(Yt(r)!==Yt(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new Gt(s),this.emitter=new Zt.EventEmitter,this.useDefaultTokens=e===te,this.pauseFn=r,this.resumeFn=n,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,r=this.waiting.shift(!0);r?this._dispatchTask(r,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",(t=>{this.onReleased(t)}))}_newReleaser(t){let e=!1;const r=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(r,t),r}_dispatchTask(t,e){const{resolve:r}=t;r(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,r=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const r=this.waiting.push(t),n=t.reject;return e&&e.addEventListener("abort",(()=>{this.waiting[r]=void 0;const t=e.reason instanceof Error?e.reason:new Qt.AbortError(e.reason||"aborted");e.alreadyRejected=!0,n(t)})),r};let n=this.tryAcquire(t);const s=n&&(0,Dt.isAsync)(n),i=e=>new Promise(((n,s)=>{const i={...t,resolve:n,reject:s,token:e};void 0===e?r(i):this._dispatchTask(i,{...t,token:e})}));return s?n.then((t=>i(t))):i(n)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new Qt.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},ne=class extends re{constructor(t,e){if("number"==typeof t)(e=e||{}).maxConcurrency=t;else{if("number"!=typeof(e=t).maxConcurrency)throw new Error("maxConcurrency must be set");t=e.maxConcurrency}super(e),this.maxConcurrency=e.maxConcurrency,e.isReadyFn&&(this.isReady=e.isReadyFn)}initFree(t){const e=t.maxConcurrency=Math.max(1,t.maxConcurrency);this.free=new Gt(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,Dt.isAsync)(e)){return e instanceof Promise||(e=e()),e.then((e=>{if(e)return this.lock(t)}))}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}},se=(require("@isdk/common-error"),require("custom-ability")),ie=require("util-ex"),oe=((ee=oe||{})[ee.MultiTask=1]="MultiTask",ee[ee.Cancelable=2]="Cancelable",ee[ee.Priority=4]="Priority",ee),ae=class extends AbortController{constructor(t){super(),(0,ie.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")}}},ce=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,r=this.__task_semaphore;return e>0&&!r&&(t&&(t=t.bind(this)),r=this.__task_semaphore=new ne(e-1,{isReadyFn:t})),r}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),Kt.has(r,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Kt.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);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(0);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(0)){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(0);if(!n&&r&&this.getRunningTask())throw new p.CommonError("The task is running",this.name,p.ErrorCode.TooManyRequests);const s=t?.aborter||new ae(this);if(!(s instanceof ae)){if(!(s instanceof AbortController))throw new p.CommonError("aborter should be an AbortController",this.name,p.ErrorCode.InvalidArgument);Object.setPrototypeOf(s,new ae(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(0)){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,ie.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.getSemaphore(r?.isReadyFn);if(s){const t=n,e=t.task;n=s.acquire({signal: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(0)){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)}}};ce.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},ce.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,se.createAbilityInjector)(ce,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=oe.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=r}}),c(require("memoizee")),require("json-canonicalize");var ue=c(require("path")),he=require("pkg-dir");require("util-ex");var le=c(require("path")),fe=require("url"),we=(require("@xenova/transformers"),(0,fe.fileURLToPath)(h)),pe=le.default.dirname(we),{exit:de}=(le.default.join(function(t){const e=(0,he.packageDirectorySync)({cwd:t});if(e)return e;const r=t.split(ue.default.sep);let n=r.lastIndexOf("dist");if(n>0)return r.slice(0,n).join(ue.default.sep);if(n=r.lastIndexOf("src"),n>0)return r.slice(0,n).join(ue.default.sep);throw new Error("can not find package directory")}(pe),".cache"),require("yaml"),require("lodash-es"),process),ye=class t extends f.AdvancePropertyManager{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}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),Kt.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();if(this.items[e]=r,r.alias){const t=r.alias;if("string"==typeof t)this.aliases[t]&&(0,p.throwError)(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const r of t)this.aliases[r]&&(0,p.throwError)(`Alias ${r} already exists for ${e}`),this.aliases[r]=e}n=r}return n}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return 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),Kt.has(e,t)}isStream(t){return this.stream}},me={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"},alias:{type:["array","string"]}};ye.defineProperties(ye,me);var ge=class extends ye{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}},be=new ge(Vt),xe=require("secondary-cache"),Ee=require("secondary-cache"),ve=xe.Cache;function ke({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 Se(t,e){let r=ye.get(t);return r||(r=new ye(t,{func:ke,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 xe.Cache(e)),r}var $e=Se("lrucache"),je=class t extends ye{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},s=["post","put","patch"];let i;e||(e=this.action||"post"),"res"===e&&(e="get"),n.headers&&n.headers["Content-Type"]||!s.includes(e)||(n.headers={"Content-Type":"application/json",...n.headers}),t?.stream&&!n.headers.Connection&&(n.headers.Connection="keep-alive"),r?("string"!=typeof r&&(r=JSON.stringify(r)),r=this.name+"/"+r):r=this.name,n.method=e.toUpperCase(),"get"===e||"delete"===e?i=r+this.getUrlParams(t):(n.body=JSON.stringify(t),i=r),n.headers&&!s.includes(e)&&delete n.headers["Content-Type"];const o=await fetch(`${this.apiRoot}/${i}`,n);if(!o.ok){throw await this.errorFrom(o)}return o}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()}},Ae={...y};je.defineProperties(je,Ae);var Oe=class extends je{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))}}},Ce={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};Oe.defineProperties(Oe,Ce);var qe=class extends Oe{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)}},Te=class extends qe{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=It,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)}},Me=new Te(It),Ne=require("util-ex"),Ie=class t extends ye{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({}){}},Ve={...y};Ie.defineProperties(Ie,Ve);var Pe=class extends Ie{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,Ne.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)}};Pe.defineProperties(Pe,{methods:{type:"array"}});var Ue=class extends Pe{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}},Fe=be.runSync(),_e=class t extends Ue{constructor(){super(...arguments),this.name=It,this.description="subscribe server sent event",this.result="event",this.depends={[Vt]:be}}static get sse(){return this._sse||(this._sse=new Ut),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=Fe.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)||Fe.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)Fe.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)}},Be=new _e(It);function Le(){be.register(),$e.register()}
1
+ "use strict";var t,e=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,h=(t,e,n,h)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let a of r(e))o.call(t,a)||a===n||s(t,a,{get:()=>e[a],enumerable:!(h=i(e,a))||h.enumerable});return t},a=(t,i,r)=>(r=null!=t?e(n(t)):{},h(!i&&t&&t.__esModule?r:s(r,"default",{value:t,enumerable:!0}),t)),c={};((t,e)=>{for(var i in e)s(t,i,{get:e[i],enumerable:!0})})(c,{EventClient:()=>vt,EventServer:()=>xt,EventToolFunc:()=>it,LRUCache:()=>ot.LRUCache,SecondaryCache:()=>ht,_lrucache:()=>at,createLRUCache:()=>ct,event:()=>rt,eventClient:()=>mt,eventServer:()=>St,lrucache:()=>ut,registerCoreTools:()=>jt}),module.exports=(t=c,h(s({},"__esModule",{value:!0}),t));var u=(()=>"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"),d=require("util-ex"),p=require("@isdk/common-error"),y=(require("custom-ability"),require("util-ex"),["get","post","put","delete","patch","list","res"]),v={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,s,i,r)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},m=(require("date-fns"),require("date-fns"),require("@isdk/template-engines"),require("@isdk/template-engines"));function b(t){return Object.keys(t).sort().map((e=>t[e]))}var g=class extends m.StringTemplate{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 m.StringTemplate?t.examplePrompt:m.StringTemplate.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 s=await this.examplePrompt.format(t);e.push(s)}else if("string"==typeof t)e.push(t);else if(t){const s=b(t);s.length>0&&e.push(...s)}const s=[this.prefix,...e,this.suffix].join(this.exampleSeparator),i=this.templateFormat;return await m.StringTemplate.format({template:s,data:t,templateFormat:i})}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}};m.StringTemplate.register(g,{name:"fewshot",aliases:["few_shot"]});(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}));require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var w=require("custom-ability"),q=(require("events-ex"),"event"),k="event-bus";(0,w.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(k)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.on(e,s)}once(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.once(e,s)}off(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.off(e,s)}emit(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,s):i.emit.call(this,e,this.name,...s)}emitError(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emit.call(this,"error",e,this.name,...s)}async emitAsync(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emitAsync.call(this,e,this.name,...s)}}}),!0);function A(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var x=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 s,i;this.active||(0,p.throwError)("Channel closed","SSEChannel",498);let r=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(r=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"):"",s="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:r,output:s});else{if(!this.clients.size)return;s="data: \n\n"}for([...this.clients].filter((t=>!r||A(t.events,r))).forEach(((t,e)=>{t.res.write(s)}));this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e,s){this.active||(0,p.throwError)("Channel closed","SSEChannel",498);const i={req:t,res:e,events:s},r=this.options.maxStreamDuration;let n="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";r>0&&(n+=", s-maxage="+(Math.floor(r/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":n,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),i.req.socket.setNoDelay(!0),i.res.writeHead(200,o);let h="retry: "+this.options.clientRetryInterval+"\n\n";const a=Number.parseInt(t.headers["last-event-id"],10),c=Number.isNaN(a)?this.options.rewind:this.nextID-1-a;return c&&this.messages.filter((t=>A(i.events,t.eventName))).slice(0-c).forEach((t=>{h+=t.output})),i.res.write(h),this.clients.add(i),r>0&&setTimeout((()=>{i.res.writableEnded||this.unsubscribe(i)}),r),i.res.on("close",(()=>this.unsubscribe(i))),i}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 s=e.req.socket.remoteAddress??"";s in t||(t[s]=0),t[s]++})),t}getSubscriberCount(){return this.clients.size}};require("eventsource-parser");require("uuid"),a(require("base32768")),require("uuid");var S=a(require("xxhashjs")),{h32:j,h64:E}=(a(require("base32768")),require("json-canonicalize"),require("hash-wasm"),S.default),C=(require("json-canonicalize"),a(require("base32768")),require("@isdk/util"),require("util-ex"),require("lodash-es"),require("util-ex"),require("lodash-es"),require("util-ex"),"[a-zA-Z_$][a-zA-Z_\\d$]*"),T=(new RegExp(`^\\s*(\\(\\s*\\)|${C}|\\(${`${C}\\s*(,\\s*${C})*`}\\))\\s*=>`),a(require("mime-type/with-db")),a(require("jschardet")),require("@isdk/util")),O=require("yaml-types");require("mime-type/with-db"),require("@isdk/util");(0,T.registerYamlTag)(O.regexp);var R=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}},$=require("util-ex"),F=require("events-ex");function P(t=0){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 M=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=P(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const s=this._front+e&this._capacity-1;return this[s]=t,++e<=this._capacity&&(this._length=e),s}unshift(t){let e=this._length;this.checkCapacity(++e);const s=this._capacity,i=(this._front-1&s-1^s)-s;return this[i]=t,this._front=i,e<=this._capacity&&(this._length=e),i}pop(t){let e=this._length;if(0===e)return;let s=this._front+e-1&this._capacity-1,i=this[s];for(;--e>0&&t&&null==i;)s--,i=this[s];return this[s]=void 0,this._length=e,i}shift(t){let e=this._length;if(0===e)return;let s=this._front,i=this[s];for(;--e>0&&t&&null==i;)s=s+1&this._capacity-1,i=this[s];return this[s]=void 0,this._front=s+1&this._capacity-1,this._length=e,i}get size(){return this._length}get(t){let e;if(t===(0|t)){const s=this._length;t<0&&(t+=s),t>=0&&t<s&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,s=this._capacity;for(let i=0;i<t;++i)this[e+i&s-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const s=this._front,i=this._capacity-1,r=s+t&i,n=this[r];if(t<e/2)this.copyWithin(s+1&i,s,s+t&i),this[s]=void 0,this._front=s+1&i;else{this.copyWithin(r,r+1&i,s+e&i);this[s+e-1&i]=void 0}return this._length=e-1,n}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(P(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const s=this._front,i=this._length;if(s+i>e){!function(t,e,s,i,r){for(let n=0;n<r;++n)s[n+i]=t[n+e],t[n+e]=void 0}(this,0,this,e,s+i&e-1)}}},_=require("@isdk/common-error"),I=32;function N(t){return"function"==typeof t}function z(){return"1"}var J,U=class{constructor(t={}){const{initFn:e=z,pauseFn:s,resumeFn:i,capacity:r=I}=t;if(N(s)!==N(i))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new M(r),this.emitter=new F.EventEmitter,this.useDefaultTokens=e===z,this.pauseFn=s,this.resumeFn=i,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,s=this.waiting.shift(!0);s?this._dispatchTask(s,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",(t=>{this.onReleased(t)}))}_newReleaser(t){let e=!1;const s=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(s,t),s}_dispatchTask(t,e){const{resolve:s}=t;s(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,s=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const s=this.waiting.push(t),i=t.reject;return e&&e.addEventListener("abort",(()=>{this.waiting[s]=void 0;const t=e.reason instanceof Error?e.reason:new _.AbortError(e.reason||"aborted");e.alreadyRejected=!0,i(t)})),s};let i=this.tryAcquire(t);const r=i&&(0,$.isAsync)(i),n=e=>new Promise(((i,r)=>{const n={...t,resolve:i,reject:r,token:e};void 0===e?s(n):this._dispatchTask(n,{...t,token:e})}));return r?i.then((t=>n(t))):n(i)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new _.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},W=class extends U{constructor(t,e){if("number"==typeof t)(e=e||{}).maxConcurrency=t;else{if("number"!=typeof(e=t).maxConcurrency)throw new Error("maxConcurrency must be set");t=e.maxConcurrency}super(e),this.maxConcurrency=e.maxConcurrency,e.isReadyFn&&(this.isReady=e.isReadyFn)}initFree(t){const e=t.maxConcurrency=Math.max(1,t.maxConcurrency);this.free=new M(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,$.isAsync)(e)){return e instanceof Promise||(e=e()),e.then((e=>{if(e)return this.lock(t)}))}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}},B=(require("@isdk/common-error"),require("custom-ability")),L=require("util-ex"),Z=((J=Z||{})[J.MultiTask=1]="MultiTask",J[J.Cancelable=2]="Cancelable",J[J.Priority=4]="Priority",J),D=class extends AbortController{constructor(t){super(),(0,L.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")}}},G=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,s=this.__task_semaphore;return e>0&&!s&&(t&&(t=t.bind(this)),s=this.__task_semaphore=new W(e-1,{isReadyFn:t})),s}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures;return e._asyncFeatures&&(s|=e._asyncFeatures),R.has(s,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),R.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".isAborted",p.ErrorCode.InvalidArgument);s=s[t]}return!s||s.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".getRunningTask",p.ErrorCode.InvalidArgument);s=s[t]}return s?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,s=void 0),s}getRunningTaskCount(){let t;if(this.hasAsyncFeature(0)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,s])=>{if(!s?.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 s=this.super,i=this.self||this;return t=s?s.call(i,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,s=!0){const i=this.hasAsyncFeature(0);if(!i&&s&&this.getRunningTask())throw new p.CommonError("The task is running",this.name,p.ErrorCode.TooManyRequests);const r=t?.aborter||new D(this);if(!(r instanceof D)){if(!(r instanceof AbortController))throw new p.CommonError("aborter should be an AbortController",this.name,p.ErrorCode.InvalidArgument);Object.setPrototypeOf(r,new D(this))}if(i){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),r.id=e,t[e]=r}else this.__task_aborter=r;const n=t?.timeout;return n>0&&(r.timeoutId=setTimeout((()=>{r.timeoutId=void 0,this.abort("timeout",{timeout:n})}),n)),r.signal.addEventListener("abort",(()=>{const t=r.timeoutId;t&&(r.timeoutId=void 0,clearTimeout(t));const e=r.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{r.streamController?.error(e.reason)}})),r}$cleanMultiTaskAborter(t,e){const s=this.super,i=this.self||this;s?s.call(i,t,e):i._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(0)){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,s){const i=this.createAborter(e,s?.taskId,s?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=i);let r=t(e,i).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(i)},s=function(t){const e=t||{};return new TransformStream({async start(t){const s=t.error;if(t.error=i=>{s.call(t,i),e.onError&&e.onError(i)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,s){try{let i;e.onTransform&&(i=await e.onTransform(t,s)),i||(i=t),s.enqueue(i)}catch(t){s.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,L.defineProperty)(i,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=i.id),t)});t=t.pipeThrough(s)}else this.cleanTaskAborter(i);return t})).catch((t=>{throw this.cleanTaskAborter(i),t})).finally((()=>{i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=void 0)}));return r.task=i,r}runAsyncCancelableTask(t={},e,s){let i=this.createTaskPromise(e,t,s);const r=this.getSemaphore(s?.isReadyFn);if(r){const t=i,e=t.task;i=r.acquire({signal:e.signal}).then((()=>t)).finally((()=>{r.release()})),i.task=e}return i}abort(t,e){let s=this.__task_aborter;if(s){const i=s;if(this.hasAsyncFeature(0)){const t=e?.taskId;if(null==t)throw new p.CommonError("Missing data.taskId",this.name+".abort",p.ErrorCode.InvalidArgument);s=s[t],this.cleanMultiTaskAborter(t,i)}else this.__task_aborter=void 0;s&&!s.signal.aborted&&s.abort(t,e)}}};G.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},G.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,B.createAbilityInjector)(G,"abort",{afterInjection:function(t,e){let s=t.prototype._asyncFeatures||0;s|=Z.Cancelable,e&&(e.asyncFeatures&&(s|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=s}}),a(require("memoizee")),require("json-canonicalize");var H=a(require("path")),K=require("pkg-dir");require("util-ex");var Q=a(require("path")),V=require("url"),X=(require("@xenova/transformers"),(0,V.fileURLToPath)(u)),Y=Q.default.dirname(X),{exit:tt}=(Q.default.join(function(t){const e=(0,K.packageDirectorySync)({cwd:t});if(e)return e;const s=t.split(H.default.sep);let i=s.lastIndexOf("dist");if(i>0)return s.slice(0,i).join(H.default.sep);if(i=s.lastIndexOf("src"),i>0)return s.slice(0,i).join(H.default.sep);throw new Error("can not find package directory")}(Y),".cache"),require("yaml"),require("lodash-es"),process),et=class t extends f.AdvancePropertyManager{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const s in this.list()){const i=this.get(s);let r=i.tags;if("string"==typeof r){if(r===t){e=i;break}}else if(Array.isArray(r)&&r.indexOf(t)>=0){e=i;break}}return e}static getAllByTag(t){let e=[];for(const s in this.list()){const i=this.get(s);let r=i.tags;"string"==typeof r?r===t&&e.push(i):Array.isArray(r)&&r.indexOf(t)>=0&&e.push(i)}return e}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures;return e._asyncFeatures&&(s|=e._asyncFeatures),R.has(s,t)}static run(t,e){const s=this.get(t);if(s)return s.run(e);throw new p.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const s=this.get(t);if(s)return s.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 s=this.get(t);if(s)return s.runWithPos(...e);throw new p.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const s=this.get(t);if(s)return s.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,s={}){switch(typeof e){case"string":s.name=e;break;case"function":s.func=e;break;case"object":s=e}e=s.name;let i=!!this.get(e);if(i)i=!1;else{if(!(s instanceof t))return i=new this(s),i.register();if(this.items[e]=s,s.alias){const t=s.alias;if("string"==typeof t)this.aliases[t]&&(0,p.throwError)(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const s of t)this.aliases[s]&&(0,p.throwError)(`Alias ${s} already exists for ${e}`),this.aliases[s]=e}i=s}return i}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return 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,s=this.depends;if(s){const e=Object.keys(s);for(const i of e){const e=s[i];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={},s=Object.keys(this.params);let i=Math.min(s.length,t.length);for(let r=0;r<i;r++)e[s[r]]=t[r];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const s=Object.keys(t);let i=Math.min(s.length,this.params.length);for(let r=0;r<i;r++)e.push(t[s[r]])}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),R.has(e,t)}isStream(t){return this.stream}},st={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,s,i,r){let n=t;const o=typeof t;return r.isExported?n="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),n=(0,d._createFunction)(t,e.scope)),n}},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"},alias:{type:["array","string"]}};et.defineProperties(et,st);var it=class extends et{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}},rt=new it(k),nt=require("secondary-cache"),ot=require("secondary-cache"),ht=nt.Cache;function at({key:t,value:e,options:s}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,s):this.cache.get(t):(s&&this.cache.setDefaultOptions(s),this.cache)}function ct(t,e){let s=et.get(t);return s||(s=new et(t,{func:at,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"}),s.cache=new nt.Cache(e)),s}var ut=ct("lrucache"),lt=class t extends et{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 s in e){const i=this.get(s),r=e[s];i?i instanceof t?i.assign(r):(0,p.throwError)(`${s} already registered as ${i.constructor.name}`,"ClientTools"):this.register(r)}}static async fetch(t,e){const s=this.get(t);if(s&&s.fetch)return s.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,s){const i={...this.fetchOptions},r=["post","put","patch"];let n;e||(e=this.action||"post"),"res"===e&&(e="get"),i.headers&&i.headers["Content-Type"]||!r.includes(e)||(i.headers={"Content-Type":"application/json",...i.headers}),t?.stream&&!i.headers.Connection&&(i.headers.Connection="keep-alive"),s?("string"!=typeof s&&(s=JSON.stringify(s)),s=this.name+"/"+s):s=this.name,i.method=e.toUpperCase(),"get"===e||"delete"===e?n=s+this.getUrlParams(t):(i.body=JSON.stringify(t),n=s),i.headers&&!r.includes(e)&&delete i.headers["Content-Type"];const o=await fetch(`${this.apiRoot}/${n}`,i);if(!o.ok){throw await this.errorFrom(o)}return o}async errorFrom(t){let e,s=t.status,i=t.statusText,r=this.name;if(t.body){const s=await t.text();try{const t=JSON.parse(s);t&&(t.error&&(i=t.error),t.name&&(r=t.name),t.data&&(e=t.data,e.name=r,e.what&&(e.msg=i,i=e.what)),t.message&&(i=i+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return(0,p.createError)(i,r,s)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},ft={...v};lt.defineProperties(lt,ft);var dt=class extends lt{async _func(t,e){const s=await this.fetch(e,t);if(e?.stream)return s;return await s.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))}}},pt={methods:{type:"array",assign(t,e,s,i,r){r?.isExported||e.assignMethods(t)}}};dt.defineProperties(dt,pt);var yt=class extends dt{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let s=t.id;return s||(0,p.throwError)("id is required"),"string"==typeof s&&(s=encodeURIComponent(s)),delete t.id,super.fetch(t,e,s)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},vt=class extends yt{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=q,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}):"",s=`${this.apiRoot}/${this.name}${e}`,i=this._es=new EventSource(s);return Object.entries(this._sseEvents).forEach((([t,e])=>{i.addEventListener(t,e)})),this._esEvents=t,i}esListener(t){const e=t.data?JSON.parse(t.data):void 0,s=t.type;if(!this._forwardEvents.has(s)){const t=this.emitter;t&&e&&s&&(Array.isArray(e)?t.emit(s,...e):t.emit(s,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const s=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);s.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)}},mt=new vt(q),bt=require("util-ex"),gt=class t extends et{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const s in this.items){let i=this.items[s];(i instanceof t||i.isApi)&&(i.allowExportFunc||(i=i.toJSON(),delete i.func),e[s]=i)}return e}func({}){}},wt={...v};gt.defineProperties(gt,wt);var qt=class extends gt{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const s=this.methods=[];this.initRpcMethods(s)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const s of e)"function"==typeof this[s]&&t.push(s);(0,bt.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const s=e.slice(1);void 0===this[s]&&(this[s]=this[e])}))}cast(t,e){let s=this.params[t];return s&&("string"!=typeof s&&(s=s.type),"number"===s&&(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)}};qt.defineProperties(qt,{methods:{type:"array"}});var kt=class extends qt{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=y}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}},At=rt.runSync(),xt=class t extends kt{constructor(){super(...arguments),this.name=q,this.description="subscribe server sent event",this.result="event",this.depends={[k]:rt}}static get sse(){return this._sse||(this._sse=new x),this._sse}get sse(){return this.constructor.sse}static publish(e,s){return t.sse.publish(e,s)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,s,i){return t.sse.subscribe(e,s,i)}static alreadyForward(e){const s=At.listeners(e);for(const e of s)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,s){return"string"==typeof s&&(s=[s]),this.constructor.subscribe(t,e,s)}forward(e){Array.isArray(e)||(e=[e]);for(const s of e)t.alreadyForward(s)||At.on(s,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const s of e)At.off(s,t.ebListener)}list({_req:t,_res:e,event:s}){t&&e&&this.subscribeSSE(t,e,s)}$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 s of t)this.publishSSE(e,s);return{event:t}}(0,p.throwError)("event or data is required","pub",p.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},St=new xt(q);function jt(){rt.register(),ut.register()}
package/dist/funcs.mjs CHANGED
@@ -1 +1 @@
1
- import{EventClient as m,EventServer as o,EventToolFunc as r,LRUCache as p,SecondaryCache as t,_lrucache as c,createLRUCache as h,event as i,eventClient as j,eventServer as k,lrucache as n,registerCoreTools as s}from"./chunk-XLXW6OPN.mjs";import"./chunk-VIG2GB47.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as LRUCache,t as SecondaryCache,c as _lrucache,h as createLRUCache,i as event,j as eventClient,k as eventServer,n as lrucache,s as registerCoreTools};
1
+ import{EventClient as m,EventServer as o,EventToolFunc as r,LRUCache as p,SecondaryCache as t,_lrucache as c,createLRUCache as h,event as i,eventClient as j,eventServer as k,lrucache as n,registerCoreTools as s}from"./chunk-OYDBRUZJ.mjs";import"./chunk-VIG2GB47.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as LRUCache,t as SecondaryCache,c as _lrucache,h as createLRUCache,i as event,j as eventClient,k as eventServer,n as lrucache,s as registerCoreTools};