@isdk/ai-tool 0.5.6 → 0.5.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-YVFGQB4L.mjs +1 -0
- package/dist/funcs.d.mts +1 -1
- package/dist/funcs.d.ts +1 -1
- package/dist/funcs.js +1 -1
- package/dist/funcs.mjs +1 -1
- package/dist/{index-Br-4ZYgE.d.mts → index-BkwhCK1q.d.mts} +7 -0
- package/dist/{index-Br-4ZYgE.d.ts → index-BkwhCK1q.d.ts} +7 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/docs/classes/BinarySemaphore.md +25 -25
- package/docs/classes/CancelableAbility.md +25 -25
- package/docs/classes/ClientTools.md +83 -55
- package/docs/classes/EnvPromptTemplate.md +19 -19
- package/docs/classes/EventClient.md +106 -78
- package/docs/classes/EventServer.md +107 -79
- package/docs/classes/EventToolFunc.md +75 -47
- package/docs/classes/FStringPromptTemplate.md +19 -19
- package/docs/classes/FewShotPromptTemplate.md +23 -23
- package/docs/classes/GolangPromptTemplate.md +19 -19
- package/docs/classes/HFEnvironment.md +10 -10
- package/docs/classes/HFInterpreter.md +5 -5
- package/docs/classes/HFTemplate.md +5 -5
- package/docs/classes/HfPromptTemplate.md +19 -19
- package/docs/classes/IntSet.md +12 -12
- package/docs/classes/PromptExampleSelector.md +9 -9
- package/docs/classes/PromptTemplate.md +18 -18
- package/docs/classes/ReadableStreamError.md +2 -2
- package/docs/classes/ResClientTools.md +82 -62
- package/docs/classes/ResServerTools.md +83 -63
- package/docs/classes/SSEChannel.md +16 -16
- package/docs/classes/Semaphore.md +26 -26
- package/docs/classes/ServerTools.md +79 -51
- package/docs/classes/SignalGate.md +9 -9
- package/docs/classes/TaskAbortController.md +8 -8
- package/docs/classes/ToolFunc.md +68 -44
- package/docs/classes/YamlTypeBaseObject.md +2 -2
- package/docs/enumerations/AsyncFeatureBits.md +4 -4
- package/docs/enumerations/AsyncFeatures.md +4 -4
- package/docs/enumerations/HashAlgorithm.md +12 -12
- package/docs/functions/AIArgProcessor.md +1 -1
- package/docs/functions/AIStream.md +1 -1
- package/docs/functions/ChoiceArgProcessor.md +1 -1
- package/docs/functions/ObjectArgsToArgsInfo.md +1 -1
- package/docs/functions/RateLimit.md +1 -1
- package/docs/functions/TemplateArgProcessor.md +1 -1
- package/docs/functions/assignDirs.md +1 -1
- package/docs/functions/backendEventable.md +1 -1
- package/docs/functions/beforeShutdown.md +1 -1
- package/docs/functions/completeSentences.md +1 -1
- package/docs/functions/concatText.md +1 -1
- package/docs/functions/countLLMTokens.md +1 -1
- package/docs/functions/countRegexMatches.md +1 -1
- package/docs/functions/createCallbacksTransformer.md +1 -1
- package/docs/functions/createEmptyReadableStream.md +1 -1
- package/docs/functions/createEndWithRepetitionDetector.md +1 -1
- package/docs/functions/createEventStreamTransformer.md +1 -1
- package/docs/functions/createHfValueFunc.md +1 -1
- package/docs/functions/createLRUCache.md +1 -1
- package/docs/functions/createYamlObjectTag.md +1 -1
- package/docs/functions/dateToText.md +1 -1
- package/docs/functions/decodeCharset.md +1 -1
- package/docs/functions/detectCharset.md +1 -1
- package/docs/functions/encodeLLMTokens.md +1 -1
- package/docs/functions/ensureQuoted.md +1 -1
- package/docs/functions/expandConfig.md +1 -1
- package/docs/functions/expandEnv.md +1 -1
- package/docs/functions/expandObjEnv.md +1 -1
- package/docs/functions/expandPath.md +1 -1
- package/docs/functions/extNameLevel.md +1 -1
- package/docs/functions/fileIsExists.md +1 -1
- package/docs/functions/filenameReservedRegex.md +1 -1
- package/docs/functions/filterValidFnScope.md +1 -1
- package/docs/functions/findIndexNonEmptyFrom.md +1 -1
- package/docs/functions/findPort.md +1 -1
- package/docs/functions/formatTextWithSpace.md +1 -1
- package/docs/functions/getAllEnumKeys.md +1 -1
- package/docs/functions/getConfigFileNames.md +1 -1
- package/docs/functions/getConfigs.md +1 -1
- package/docs/functions/getEnvVairables.md +1 -1
- package/docs/functions/getFileMetaInfo.md +1 -1
- package/docs/functions/getHashAlgoBySize.md +1 -1
- package/docs/functions/getKeysPath.md +1 -1
- package/docs/functions/getLLMTokenizer.md +1 -1
- package/docs/functions/getMultiLevelExtname.md +1 -1
- package/docs/functions/getPackageDir.md +1 -1
- package/docs/functions/getRealFilepath.md +1 -1
- package/docs/functions/getResponseErrorReadableStream.md +1 -1
- package/docs/functions/getXDGConfigs.md +1 -1
- package/docs/functions/hasDirectoryIn.md +1 -1
- package/docs/functions/hash.md +1 -1
- package/docs/functions/hashFile.md +1 -1
- package/docs/functions/hashStream.md +1 -1
- package/docs/functions/hfParse.md +1 -1
- package/docs/functions/hfTokenize.md +1 -1
- package/docs/functions/initShutdown.md +1 -1
- package/docs/functions/interpolateEnv.md +1 -1
- package/docs/functions/interpolateFString.md +1 -1
- package/docs/functions/interpolateGolangTemplate.md +1 -1
- package/docs/functions/isLangUsingSpaces.md +1 -1
- package/docs/functions/isListItemString.md +1 -1
- package/docs/functions/isModelNameMatched.md +1 -1
- package/docs/functions/isPunctuationChar.md +1 -1
- package/docs/functions/isQuoted.md +1 -1
- package/docs/functions/isRegExp.md +1 -1
- package/docs/functions/isSameString.md +1 -1
- package/docs/functions/isSectionString.md +1 -1
- package/docs/functions/isSentenceEnding.md +1 -1
- package/docs/functions/isSepLineString.md +1 -1
- package/docs/functions/isStrWrapped.md +1 -1
- package/docs/functions/isSubdirectory.md +1 -1
- package/docs/functions/isTitleString.md +1 -1
- package/docs/functions/isValidFilename.md +1 -1
- package/docs/functions/isValidFilepath.md +1 -1
- package/docs/functions/isWebStream.md +1 -1
- package/docs/functions/jsonFilterToWhere.md +1 -1
- package/docs/functions/jsonToMarkdownStr.md +1 -1
- package/docs/functions/loadAIConfig.md +1 -1
- package/docs/functions/loadConfig.md +1 -1
- package/docs/functions/loadConfigFile.md +1 -1
- package/docs/functions/loadFileFromPaths.md +1 -1
- package/docs/functions/loadTextFromPaths.md +1 -1
- package/docs/functions/lrucache.md +1 -1
- package/docs/functions/makeToolFuncCancelable.md +1 -1
- package/docs/functions/matchUrlProtocol.md +1 -1
- package/docs/functions/memoize.md +1 -1
- package/docs/functions/messagesToText.md +1 -1
- package/docs/functions/paramsSizeToScaleStr.md +1 -1
- package/docs/functions/parseCommand.md +1 -1
- package/docs/functions/parseFString.md +1 -1
- package/docs/functions/parseJsJson.md +1 -1
- package/docs/functions/parseJsJsonSimpleSync.md +1 -1
- package/docs/functions/parseObjectArgInfo.md +1 -1
- package/docs/functions/parseObjectArgumentInfos.md +1 -1
- package/docs/functions/parseObjectArguments.md +1 -1
- package/docs/functions/parseObjectArgumentsAsArgInfos.md +1 -1
- package/docs/functions/parseYaml.md +1 -1
- package/docs/functions/quoteStr.md +1 -1
- package/docs/functions/reControlCharsRegex.md +1 -1
- package/docs/functions/readFilenamesRecursiveSync.md +1 -1
- package/docs/functions/readTextFileChunks.md +1 -1
- package/docs/functions/readTextFileChunksEx.md +1 -1
- package/docs/functions/readableFromAsyncIterable.md +1 -1
- package/docs/functions/registerCoreTools.md +1 -1
- package/docs/functions/registerYamlTag.md +1 -1
- package/docs/functions/removeMarkdownBold.md +1 -1
- package/docs/functions/removeMarkdownBoldAndItalic.md +1 -1
- package/docs/functions/removeMarkdownItalic.md +1 -1
- package/docs/functions/replaceWithPlaceholder.md +1 -1
- package/docs/functions/restoreFromPlacehoders.md +1 -1
- package/docs/functions/sanitizeFilename.md +1 -1
- package/docs/functions/sanitizeFilepath.md +1 -1
- package/docs/functions/saveConfigFile.md +1 -1
- package/docs/functions/scaleStrToParamsSize.md +1 -1
- package/docs/functions/shutdown.md +1 -1
- package/docs/functions/simplifyObjectArguments.md +1 -1
- package/docs/functions/sortedValues.md +1 -1
- package/docs/functions/splitChunks.md +1 -1
- package/docs/functions/splitParagraph.md +1 -1
- package/docs/functions/splitSentence.md +1 -1
- package/docs/functions/stringifyYaml.md +1 -1
- package/docs/functions/stripConsoleColor.md +1 -1
- package/docs/functions/textToDate.md +1 -1
- package/docs/functions/toDateTime.md +1 -1
- package/docs/functions/trimStartOfStreamHelper.md +1 -1
- package/docs/functions/truncTo.md +1 -1
- package/docs/functions/truncateByToken.md +1 -1
- package/docs/functions/truncateToTokenLimit.md +1 -1
- package/docs/functions/truncateToTokenLimitEx.md +1 -1
- package/docs/functions/uuid.md +1 -1
- package/docs/functions/wait.md +1 -1
- package/docs/functions/xxhash.md +1 -1
- package/docs/functions/xxhash32.md +1 -1
- package/docs/functions/xxhash64.md +1 -1
- package/docs/functions/xxhashAsStr.md +1 -1
- package/docs/interfaces/AIChatAssistantMessageParam.md +12 -12
- package/docs/interfaces/AIChatContentPartImage.md +3 -3
- package/docs/interfaces/AIChatContentPartText.md +3 -3
- package/docs/interfaces/AIChatMessageParamBase.md +7 -7
- package/docs/interfaces/AIChatMessageToolCall.md +4 -4
- package/docs/interfaces/AIChatSystemMessageParam.md +9 -9
- package/docs/interfaces/AIChatToolChoiceFuncObject.md +3 -3
- package/docs/interfaces/AIChatToolChoiceObject.md +2 -2
- package/docs/interfaces/AIChatToolFunc.md +5 -5
- package/docs/interfaces/AIChatToolFuncParam.md +3 -3
- package/docs/interfaces/AIChatToolMessageParam.md +10 -10
- package/docs/interfaces/AIChatToolParam.md +2 -2
- package/docs/interfaces/AIChatToolTypeObject.md +2 -2
- package/docs/interfaces/AIChatUserMessageParam.md +13 -13
- package/docs/interfaces/AIChoiceConfig.md +8 -8
- package/docs/interfaces/AIResult.md +6 -6
- package/docs/interfaces/AIStreamParser.md +2 -2
- package/docs/interfaces/AIStreamParserOptions.md +2 -2
- package/docs/interfaces/BaseFunc.md +22 -10
- package/docs/interfaces/BaseFuncItem.md +17 -9
- package/docs/interfaces/BinarySemaphoreAcquireOptions.md +2 -2
- package/docs/interfaces/BinarySemaphoreOptions.md +5 -5
- package/docs/interfaces/BinarySemaphoreReleaseOptions.md +2 -2
- package/docs/interfaces/BinarySemaphoreReleaserFunc.md +3 -3
- package/docs/interfaces/CancelableAbilityOptions.md +4 -4
- package/docs/interfaces/ClientFuncItem.md +24 -12
- package/docs/interfaces/DotenvExpandOptions.md +4 -4
- package/docs/interfaces/DotenvExpandOutput.md +3 -3
- package/docs/interfaces/DotenvParseInput.md +1 -1
- package/docs/interfaces/DotenvParseOutput.md +1 -1
- package/docs/interfaces/DotenvPopulateInput.md +1 -1
- package/docs/interfaces/EventClientFuncParams.md +5 -5
- package/docs/interfaces/EventServerFuncParams.md +6 -6
- package/docs/interfaces/FewShotPromptTemplateOptions.md +12 -12
- package/docs/interfaces/FuncItem.md +22 -10
- package/docs/interfaces/FuncParam.md +7 -7
- package/docs/interfaces/FuncParams.md +1 -1
- package/docs/interfaces/Funcs.md +1 -1
- package/docs/interfaces/HashAlgoParams.md +4 -4
- package/docs/interfaces/IFileMetaInfo.md +8 -8
- package/docs/interfaces/IReadTextFileChunksOptions.md +11 -11
- package/docs/interfaces/ITruncateToTokenLimitOptions.md +10 -10
- package/docs/interfaces/JsonFilter.md +1 -1
- package/docs/interfaces/ParseObjectArgumentOptions.md +11 -11
- package/docs/interfaces/PromptExampleSelectorOptions.md +3 -3
- package/docs/interfaces/PromptTemplateOptions.md +7 -7
- package/docs/interfaces/RemoteFuncItem.md +24 -12
- package/docs/interfaces/ReplacePlacehoderOptions.md +5 -5
- package/docs/interfaces/ResClientFuncParams.md +3 -3
- package/docs/interfaces/ResServerFuncParams.md +6 -6
- package/docs/interfaces/SanitizeFilenameOptions.md +3 -3
- package/docs/interfaces/SectionStringOptions.md +3 -3
- package/docs/interfaces/SemaphoreOptions.md +7 -7
- package/docs/interfaces/SemaphoreTaskItem.md +5 -5
- package/docs/interfaces/ServerFuncItem.md +25 -13
- package/docs/interfaces/ServerFuncParams.md +3 -3
- package/docs/interfaces/SplitSentenceOptions.md +5 -5
- package/docs/interfaces/StreamCallbacksAndOptions.md +5 -5
- package/docs/interfaces/TaskAbortControllers.md +1 -1
- package/docs/interfaces/TaskPromise.md +2 -2
- package/docs/interfaces/ToolFuncPackage.md +4 -4
- package/docs/type-aliases/AIChatContentPart.md +1 -1
- package/docs/type-aliases/AIChatMessageParam.md +1 -1
- package/docs/type-aliases/AIChatRole.md +1 -1
- package/docs/type-aliases/AIChatToolChoiceParam.md +1 -1
- package/docs/type-aliases/AIMessageType.md +1 -1
- package/docs/type-aliases/AIModelNameRule.md +1 -1
- package/docs/type-aliases/AIModelNameRuleFn.md +1 -1
- package/docs/type-aliases/AIModelNameRules.md +1 -1
- package/docs/type-aliases/AITextGenerationFinishReason.md +1 -1
- package/docs/type-aliases/ActionName.md +1 -1
- package/docs/type-aliases/AsyncTaskId.md +1 -1
- package/docs/type-aliases/BeforeShutdownListener.md +1 -1
- package/docs/type-aliases/EventErrorListenerFn.md +1 -1
- package/docs/type-aliases/EventListenerFn.md +1 -1
- package/docs/type-aliases/FStringPromptTemplateNode.md +1 -1
- package/docs/type-aliases/FuncParamType.md +1 -1
- package/docs/type-aliases/PromptExamples.md +1 -1
- package/docs/type-aliases/PromptTemplateType.md +1 -1
- package/docs/type-aliases/PromptType.md +1 -1
- package/docs/type-aliases/SemaphoreIsReadyFuncType.md +1 -1
- package/docs/type-aliases/TFunc.md +1 -1
- package/docs/variables/AIChatRoles.md +1 -1
- package/docs/variables/AIMessageTypes.md +1 -1
- package/docs/variables/AITextGenerationFinishReasons.md +1 -1
- package/docs/variables/ActionNames.md +1 -1
- package/docs/variables/ClientToolFuncSchema.md +1 -1
- package/docs/variables/DEFAULT_CONFIG_NAME.md +1 -1
- package/docs/variables/DefaultAsyncSemaphoreCapacity.md +1 -1
- package/docs/variables/EventBusName.md +1 -1
- package/docs/variables/EventName.md +1 -1
- package/docs/variables/FilenameReservedRegex.md +1 -1
- package/docs/variables/HFBuiltins.md +1 -1
- package/docs/variables/LLM_TOKENIZER_NAMES.md +1 -1
- package/docs/variables/LLM_TOKENIZER_NAMES_MAP.md +1 -1
- package/docs/variables/PASSING_SCORE.md +1 -1
- package/docs/variables/PromptTemplateTypes.md +1 -1
- package/docs/variables/PromptTypes.md +1 -1
- package/docs/variables/RStreamErrCode.md +1 -1
- package/docs/variables/RemoteToolFuncSchema.md +1 -1
- package/docs/variables/ResponseRStreamErrCode.md +1 -1
- package/docs/variables/SHUTDOWN_SIGNALS.md +1 -1
- package/docs/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
- package/docs/variables/SecondaryCache.md +1 -1
- package/docs/variables/ServerToolFuncSchema.md +1 -1
- package/docs/variables/ToolAsyncCancelableBit.md +1 -1
- package/docs/variables/ToolAsyncMultiTaskBit.md +1 -1
- package/docs/variables/ToolAsyncPriorityBit.md +1 -1
- package/docs/variables/ToolFuncSchema.md +9 -1
- package/docs/variables/WindowsReservedNameRegex.md +1 -1
- package/docs/variables/base32768.md +1 -1
- package/docs/variables/defaultTemplateFormat.md +1 -1
- package/docs/variables/event.md +1 -1
- package/docs/variables/eventClient.md +1 -1
- package/docs/variables/eventServer.md +1 -1
- package/docs/variables/lrucache.md +1 -1
- package/package.json +1 -1
- package/dist/chunk-OHVYEOHR.mjs +0 -1
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:()=>be,LRUCache:()=>Ee.LRUCache,SecondaryCache:()=>ve,_lrucache:()=>ke,createLRUCache:()=>Se,event:()=>ge,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 b="default",g=class t extends m.BaseFactory{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const r=e.templateFormat||b,n=t.get(r);return n.isTemplate!==t.isTemplate&&n.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,r){"string"==typeof e?(r||(r={}),r.template=e):e&&(e=(r=e).template);const{templateFormat:n}=r||{};if(super(r),this.constructor===t){const e=t.get(n||b);if(e)return Reflect.construct(e,arguments);throw new p.CommonError(`Prompt template type ${n} not found`,"PromptTemplate",p.ErrorCode.InvalidArgument)}}_initialize(t){throw new p.NotImplementationError("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new p.NotImplementationError("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{0}));var 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 O=class{constructor(){this.type="Statement"}},A=class extends O{constructor(t){super(),this.body=t,this.type="Program"}},C=class extends O{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},q=class extends O{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},T=class extends O{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},M=class extends O{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},N=class extends O{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 A([]);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=g();for(;o(x.AdditiveBinaryOperator);){const n=t[r];++r;const s=g();e=new W(n,e,s)}return e}function d(t){let e=new V(t,y());return e=b(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 b(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 g(){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=b(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 bt={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),gt(t,e,r)},join:function(t,e=","){return Array.isArray(t)?t.join(e):t}};function gt(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=>gt(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}": ${gt(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(bt);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]}g.register(class extends g{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=new Et(r)}catch(t){}return e&&(n=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 Ot(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function At(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 Ot(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):Ot(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=Ot(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=Ot(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):Ot(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=Ot(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}g.register(class extends g{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=$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"]});g.register(class extends g{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return At(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 At(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]))}g.register(class extends g{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"]});g.register(class extends g{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof g?t.examplePrompt:g.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const r=await this.examplePrompt.format(t);e.push(r)}else if("string"==typeof t)e.push(t);else if(t){const r=Mt(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await g.format({template:r,data:t,templateFormat:n})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}},{name:"fewshot",aliases:["few_shot"]});require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var 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 get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const r in this.list()){const n=this.get(r);let s=n.tags;if("string"==typeof s){if(s===t){e=n;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=n;break}}return e}static getAllByTag(t){let e=[];for(const r in this.list()){const n=this.get(r);let s=n.tags;"string"==typeof s?s===t&&e.push(n):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(n)}return e}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),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();this.items[e]=r,n=r}return n}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,r=this.depends;if(r){const e=Object.keys(r);for(const n of e){const e=r[n];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},r=Object.keys(this.params);let n=Math.min(r.length,t.length);for(let s=0;s<n;s++)e[r[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const r=Object.keys(t);let n=Math.min(r.length,this.params.length);for(let s=0;s<n;s++)e.push(t[r[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,p.throwError)("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),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"}};ye.defineProperties(ye,me);var be=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}},ge=new be(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()}},Oe={...y};je.defineProperties(je,Oe);var Ae=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)}}};Ae.defineProperties(Ae,Ce);var qe=class extends Ae{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=ge.runSync(),_e=class t extends Ue{constructor(){super(...arguments),this.name=It,this.description="subscribe server sent event",this.result="event",this.depends={[Vt]:ge}}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(){ge.register(),$e.register()}
|
|
1
|
+
"use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},c=(t,n,s)=>(s=null!=t?e(i(t)):{},a(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})})(u,{EventClient:()=>Te,EventServer:()=>_e,EventToolFunc:()=>be,LRUCache:()=>Ee.LRUCache,SecondaryCache:()=>ve,_lrucache:()=>ke,createLRUCache:()=>Se,event:()=>ge,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 b="default",g=class t extends m.BaseFactory{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const r=e.templateFormat||b,n=t.get(r);return n.isTemplate!==t.isTemplate&&n.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,r){"string"==typeof e?(r||(r={}),r.template=e):e&&(e=(r=e).template);const{templateFormat:n}=r||{};if(super(r),this.constructor===t){const e=t.get(n||b);if(e)return Reflect.construct(e,arguments);throw new p.CommonError(`Prompt template type ${n} not found`,"PromptTemplate",p.ErrorCode.InvalidArgument)}}_initialize(t){throw new p.NotImplementationError("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new p.NotImplementationError("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{0}));var 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 O=class{constructor(){this.type="Statement"}},A=class extends O{constructor(t){super(),this.body=t,this.type="Program"}},C=class extends O{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},q=class extends O{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},T=class extends O{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},M=class extends O{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},N=class extends O{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 A([]);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=g();for(;o(x.AdditiveBinaryOperator);){const n=t[r];++r;const s=g();e=new W(n,e,s)}return e}function d(t){let e=new V(t,y());return e=b(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 b(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 g(){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=b(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 bt={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),gt(t,e,r)},join:function(t,e=","){return Array.isArray(t)?t.join(e):t}};function gt(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=>gt(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}": ${gt(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(bt);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]}g.register(class extends g{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=new Et(r)}catch(t){}return e&&(n=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){function e(t,r){return r||(r=new Set),!!r.has(t)||"object"==typeof t&&null!==t&&(r.add(t),Object.values(t).some((t=>e(t,r))))}return t=Object.fromEntries(Object.entries(t).filter((([t,r])=>!e(r)))),this.compiledTemplate.render(t)}},{name:"hf",aliases:["huggingface","internal","default"]});function Ot(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function At(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 Ot(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):Ot(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=Ot(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=Ot(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):Ot(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=Ot(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}g.register(class extends g{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=$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"]});g.register(class extends g{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return At(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 At(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]))}g.register(class extends g{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"]});g.register(class extends g{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof g?t.examplePrompt:g.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const r=await this.examplePrompt.format(t);e.push(r)}else if("string"==typeof t)e.push(t);else if(t){const r=Mt(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await g.format({template:r,data:t,templateFormat:n})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}},{name:"fewshot",aliases:["few_shot"]});require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var 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 be=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}},ge=new be(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()}},Oe={...y};je.defineProperties(je,Oe);var Ae=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)}}};Ae.defineProperties(Ae,Ce);var qe=class extends Ae{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=ge.runSync(),_e=class t extends Ue{constructor(){super(...arguments),this.name=It,this.description="subscribe server sent event",this.result="event",this.depends={[Vt]:ge}}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(){ge.register(),$e.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
|
|
1
|
+
import{EventClient as m,EventServer as o,EventToolFunc as r,LRUCache as p,SecondaryCache as t,_lrucache as G,createLRUCache as c,event as h,eventClient as i,eventServer as j,lrucache as k,registerCoreTools as n}from"./chunk-YVFGQB4L.mjs";import"./chunk-VIG2GB47.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as LRUCache,t as SecondaryCache,G as _lrucache,c as createLRUCache,h as event,i as eventClient,j as eventServer,k as lrucache,n as registerCoreTools};
|
|
@@ -30,6 +30,7 @@ interface BaseFuncItem {
|
|
|
30
30
|
setup?: (this: ToolFunc, options?: FuncItem) => void;
|
|
31
31
|
isApi?: boolean;
|
|
32
32
|
stream?: boolean;
|
|
33
|
+
alias?: string | string[];
|
|
33
34
|
}
|
|
34
35
|
interface FuncItem extends BaseFuncItem {
|
|
35
36
|
func?: TFunc;
|
|
@@ -50,6 +51,9 @@ declare interface ToolFunc extends BaseFunc {
|
|
|
50
51
|
}
|
|
51
52
|
declare class ToolFunc extends AdvancePropertyManager {
|
|
52
53
|
static items: Funcs;
|
|
54
|
+
static aliases: {
|
|
55
|
+
[name: string]: string;
|
|
56
|
+
};
|
|
53
57
|
static dataPath: string;
|
|
54
58
|
static get(name: string): ToolFunc;
|
|
55
59
|
static list(): Funcs;
|
|
@@ -120,6 +124,9 @@ declare const ToolFuncSchema: {
|
|
|
120
124
|
asyncFeatures: {
|
|
121
125
|
type: string;
|
|
122
126
|
};
|
|
127
|
+
alias: {
|
|
128
|
+
type: string[];
|
|
129
|
+
};
|
|
123
130
|
};
|
|
124
131
|
|
|
125
132
|
declare const PASSING_SCORE = 0.618;
|
|
@@ -30,6 +30,7 @@ interface BaseFuncItem {
|
|
|
30
30
|
setup?: (this: ToolFunc, options?: FuncItem) => void;
|
|
31
31
|
isApi?: boolean;
|
|
32
32
|
stream?: boolean;
|
|
33
|
+
alias?: string | string[];
|
|
33
34
|
}
|
|
34
35
|
interface FuncItem extends BaseFuncItem {
|
|
35
36
|
func?: TFunc;
|
|
@@ -50,6 +51,9 @@ declare interface ToolFunc extends BaseFunc {
|
|
|
50
51
|
}
|
|
51
52
|
declare class ToolFunc extends AdvancePropertyManager {
|
|
52
53
|
static items: Funcs;
|
|
54
|
+
static aliases: {
|
|
55
|
+
[name: string]: string;
|
|
56
|
+
};
|
|
53
57
|
static dataPath: string;
|
|
54
58
|
static get(name: string): ToolFunc;
|
|
55
59
|
static list(): Funcs;
|
|
@@ -120,6 +124,9 @@ declare const ToolFuncSchema: {
|
|
|
120
124
|
asyncFeatures: {
|
|
121
125
|
type: string;
|
|
122
126
|
};
|
|
127
|
+
alias: {
|
|
128
|
+
type: string[];
|
|
129
|
+
};
|
|
123
130
|
};
|
|
124
131
|
|
|
125
132
|
declare const PASSING_SCORE = 0.618;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as custom_ability from 'custom-ability';
|
|
2
2
|
export { createAbilityInjector } from 'custom-ability';
|
|
3
3
|
export { toRegExp } from 'util-ex';
|
|
4
|
-
import { A as AsyncTaskId, a as AIModelNameRules } from './index-
|
|
5
|
-
export { e as AIModelNameRule, d as AIModelNameRuleFn, c as ActionName, b as ActionNames, s as AsyncFeatureBits, t as AsyncFeatures, J as BaseFunc, H as BaseFuncItem, n as BinarySemaphore, i as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, j as BinarySemaphoreReleaseOptions, k as BinarySemaphoreReleaserFunc, x as CancelableAbility, C as CancelableAbilityOptions, O as ClientFuncItem, U as ClientToolFuncSchema, Q as ClientTools, D as DefaultAsyncSemaphoreCapacity, a5 as EventClient, a4 as EventClientFuncParams, a8 as EventServer, a7 as EventServerFuncParams, _ as EventToolFunc, I as FuncItem, z as FuncParam, F as FuncParamType, E as FuncParams, K as Funcs, P as PASSING_SCORE, p as RateLimit, f as RemoteFuncItem, R as RemoteToolFuncSchema, aa as ResClientFuncParams, ab as ResClientTools, ac as ResServerFuncParams, ad as ResServerTools, g as SSEChannel, S as SSEChannelAlreadyClosedErrCode, a0 as SecondaryCache, o as Semaphore, h as SemaphoreIsReadyFuncType, l as SemaphoreOptions, m as SemaphoreTaskItem, W as ServerFuncItem, V as ServerFuncParams, Y as ServerToolFuncSchema, X as ServerTools, G as TFunc, u as TaskAbortController, v as TaskAbortControllers, w as TaskPromise, q as ToolAsyncCancelableBit, T as ToolAsyncMultiTaskBit, r as ToolAsyncPriorityBit, M as ToolFunc, L as ToolFuncPackage, N as ToolFuncSchema, a1 as _lrucache, a2 as createLRUCache, $ as event, a6 as eventClient, a9 as eventServer, a3 as lrucache, y as makeToolFuncCancelable, Z as registerCoreTools } from './index-
|
|
4
|
+
import { A as AsyncTaskId, a as AIModelNameRules } from './index-BkwhCK1q.mjs';
|
|
5
|
+
export { e as AIModelNameRule, d as AIModelNameRuleFn, c as ActionName, b as ActionNames, s as AsyncFeatureBits, t as AsyncFeatures, J as BaseFunc, H as BaseFuncItem, n as BinarySemaphore, i as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, j as BinarySemaphoreReleaseOptions, k as BinarySemaphoreReleaserFunc, x as CancelableAbility, C as CancelableAbilityOptions, O as ClientFuncItem, U as ClientToolFuncSchema, Q as ClientTools, D as DefaultAsyncSemaphoreCapacity, a5 as EventClient, a4 as EventClientFuncParams, a8 as EventServer, a7 as EventServerFuncParams, _ as EventToolFunc, I as FuncItem, z as FuncParam, F as FuncParamType, E as FuncParams, K as Funcs, P as PASSING_SCORE, p as RateLimit, f as RemoteFuncItem, R as RemoteToolFuncSchema, aa as ResClientFuncParams, ab as ResClientTools, ac as ResServerFuncParams, ad as ResServerTools, g as SSEChannel, S as SSEChannelAlreadyClosedErrCode, a0 as SecondaryCache, o as Semaphore, h as SemaphoreIsReadyFuncType, l as SemaphoreOptions, m as SemaphoreTaskItem, W as ServerFuncItem, V as ServerFuncParams, Y as ServerToolFuncSchema, X as ServerTools, G as TFunc, u as TaskAbortController, v as TaskAbortControllers, w as TaskPromise, q as ToolAsyncCancelableBit, T as ToolAsyncMultiTaskBit, r as ToolAsyncPriorityBit, M as ToolFunc, L as ToolFuncPackage, N as ToolFuncSchema, a1 as _lrucache, a2 as createLRUCache, $ as event, a6 as eventClient, a9 as eventServer, a3 as lrucache, y as makeToolFuncCancelable, Z as registerCoreTools } from './index-BkwhCK1q.mjs';
|
|
6
6
|
import { BaseError } from '@isdk/common-error';
|
|
7
7
|
export { AbortError, AbortErrorCode, AlreadyExistsError, AlreadyExistsErrorCode, BaseError, CommonError, ErrorCode, InternalErrorCode, NotFoundError, NotFoundErrorCode, NotImplementationError, NotImplementedErrorCode, createError, throwError } from '@isdk/common-error';
|
|
8
8
|
import { BaseFactory } from 'custom-factory';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as custom_ability from 'custom-ability';
|
|
2
2
|
export { createAbilityInjector } from 'custom-ability';
|
|
3
3
|
export { toRegExp } from 'util-ex';
|
|
4
|
-
import { A as AsyncTaskId, a as AIModelNameRules } from './index-
|
|
5
|
-
export { e as AIModelNameRule, d as AIModelNameRuleFn, c as ActionName, b as ActionNames, s as AsyncFeatureBits, t as AsyncFeatures, J as BaseFunc, H as BaseFuncItem, n as BinarySemaphore, i as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, j as BinarySemaphoreReleaseOptions, k as BinarySemaphoreReleaserFunc, x as CancelableAbility, C as CancelableAbilityOptions, O as ClientFuncItem, U as ClientToolFuncSchema, Q as ClientTools, D as DefaultAsyncSemaphoreCapacity, a5 as EventClient, a4 as EventClientFuncParams, a8 as EventServer, a7 as EventServerFuncParams, _ as EventToolFunc, I as FuncItem, z as FuncParam, F as FuncParamType, E as FuncParams, K as Funcs, P as PASSING_SCORE, p as RateLimit, f as RemoteFuncItem, R as RemoteToolFuncSchema, aa as ResClientFuncParams, ab as ResClientTools, ac as ResServerFuncParams, ad as ResServerTools, g as SSEChannel, S as SSEChannelAlreadyClosedErrCode, a0 as SecondaryCache, o as Semaphore, h as SemaphoreIsReadyFuncType, l as SemaphoreOptions, m as SemaphoreTaskItem, W as ServerFuncItem, V as ServerFuncParams, Y as ServerToolFuncSchema, X as ServerTools, G as TFunc, u as TaskAbortController, v as TaskAbortControllers, w as TaskPromise, q as ToolAsyncCancelableBit, T as ToolAsyncMultiTaskBit, r as ToolAsyncPriorityBit, M as ToolFunc, L as ToolFuncPackage, N as ToolFuncSchema, a1 as _lrucache, a2 as createLRUCache, $ as event, a6 as eventClient, a9 as eventServer, a3 as lrucache, y as makeToolFuncCancelable, Z as registerCoreTools } from './index-
|
|
4
|
+
import { A as AsyncTaskId, a as AIModelNameRules } from './index-BkwhCK1q.js';
|
|
5
|
+
export { e as AIModelNameRule, d as AIModelNameRuleFn, c as ActionName, b as ActionNames, s as AsyncFeatureBits, t as AsyncFeatures, J as BaseFunc, H as BaseFuncItem, n as BinarySemaphore, i as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, j as BinarySemaphoreReleaseOptions, k as BinarySemaphoreReleaserFunc, x as CancelableAbility, C as CancelableAbilityOptions, O as ClientFuncItem, U as ClientToolFuncSchema, Q as ClientTools, D as DefaultAsyncSemaphoreCapacity, a5 as EventClient, a4 as EventClientFuncParams, a8 as EventServer, a7 as EventServerFuncParams, _ as EventToolFunc, I as FuncItem, z as FuncParam, F as FuncParamType, E as FuncParams, K as Funcs, P as PASSING_SCORE, p as RateLimit, f as RemoteFuncItem, R as RemoteToolFuncSchema, aa as ResClientFuncParams, ab as ResClientTools, ac as ResServerFuncParams, ad as ResServerTools, g as SSEChannel, S as SSEChannelAlreadyClosedErrCode, a0 as SecondaryCache, o as Semaphore, h as SemaphoreIsReadyFuncType, l as SemaphoreOptions, m as SemaphoreTaskItem, W as ServerFuncItem, V as ServerFuncParams, Y as ServerToolFuncSchema, X as ServerTools, G as TFunc, u as TaskAbortController, v as TaskAbortControllers, w as TaskPromise, q as ToolAsyncCancelableBit, T as ToolAsyncMultiTaskBit, r as ToolAsyncPriorityBit, M as ToolFunc, L as ToolFuncPackage, N as ToolFuncSchema, a1 as _lrucache, a2 as createLRUCache, $ as event, a6 as eventClient, a9 as eventServer, a3 as lrucache, y as makeToolFuncCancelable, Z as registerCoreTools } from './index-BkwhCK1q.js';
|
|
6
6
|
import { BaseError } from '@isdk/common-error';
|
|
7
7
|
export { AbortError, AbortErrorCode, AlreadyExistsError, AlreadyExistsErrorCode, BaseError, CommonError, ErrorCode, InternalErrorCode, NotFoundError, NotFoundErrorCode, NotImplementationError, NotImplementedErrorCode, createError, throwError } from '@isdk/common-error';
|
|
8
8
|
import { BaseFactory } from 'custom-factory';
|