@isdk/ai-tool 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4FKBOPZI.mjs +1 -0
- package/dist/{chunk-VIG2GB47.mjs → chunk-TGTHY57V.mjs} +1 -1
- package/dist/funcs.d.mts +1 -2
- package/dist/funcs.d.ts +1 -2
- package/dist/funcs.js +1 -1
- package/dist/funcs.mjs +1 -1
- package/dist/{index-BCco-g_I.d.mts → index-BLW3R7VS.d.mts} +114 -69
- package/dist/{index-BCco-g_I.d.ts → index-BLW3R7VS.d.ts} +114 -69
- package/dist/index.d.mts +101 -38
- package/dist/index.d.ts +101 -38
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/test/util.js +1 -1
- package/dist/test/util.mjs +1 -1
- package/docs/api/{namespaces → @isdk/namespaces}/EventStates/README.md +2 -2
- package/docs/api/{namespaces → @isdk/namespaces}/EventStates/variables/ABORT.md +2 -2
- package/docs/api/{namespaces → @isdk/namespaces}/EventStates/variables/CONTINUE.md +2 -2
- package/docs/api/{namespaces → @isdk/namespaces}/EventStates/variables/DONE.md +2 -2
- package/docs/api/{namespaces → @isdk/namespaces}/EventStates/variables/STOPPED.md +2 -2
- package/docs/api/@isdk/namespaces/uuidv5/README.md +12 -0
- package/docs/api/{namespaces → @isdk/namespaces}/uuidv5/variables/DNS.md +2 -2
- package/docs/api/{namespaces → @isdk/namespaces}/uuidv5/variables/URL.md +2 -2
- package/docs/api/_media/pubsub.md +427 -105
- package/docs/api/_media/server_client_tools.md +5 -3
- package/docs/api/_media/toolFunc.md +3 -1
- package/docs/api/classes/AbortError.md +8 -8
- package/docs/api/classes/AlreadyExistsError.md +8 -8
- package/docs/api/classes/BaseError.md +14 -14
- package/docs/api/classes/BinarySemaphore.md +39 -39
- package/docs/api/classes/CancelableAbility.md +43 -39
- package/docs/api/classes/ClientToolTransport.md +22 -22
- package/docs/api/classes/ClientTools.md +182 -154
- package/docs/api/classes/CommonError.md +12 -12
- package/docs/api/classes/ConfigFile.md +6 -6
- package/docs/api/classes/EnvPromptTemplate.md +14 -14
- package/docs/api/classes/EventClient.md +258 -201
- package/docs/api/classes/EventEmitter.md +14 -14
- package/docs/api/classes/EventServer.md +220 -237
- package/docs/api/classes/EventToolFunc.md +144 -116
- package/docs/api/classes/FStringPromptTemplate.md +14 -14
- package/docs/api/classes/FewShotPromptTemplate.md +30 -26
- package/docs/api/classes/GolangPromptTemplate.md +13 -13
- package/docs/api/classes/HttpClientToolTransport.md +23 -23
- package/docs/api/classes/HttpServerToolTransport.md +40 -27
- package/docs/api/classes/IntSet.md +21 -21
- package/docs/api/classes/LRUCache.md +18 -18
- package/docs/api/classes/NotFoundError.md +8 -8
- package/docs/api/classes/NotImplementationError.md +8 -8
- package/docs/api/classes/PromptExampleSelector.md +17 -15
- package/docs/api/classes/PromptTemplate.md +15 -15
- package/docs/api/classes/ReadableStreamError.md +12 -12
- package/docs/api/classes/ResClientTools.md +658 -143
- package/docs/api/classes/ResServerTools.md +643 -133
- package/docs/api/classes/RpcMethodsClientTool.md +3303 -0
- package/docs/api/classes/RpcMethodsServerTool.md +3248 -0
- package/docs/api/classes/SSEChannel.md +142 -52
- package/docs/api/classes/Semaphore.md +40 -40
- package/docs/api/classes/ServerToolTransport.md +32 -27
- package/docs/api/classes/ServerTools.md +167 -139
- package/docs/api/classes/SignalGate.md +19 -17
- package/docs/api/classes/SseClientPubSubTransport.md +38 -10
- package/docs/api/classes/SseServerPubSubTransport.md +115 -42
- package/docs/api/classes/TaskAbortController.md +13 -13
- package/docs/api/classes/ToolFunc.md +157 -129
- package/docs/api/classes/ToolTransport.md +13 -13
- package/docs/api/classes/YamlTypeBaseObject.md +5 -5
- package/docs/api/enumerations/AsyncFeatureBits.md +4 -4
- package/docs/api/enumerations/AsyncFeatures.md +4 -4
- package/docs/api/enumerations/HashAlgorithm.md +12 -12
- package/docs/api/functions/AIArgProcessor.md +2 -2
- package/docs/api/functions/AIStream.md +8 -4
- package/docs/api/functions/ChoiceArgProcessor.md +2 -2
- package/docs/api/functions/DefaultDateFormat.md +2 -2
- package/docs/api/functions/ObjectArgsToArgsInfo.md +1 -1
- package/docs/api/functions/RateLimit.md +2 -2
- package/docs/api/functions/TemplateArgProcessor.md +2 -2
- package/docs/api/functions/addDate.md +7 -3
- package/docs/api/functions/assignDirs.md +1 -1
- package/docs/api/functions/beforeShutdown.md +1 -1
- package/docs/api/functions/calcPerplexity.md +2 -2
- package/docs/api/functions/calcPerplexitySimple.md +1 -1
- package/docs/api/functions/canonicalize.md +1 -1
- package/docs/api/functions/completeSentences.md +1 -1
- package/docs/api/functions/concatText.md +1 -1
- package/docs/api/functions/countLLMTokens.md +1 -1
- package/docs/api/functions/countRegexMatches.md +1 -1
- package/docs/api/functions/createAbilityInjector.md +16 -8
- package/docs/api/functions/createCallbacksTransformer.md +7 -3
- package/docs/api/functions/createEmptyReadableStream.md +1 -1
- package/docs/api/functions/createEndWithRepetitionDetector.md +2 -2
- package/docs/api/functions/createError.md +1 -1
- package/docs/api/functions/createEventStreamTransformer.md +8 -4
- package/docs/api/functions/createHfValueFunc.md +1 -1
- package/docs/api/functions/createLRUCache.md +2 -2
- package/docs/api/functions/createYamlObjectTag.md +1 -1
- package/docs/api/functions/dateToText.md +1 -1
- package/docs/api/functions/decodeCharset.md +2 -2
- package/docs/api/functions/defaultsWithConcat.md +1 -1
- package/docs/api/functions/detectCharset.md +2 -2
- package/docs/api/functions/encodeLLMTokens.md +1 -1
- package/docs/api/functions/ensureQuoted.md +1 -1
- package/docs/api/functions/eventable.md +6 -8
- package/docs/api/functions/expandConfig.md +2 -2
- package/docs/api/functions/expandObjEnv.md +1 -1
- package/docs/api/functions/expandPath.md +2 -2
- package/docs/api/functions/expandPathInObject.md +2 -2
- package/docs/api/functions/expandPaths.md +2 -2
- package/docs/api/functions/fileIsExists.md +1 -1
- package/docs/api/functions/filterValidFnScope.md +2 -2
- package/docs/api/functions/findIndexNonEmptyFrom.md +1 -1
- package/docs/api/functions/findPort.md +1 -1
- package/docs/api/functions/formatISO.md +1 -1
- package/docs/api/functions/formatTextWithSpace.md +2 -2
- package/docs/api/functions/funcGetMeta.md +1 -1
- package/docs/api/functions/funcWithMeta.md +2 -2
- package/docs/api/functions/genUrlParamsStr.md +8 -2
- package/docs/api/functions/getAllEnumKeys.md +4 -2
- package/docs/api/functions/getConfigFileNames.md +2 -2
- package/docs/api/functions/getConfigs.md +2 -2
- package/docs/api/functions/getFileMetaInfo.md +1 -1
- package/docs/api/functions/getHashAlgoBySize.md +1 -1
- package/docs/api/functions/getKeysPath.md +4 -2
- package/docs/api/functions/getLLMTokenizer.md +1 -1
- package/docs/api/functions/getMultiLevelExtname.md +1 -1
- package/docs/api/functions/getPackageDir.md +1 -1
- package/docs/api/functions/getRealFilepath.md +1 -1
- package/docs/api/functions/getResponseErrorReadableStream.md +2 -2
- package/docs/api/functions/getXDGConfigs.md +1 -1
- package/docs/api/functions/hasDirectoryIn.md +2 -2
- package/docs/api/functions/hash.md +1 -1
- package/docs/api/functions/hashFile.md +2 -2
- package/docs/api/functions/hashObject.md +2 -2
- package/docs/api/functions/hashStream.md +1 -1
- package/docs/api/functions/initShutdown.md +1 -1
- package/docs/api/functions/isLangUsingSpaces.md +1 -1
- package/docs/api/functions/isListItemString.md +1 -1
- package/docs/api/functions/isModelNameMatched.md +2 -2
- package/docs/api/functions/isPunctuationChar.md +1 -1
- package/docs/api/functions/isQuoted.md +1 -1
- package/docs/api/functions/isRegExp.md +1 -1
- package/docs/api/functions/isSameString.md +1 -1
- package/docs/api/functions/isSectionString.md +2 -2
- package/docs/api/functions/isSentenceEnding.md +1 -1
- package/docs/api/functions/isSepLineString.md +1 -1
- package/docs/api/functions/isStrWrapped.md +1 -1
- package/docs/api/functions/isSubdirectory.md +1 -1
- package/docs/api/functions/isTitleString.md +2 -2
- package/docs/api/functions/isWebStream.md +1 -1
- package/docs/api/functions/joinSplitWords.md +1 -1
- package/docs/api/functions/jsonFilterToWhere.md +2 -2
- package/docs/api/functions/jsonToMarkdownStr.md +2 -2
- package/docs/api/functions/loadAIConfig.md +1 -1
- package/docs/api/functions/loadConfig.md +1 -1
- package/docs/api/functions/loadConfigFile.md +1 -1
- package/docs/api/functions/loadFileFromPaths.md +2 -2
- package/docs/api/functions/loadTextFromPaths.md +3 -3
- package/docs/api/functions/lrucache.md +1 -1
- package/docs/api/functions/matchUrlProtocol.md +1 -1
- package/docs/api/functions/memoize.md +5 -3
- package/docs/api/functions/mergeArray.md +1 -1
- package/docs/api/functions/messagesToText.md +1 -1
- package/docs/api/functions/nanoid.md +45 -0
- package/docs/api/functions/normalizePath.md +1 -1
- package/docs/api/functions/paramsSizeToScaleStr.md +1 -1
- package/docs/api/functions/parseCommand.md +3 -3
- package/docs/api/functions/parseDateFormat.md +7 -3
- package/docs/api/functions/parseISO.md +7 -3
- package/docs/api/functions/parseJsJson.md +2 -2
- package/docs/api/functions/parseJsJsonSimpleSync.md +2 -2
- package/docs/api/functions/parseObjectArgInfo.md +2 -2
- package/docs/api/functions/parseObjectArgumentInfos.md +2 -2
- package/docs/api/functions/parseObjectArguments.md +2 -2
- package/docs/api/functions/parseObjectArgumentsAsArgInfos.md +2 -2
- package/docs/api/functions/parseYaml.md +1 -1
- package/docs/api/functions/pruneSubdirectories.md +1 -1
- package/docs/api/functions/pruneSubdirectoriesInPlace.md +1 -1
- package/docs/api/functions/quoteStr.md +1 -1
- package/docs/api/functions/readFilenamesRecursiveSync.md +2 -2
- package/docs/api/functions/readTextFileChunks.md +2 -2
- package/docs/api/functions/readTextFileChunksEx.md +2 -2
- package/docs/api/functions/readableFromAsyncIterable.md +4 -2
- package/docs/api/functions/registerCoreTools.md +1 -1
- package/docs/api/functions/removeMarkdownBold.md +2 -2
- package/docs/api/functions/removeMarkdownBoldAndItalic.md +2 -2
- package/docs/api/functions/removeMarkdownItalic.md +2 -2
- package/docs/api/functions/replaceWithPlaceholder.md +2 -2
- package/docs/api/functions/restoreFromPlacehoders.md +2 -2
- package/docs/api/functions/sanitizeFilename.md +1 -1
- package/docs/api/functions/sanitizeFilepath.md +1 -1
- package/docs/api/functions/saveConfigFile.md +1 -1
- package/docs/api/functions/scaleStrToParamsSize.md +1 -1
- package/docs/api/functions/shutdown.md +1 -1
- package/docs/api/functions/simplifyObjectArguments.md +1 -1
- package/docs/api/functions/sleep.md +1 -1
- package/docs/api/functions/sortedValues.md +4 -2
- package/docs/api/functions/splitChunks.md +2 -2
- package/docs/api/functions/splitParagraph.md +2 -2
- package/docs/api/functions/splitSentence.md +1 -1
- package/docs/api/functions/splitWords.md +1 -1
- package/docs/api/functions/stringifyYaml.md +1 -1
- package/docs/api/functions/stripConsoleColor.md +1 -1
- package/docs/api/functions/textToDate.md +1 -1
- package/docs/api/functions/throwError.md +1 -1
- package/docs/api/functions/toDate.md +7 -3
- package/docs/api/functions/toDateTime.md +1 -1
- package/docs/api/functions/trimStartOfStreamHelper.md +3 -3
- package/docs/api/functions/truncTo.md +1 -1
- package/docs/api/functions/truncateByToken.md +2 -2
- package/docs/api/functions/truncateToTokenLimit.md +2 -2
- package/docs/api/functions/truncateToTokenLimitEx.md +2 -2
- package/docs/api/functions/uuid.md +15 -6
- package/docs/api/functions/uuidStringify.md +1 -1
- package/docs/api/functions/uuidv1.md +5 -3
- package/docs/api/functions/uuidv4.md +5 -3
- package/docs/api/functions/uuidv5.md +5 -3
- package/docs/api/functions/uuidv6.md +61 -0
- package/docs/api/functions/uuidv7.md +61 -0
- package/docs/api/functions/wrapEventEmitter.md +1 -1
- package/docs/api/functions/xxhash.md +1 -1
- package/docs/api/functions/xxhash32.md +1 -1
- package/docs/api/functions/xxhash64.md +1 -1
- package/docs/api/functions/xxhashAsStr.md +1 -1
- package/docs/api/functions/yieldExec.md +1 -1
- package/docs/api/globals.md +17 -6
- package/docs/api/interfaces/AIChatAssistantMessageParam.md +12 -12
- package/docs/api/interfaces/AIChatContentPartImage.md +3 -3
- package/docs/api/interfaces/AIChatContentPartText.md +3 -3
- package/docs/api/interfaces/AIChatMessageParamBase.md +7 -7
- package/docs/api/interfaces/AIChatMessageToolCall.md +4 -4
- package/docs/api/interfaces/AIChatSystemMessageParam.md +9 -9
- package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +3 -3
- package/docs/api/interfaces/AIChatToolChoiceObject.md +2 -2
- package/docs/api/interfaces/AIChatToolFunc.md +5 -5
- package/docs/api/interfaces/AIChatToolFuncParam.md +3 -3
- package/docs/api/interfaces/AIChatToolMessageParam.md +10 -10
- package/docs/api/interfaces/AIChatToolParam.md +2 -2
- package/docs/api/interfaces/AIChatToolTypeObject.md +2 -2
- package/docs/api/interfaces/AIChatUserMessageParam.md +13 -13
- package/docs/api/interfaces/AIChoiceConfig.md +8 -8
- package/docs/api/interfaces/AIResult.md +12 -8
- package/docs/api/interfaces/AIStreamParser.md +8 -6
- package/docs/api/interfaces/AIStreamParserOptions.md +2 -2
- package/docs/api/interfaces/BaseFunc.md +17 -17
- package/docs/api/interfaces/BaseFuncItem.md +15 -15
- package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +2 -2
- package/docs/api/interfaces/BinarySemaphoreOptions.md +5 -5
- package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +2 -2
- package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +3 -3
- package/docs/api/interfaces/CancelableAbilityOptions.md +4 -4
- package/docs/api/interfaces/ClientFuncItem.md +21 -25
- package/docs/api/interfaces/EventClientFuncParams.md +5 -5
- package/docs/api/interfaces/EventServerFuncParams.md +14 -6
- package/docs/api/interfaces/FewShotPromptTemplateOptions.md +9 -7
- package/docs/api/interfaces/FuncItem.md +18 -18
- package/docs/api/interfaces/FuncParam.md +5 -5
- package/docs/api/interfaces/FuncParams.md +1 -1
- package/docs/api/interfaces/Funcs.md +1 -1
- package/docs/api/interfaces/HashAlgoParams.md +4 -4
- package/docs/api/interfaces/IClientToolTransport.md +9 -9
- package/docs/api/interfaces/IFileMetaInfo.md +8 -8
- package/docs/api/interfaces/IPubSubClientTransport.md +31 -7
- package/docs/api/interfaces/IPubSubServerTransport.md +92 -47
- package/docs/api/interfaces/IReadTextFileChunksOptions.md +13 -13
- package/docs/api/interfaces/IServerToolTransport.md +19 -14
- package/docs/api/interfaces/IToolTransport.md +6 -6
- package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +11 -11
- package/docs/api/interfaces/JsonFilter.md +1 -1
- package/docs/api/interfaces/ParseObjectArgumentOptions.md +11 -11
- package/docs/api/interfaces/ProbabilityItem.md +4 -4
- package/docs/api/interfaces/PromptExampleSelectorOptions.md +3 -3
- package/docs/api/interfaces/PubSubClientStream.md +26 -14
- package/docs/api/interfaces/PubSubServerSession.md +8 -8
- package/docs/api/interfaces/RemoteFuncItem.md +21 -25
- package/docs/api/interfaces/ReplacePlacehoderOptions.md +5 -5
- package/docs/api/interfaces/ResClientFuncParams.md +5 -5
- package/docs/api/interfaces/ResServerFuncParams.md +14 -10
- package/docs/api/interfaces/RpcMethodsClientFuncParams.md +25 -0
- package/docs/api/interfaces/RpcMethodsServerFuncParams.md +61 -0
- package/docs/api/interfaces/SectionStringOptions.md +3 -3
- package/docs/api/interfaces/SemaphoreOptions.md +7 -7
- package/docs/api/interfaces/SemaphoreTaskItem.md +6 -6
- package/docs/api/interfaces/ServerFuncItem.md +22 -26
- package/docs/api/interfaces/ServerFuncParams.md +4 -3
- package/docs/api/interfaces/SplitSentenceOptions.md +5 -5
- package/docs/api/interfaces/StreamCallbacksAndOptions.md +11 -7
- package/docs/api/interfaces/TaskAbortControllers.md +1 -1
- package/docs/api/interfaces/TaskPromise.md +17 -9
- package/docs/api/interfaces/ToolFuncPackage.md +5 -5
- package/docs/api/type-aliases/AIChatContentPart.md +2 -2
- package/docs/api/type-aliases/AIChatMessageParam.md +2 -2
- package/docs/api/type-aliases/AIChatRole.md +2 -2
- package/docs/api/type-aliases/AIChatToolChoiceParam.md +2 -2
- package/docs/api/type-aliases/AIMessageType.md +2 -2
- package/docs/api/type-aliases/AIModelNameRule.md +2 -2
- package/docs/api/type-aliases/AIModelNameRuleFn.md +2 -2
- package/docs/api/type-aliases/AIModelNameRules.md +2 -2
- package/docs/api/type-aliases/AITextGenerationFinishReason.md +2 -2
- package/docs/api/type-aliases/ActionName.md +2 -2
- package/docs/api/type-aliases/ArrayMergeWay.md +2 -2
- package/docs/api/type-aliases/AsyncTaskId.md +2 -2
- package/docs/api/type-aliases/BeforeShutdownListener.md +2 -2
- package/docs/api/type-aliases/EventErrorListenerFn.md +2 -2
- package/docs/api/type-aliases/EventListenerFn.md +2 -2
- package/docs/api/type-aliases/FuncParamType.md +2 -2
- package/docs/api/type-aliases/PromptExamples.md +5 -3
- package/docs/api/type-aliases/PubSubClientId.md +2 -2
- package/docs/api/type-aliases/PubSubCtx.md +24 -4
- package/docs/api/type-aliases/RpcMethodHandler.md +2 -2
- package/docs/api/type-aliases/SSEClient.md +53 -0
- package/docs/api/type-aliases/SemaphoreIsReadyFuncType.md +2 -2
- package/docs/api/type-aliases/TFunc.md +2 -2
- package/docs/api/type-aliases/UUIDVersions.md +11 -0
- package/docs/api/variables/AIChatRoles.md +1 -1
- package/docs/api/variables/AIMessageTypes.md +1 -1
- package/docs/api/variables/AITextGenerationFinishReasons.md +1 -1
- package/docs/api/variables/ActionNames.md +1 -1
- package/docs/api/variables/ArrayMergeWay.md +2 -2
- package/docs/api/variables/ArrayMergeWaySymbol.md +2 -2
- package/docs/api/variables/ClientEventPrefix.md +11 -0
- package/docs/api/variables/ClientToolFuncSchema.md +4 -2
- package/docs/api/variables/DEFAULT_CONFIG_NAME.md +1 -1
- package/docs/api/variables/DefaultAsyncSemaphoreCapacity.md +1 -1
- package/docs/api/variables/EventBusName.md +1 -1
- package/docs/api/variables/EventName.md +1 -1
- package/docs/api/variables/FuncMetaSymbol.md +2 -2
- package/docs/api/variables/LLM_TOKENIZER_NAMES.md +4 -4
- package/docs/api/variables/LLM_TOKENIZER_NAMES_MAP.md +1 -1
- package/docs/api/variables/PASSING_SCORE.md +1 -1
- package/docs/api/variables/RStreamErrCode.md +1 -1
- package/docs/api/variables/RemoteToolFuncSchema.md +4 -2
- package/docs/api/variables/ResponseRStreamErrCode.md +1 -1
- package/docs/api/variables/RpcMethodsClientToolSchema.md +51 -0
- package/docs/api/variables/RpcMethodsServerToolSchema.md +21 -0
- package/docs/api/variables/SHUTDOWN_SIGNALS.md +1 -1
- package/docs/api/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
- package/docs/api/variables/SecondaryCache.md +1 -1
- package/docs/api/variables/ServerToolFuncSchema.md +4 -2
- package/docs/api/variables/StrangeHumanName.md +1 -1
- package/docs/api/variables/ToolAsyncCancelableBit.md +1 -1
- package/docs/api/variables/ToolAsyncMultiTaskBit.md +1 -1
- package/docs/api/variables/ToolAsyncPriorityBit.md +1 -1
- package/docs/api/variables/ToolFuncSchema.md +4 -2
- package/docs/api/variables/backendEventable.md +11 -0
- package/docs/api/variables/base32768.md +1 -1
- package/docs/api/variables/event.md +1 -1
- package/docs/api/variables/eventClient.md +1 -1
- package/docs/api/variables/eventServer.md +1 -1
- package/docs/api/variables/lrucache.md +1 -1
- package/docs/api/variables/makeToolFuncCancelable.md +11 -0
- package/docs/api/{functions → variables}/wait.md +16 -14
- package/docs/pubsub.md +427 -105
- package/docs/server_client_tools.md +5 -3
- package/docs/toolFunc.md +3 -1
- package/package.json +10 -9
- package/dist/chunk-LNTIQQNN.mjs +0 -1
- package/docs/api/functions/backendEventable.md +0 -29
- package/docs/api/functions/makeToolFuncCancelable.md +0 -29
- package/docs/api/interfaces/PubSubClient.md +0 -27
- package/docs/api/namespaces/uuidv5/README.md +0 -12
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EventEmitter as t}from"events-ex";import{assign as e,defaultsDeep as n}from"lodash-es";import{AdvancePropertyManager as r}from"property-manager";import{_createFunction as i}from"util-ex";import{AbortError as s,AbortErrorCode as o,AlreadyExistsError as a,AlreadyExistsErrorCode as c,BaseError as u,CommonError as f,createError as h,ErrorCode as l,InternalErrorCode as m,NotFoundErrorCode as p,NotFoundError as d,NotImplementedErrorCode as y,NotImplementationError as w,throwError as b}from"@isdk/common-error";import{createAbilityInjector as v}from"custom-ability";import{toRegExp as g}from"util-ex";var k=.618,$=["get","post","put","delete","patch","list","res"],x={action:{type:"string",assign:(t,e,n,r,i)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}};import{format as A,parse as S,parseISO as E}from"date-fns";import{add as T,formatISO as j,parseISO as I,toDate as C}from"date-fns";var O="MMMM d, y 'at' h:m:s b 'GMT'x";function N(t){return t&&(O=t),O}function M(t){let e;try{"string"==typeof t?e=E(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function R(t,e=O){return S(t,e,new Date)}function z(t,e=O){return A(t,e)}var _=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],L=["human","ai","generic","system","tool"],D=["user","assistant","system","tool","tool_calls"],P="陌生人";function X(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=M(t);n&&(e+=" ["+z(n)+"]")}e+=" "+n.content+"\n"}return e}import{StringTemplate as F,EnvStringTemplate as B,FStringTemplate as q,GolangStringTemplate as U,expandEnv as G,expandObjEnv as W,defaultTemplateFormat as Z,getEnvVairables as J,createHfValueFunc as H}from"@isdk/template-engines";import{StringTemplate as K}from"@isdk/template-engines";function Q(t){return Object.keys(t).sort().map(e=>t[e])}var V=class extends K{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 K?t.examplePrompt:K.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=Q(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await K.format({template:n,data:t,templateFormat:r})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};function Y(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}K.register(V,{name:"fewshot",aliases:["few_shot"]});var tt=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then(t=>{tt=t});var et=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var r;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(r=t,tt?r:Y(r))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}};import{detectTextLanguage as nt}from"@isdk/detect-text-language";var rt=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,it=/([A-Z][a-z]{1,2}\.)\s(\w)/g,st=/(\.[a-zA-Z]\.)\s(\w)/g,ot=new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),at=new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g"),ct=/(```)([\s\S]*?)(```)/g,ut=">>>CODE_BLOCK<<<",ft=/([*_`]{1,3})(\S.*?\S)\1/,ht=/>>> INLINE_BLOCK (\d+) <<</,lt=1e4;function mt(t,e,n){const r="$1"+e+"$2";let i=t;for(let t=0;t<n.length;t++)i=i.replace(n[t],r);return i}function pt(t,{best:e=!0,completeSentence:n,isMarkdown:r,ignoreEmptyLine:i}={}){const s=[],o=[];let a,c=0;for(;c++<lt&&(a=ct.exec(t));){const e=a[0];s.push(e),t=t.replace(e,"\n"+ut+(s.length-1)+"\n")}for(c=0;c++<lt&&(a=ft.exec(t));){const e=a[0];o.push(e),t=t.replace(e,">>> INLINE_BLOCK "+(o.length-1)+" <<<")}if(r){const e=t.split("\n");for(let t=0;t<e.length;t++){const n=e[t];gt(n,{isMarkdown:r,nextLine:e[t+1]})&&(s.push(n),e[t]=ut+(s.length-1))}t=e.join("\n")}const u=(t=(t=(t=(t=(t=t.replace(/([。!??])\1+/g,"$1")).replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let f=[];for(let t=0;t<u.length;t++){let n=u[t].trimEnd();if(!n){!r&&i||f.push("");continue}if(n.startsWith(ut)){f.push(s[Number(n.slice(16))]);continue}if(r&>(n,{isMarkdown:r,nextLine:u[t+1]})){f.push(n);continue}if(!e){f.push(n);continue}let a=mt(n,"@",[it,st]),c=Array.from(a.matchAll(rt)),h=[];if(c.length)for(let t=0;t<c.length;t++)h.push(mt(c[t][0]," ",[ot,at]));else h.push(n);f.push(...h.map(t=>At(o,t)))}return n&&(f=dt(f,{isMarkdown:r,ignoreEmptyLine:i})),f}function dt(t,{isMarkdown:e,ignoreEmptyLine:n}={}){const r=[];let i=0,s="";for(n=!e&&n;i<t.length;){let o=t[i];if(o){let a;if(n){const n=Et(t,i+1);a=vt(t[n],{isMarkdown:e,nextLine:-1===n?"":t[n+1]})}else a=vt(t[i+1],{isMarkdown:e,nextLine:t[i+2]});yt(o,{isMarkdown:e,nextLine:t[i+1]})||""===t[i+1]||a?(s&&(o=wt(s,o),s=""),r.push(o)):(s&&(o=wt(s,o)),s=o)}else n||r[r.length-1]&&r.push(o);i++}return s&&r.push(s),r}function yt(t,e){return bt(t)||vt(t,e)}function wt(t,e){const n=t+" "+e,r=nt(n,{isoCode:!0});return r&&!St(r)?(xt(t)&&(t+=" "),e=t+e):e=t.endsWith("-")?(t=t.slice(0,-1))+e:n,e}function bt(t){if(!t)return!1;return/(([.。!!??]\s*['"”’]?)|```)\s*$/.test(t)}function vt(t,e){let n=gt(t,e);return n||(n=kt(t)),n||(n=$t(t)),n}function gt(t,e){if(!t)return null;let n=/^\s*第?\s*[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十百千萬万\d]+\s*([章節节编回部篇卷幕场場辑集段册冊期片題]|片段|段落|篇[章目]|小[节節]|(子)?部分|卷[册冊]|[单單]元|章[节節回]|[.、])[ \t]*(?<title>.*)(?=\n|$)/.exec(t);if(n||(n=/^\s*(Chapter|Book|Article|Part|Paragraph|Subsection|Subpart|Volume|Episode|Issue|Unit|Section|Segment|Act|Scene)\s*\d+.*(?=\n|$)/i.exec(t)),!n&&e?.isMarkdown){n=/^[ \t]{0,3}(#+)\s+(?<title>\S.*)$/.exec(t);const r=/^[ \t]{0,3}([-=]+)(?=\n|$)/;!n&&e.nextLine&&!r.test(t)&&/^[ \t]{0,3}\S/.test(t)&&r.test(e.nextLine)&&(n=/^\s*(?<title>.*)(?=\n|$)/.exec(t))}return n}function kt(t){return/^\s*([*+-]|\d+[.、])\s*(?<item>.*)(?=\n|$)/.exec(t)}function $t(t){return/^[-=_]{3,}$/.exec(t)}function xt(t){return/[。!??,、;;::'""“”‘’~~《》<>〈〉【】(){}【】\[\]\(\)…·]$/.test(t)}function At(t,e){let n,r=0;for(;r++<lt&&(n=ht.exec(e));){const r=Number(n[1]);e=e.replace(n[0],t[r])}return e}function St(t){return!["zh","ja","th","lo","ta","ko"].includes(t)}function Et(t,e=0){for(let n=e;n<t.length;n++){const e=t[n];if(null!=e&&""!==e)return n}return-1}function Tt(t,e){const n=/(?!\\)([*_])\1(?![ \t]|\1)(.+?)(?<!\\)\1{2}/;let r;for(;(r=n.exec(t))&&(t=t.slice(0,r.index)+r[2]+t.slice(r.index+r[0].length),!e););return t}function jt(t,e){const n=/(?!\\)([*_])(?![ \t]|\1)(.+?)(?<!\\)\1/;let r;for(;(r=n.exec(t))&&(t=t.slice(0,r.index)+r[2]+t.slice(r.index+r[0].length),!e););return t}function It(t,e){return t=jt(t=Tt(t,e),e)}function Ct(t,e){const n=[],r=[],i=t.split("\n");for(let t=0;t<i.length;t++){let s=i[t];const o=0===s.trim().length;o||gt(s,{...e,nextLine:i[t+1]})?(r.length&&n.push([...r]),r.length=0,o||r.push(s)):r.push(s)}return r.length&&n.push([...r]),n}function Ot(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function Nt(t){return new Promise(e=>setTimeout(e,t))}var Mt=Nt;async function Rt(){return new Promise(t=>{setImmediate(t)})}import{createAbilityInjector as zt}from"custom-ability";import{EventEmitter as _t,eventable as Lt,states as Dt,wrapEventEmitter as Pt}from"events-ex";var Xt="event",Ft="event-bus";var Bt=zt(function(t,e){const n=e?.eventBusName||Ft;return class{static get emitter(){if(!this._emitter){const t=this.get(n)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}},!0);import{nanoid as qt}from"nanoid";import{v1 as Ut,v5 as Gt,v4 as Wt,v6 as Zt,v7 as Jt}from"uuid";import*as Ht from"base32768";import{v1 as Kt,v4 as Qt,v5 as Vt,v6 as Yt,v7 as te,stringify as ee,parse as ne,validate as re,version as ie,NIL as se}from"uuid";var oe={1:Ut,4:Wt,5:Gt,6:Zt,7:Jt};function ae(t,e){!0===t&&(e=!0),"number"==typeof t&&oe[t]||(t=1);const n=oe[t];return e?Ht.encode(n(null,new Uint8Array(16))):n()}import ce from"xxhashjs";import*as ue from"base32768";import{canonicalize as fe}from"json-canonicalize";import{createMD5 as he,createRIPEMD160 as le,createSHA1 as me,createSHA224 as pe,createSHA256 as de,createSHA512 as ye,createXXHash128 as we,createXXHash32 as be,createXXHash64 as ve}from"hash-wasm";var ge=588213,ke=(t=>(t[t.md5=1]="md5",t[t.sha1=2]="sha1",t[t.ripemd=3]="ripemd",t[t.sha256=8]="sha256",t[t.sha384=9]="sha384",t[t.sha512=10]="sha512",t[t.sha224=11]="sha224",t[t.xxhash=111]="xxhash",t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t[t.xxhash128=113]="xxhash128",t))(ke||{}),$e={1:he,2:me,8:de,10:ye,11:pe,3:le,112:be,111:ve,113:we},{h32:xe,h64:Ae}=ce;function Se(t,e=16){return"object"==typeof t&&(t=fe(t)),xe(t.normalize(),ge).toString(e)}function Ee(t,e=16){return"object"==typeof t&&(t=fe(t)),Ae(t.normalize(),ge).toString(e)}function Te(t,e=111,n=ge){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Ae(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=xe(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function je(t,e=111,n=ge){return ue.encode(Te(t,e,n))}import{canonicalize as Ie}from"json-canonicalize";import*as Ce from"base32768";var Oe=Ce;async function Ne(t,{hashAlgo:e=111,seed:n=ge,outputType:r="string"}={}){const i=await $e[e](n);i.init();const s=t.getReader();for(;;){const{done:t,value:e}=await s.read();if(t)break;i.update(e)}return"string"!==r?i.digest(r):Ce.encode(i.digest("binary"))}async function Me(t,{hashAlgo:e=111,seed:n=ge,outputType:r="string"}={}){const i=await $e[e](n);i.init(),i.update(t);return"string"!==r?i.digest(r):Ce.encode(i.digest("binary"))}async function Re(t,e){return Me(t=Ie(t),e)}function ze(t,e){return!t||t.some(t=>t instanceof RegExp?t.test(e):t===e)}var _e=498,Le=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 Map,this.messages=[],this.active=!0}publish(t,e,n){let r,i;this.active||b("Channel closed","SSEChannel",_e);let s=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t&&"string"!=typeof t&&(t=""+t),t=t?t.split(/[\r\n]+/).map(t=>"data: "+t).join("\n"):"",r="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}if(n?.clientId){(Array.isArray(n.clientId)?n.clientId:[n.clientId]).forEach(t=>{const e=this.clients.get(t);e&&e.res.write(r)})}else this.clients.forEach(t=>{s&&!ze(t.events,s)||t.res.write(r)});for(;this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e){this.active||b("Channel closed","SSEChannel",_e),(e instanceof RegExp||"string"==typeof e)&&(e=[e]);const n=this.clients.get(t);if(n){n.events||(n.events=[]);for(const t of e)n.events.some(e=>e.toString()===t.toString())||n.events.push(t);return!0}return!1}unsubscribe(t,e){this.active||b("Channel closed","SSEChannel",_e),(e instanceof RegExp||"string"==typeof e)&&(e=[e]);const n=this.clients.get(t);return!!n&&(n.events&&(n.events=n.events.filter(t=>!e.some(e=>e.toString()===t.toString()))),!0)}getClient(t){return this.clients.get(t)}connect(t,e,n,r){this.active||b("Channel closed","SSEChannel",_e);const i=ae();if(this.clients.has(i)){const t=this.clients.get(i);t&&this.disconnect(t)}(n instanceof RegExp||"string"==typeof n)&&(n=[n]);const s={req:t,res:e,events:n,clientId:i},o=this.options.maxStreamDuration;let a="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";o>0&&(a+=", s-maxage="+(Math.floor(o/1e3)-1));const c={"Content-Type":"text/event-stream","Cache-Control":a,Connection:"keep-alive"};this.options.cors&&(c["Access-Control-Allow-Origin"]="*"),s.req.socket.setNoDelay(!0),s.res.writeHead(200,c);let u="retry: "+this.options.clientRetryInterval+"\n\n";const f=Number.parseInt(t.headers["last-event-id"],10),h=Number.isNaN(f)?this.options.rewind:this.nextID-1-f;return h&&this.messages.filter(t=>ze(s.events,t.eventName)).slice(0-h).forEach(t=>{u+=t.output}),s.res.write(u),this.clients.set(s.clientId,s),this.publish({clientId:i},"welcome",{clientId:i}),o>0&&setTimeout(()=>{s.res.writableEnded||this.disconnect(s)},o),s.res.on("close",()=>this.disconnect(s)),s}disconnect(t){t.res.end(),this.clients.delete(t.clientId)}clearClients(){this.clients.forEach(t=>t.res.end()),this.clients.clear()}listClients(){const t={};return this.clients.forEach(e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++}),t}getSubscriberCount(){return this.clients.size}};function De(t){return t instanceof ReadableStream||t instanceof WritableStream}var Pe=600,Xe=601,Fe=class extends u{constructor(t,e=600){super(t,500)}};function Be(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:r}=await e.read();if(!n){const e=(new TextDecoder).decode(r);t.error(new Fe(`Response error: ${e}`,601))}}})}return new ReadableStream({start(t){t.error(new Fe("Response error: No response body",601))}})}function qe(){return new ReadableStream({start(t){t.close()}})}import{createParser as Ue}from"eventsource-parser";function Ge(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Ue({onEvent:n=>{if("data"in n&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const r=t?t(n.data,{event:n.event}):n.data;r&&e.enqueue(r)}}})},transform(t){n.feed(e.decode(t))}})}function We(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Ze(t,e){if(!t.ok)return Be(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Ge(e))}function Je(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(t){await(e.return?.(t))}})}function He(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=r=>{n.call(t,r),e.onError&&e.onError(r)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let r;e.onTransform&&(r=await e.onTransform(t,n)),r||(r=t),n.enqueue(r)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}import{extNameLevel as Ke,FilenameReservedRegex as Qe,getMultiLevelExtname as Ve,isValidFilename as Ye,isValidFilepath as tn,sanitizeFilename as en,sanitizeFilepath as nn,WindowsReservedNameRegex as rn}from"@isdk/util";import{isRegExpStr as sn,toRegExp as on}from"util-ex";function an(t,e){if("string"!=typeof t)throw new f("modelName must be a string","isModelNameMatched",l.InvalidArgument);switch(typeof e){case"string":if(sn(e)){const n=(e=on(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if(sn(n)){const r=(e=on(n)).exec(t);if(r)return r}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function cn(t){return Object.keys(t).filter(t=>Number.isNaN(Number(t)))}import{pick as un}from"lodash-es";import{newFunction as fn}from"util-ex";import{get as hn,omitBy as ln}from"lodash-es";import{newFunction as mn}from"util-ex";async function pn(t,e,n){return bn(Cn(t,e,n),e,n)}function dn(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function yn(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t),r=n.filter(t=>!isNaN(parseInt(t)));if(1===e.length)void 0!==t[0]&&(t=[t[0]]);else if(n.every(t=>!isNaN(parseInt(t)))&&dn(n.map(t=>parseInt(t))))t=Object.values(t);else if("0"===r[0]&&dn(r.map(t=>parseInt(t)))){const n=e.filter(([t,e])=>isNaN(parseInt(t)));t=e.filter(([t,e])=>!isNaN(parseInt(t))).map(([t,e])=>e);let r=0;const i=[];for(;r<n.length&&n[r][1]===t[r];)i.push(r),r++;for(;i.length;)n.splice(i.pop(),1);t={args:t,kvArgs:Object.fromEntries(n)}}else t={args:[],kvArgs:t}}return Array.isArray(t)&&(t={args:t}),t}function wn(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t);1===e.length&&void 0!==t[0]?t=t[0]:n.every(t=>!isNaN(parseInt(t)))?t=n.sort((t,e)=>parseInt(t)-parseInt(e)).map(e=>t[e]):2===e.length&&"0"===e[0][0]&&e[0][1]===e[1][1]&&(t=t[0])}return t}async function bn(t,e,n){if(t.length){const r=await Promise.all(t.map((t,r)=>In(t,r,e,n))),i=n?.returnArrayOnly;let s;if(r?.length){s=Pn(`{${r.map(t=>t).join(",")}}`,e)}return s&&!i&&(s=wn(s)),s}}function vn(t,e,n,r){const[i,s]=t;if(!i&&"|"===s[0])return"choice: {"+function(t,e,n){const r=Cn(t,e,{...n,delimiter:":"}),i={},s=r.map(([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(i[n])throw new Error("Only one "+n+" is allowed");return i[n]=!0,e}{if("|"===e[0]){if(i.items)throw new Error("Only one items is allowed");return i.items=!0,"items:["+function(t,e='"'){return t.map(t=>An(t,e))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(i.maxPick)throw new Error("Only one maxPick is allowed");return i.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return i.type=!0,'type:"'+e+'"';if($n(e)){if(i.separator)throw new Error("Only one separator is allowed");return i.separator=!0,"separator:"+e}}});return s}(s,n,r)+"}"}async function gn([t,e],n,r,i){let s,o;if(r||(r={}),t){const t=e.split(":");s=t[0].trim(),o=t[1].trim()}else o=e,s=n+"";const a={template:o,data:{...ln(r,(t,e)=>!e||"_"===e[0]||"function"==typeof t),...i?.templateData}};i?.templateFormat&&(a.templateFormat=i.templateFormat);const c=await F.formatIf(a);if(c)return o=$n(c)?c:JSON.stringify(c),s+":"+o}async function kn(t,e,n,r){let i=vn(t,0,n,r);return i||(i=await gn(t,e,n,r)),i}function $n(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function xn(t,e=['""',"''","{}"]){return e.some(e=>t[0]===e[0]&&t[t.length-1]===e[1])}function An(t,e='"'){return $n(t)?t:e+t+e}function Sn(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var En=["true","false","null","undefined","NaN","Infinity"];async function Tn(t,e,n){const r=mn("async expression",[],`return ${t};`,Bn(e));let i;try{i=await r.call(this)}catch(t){if(n||!(t instanceof ReferenceError))throw t}switch(typeof i){case"number":case"boolean":case"undefined":return i;case"function":return r.toString();default:return JSON.stringify(i)}}async function jn(t,e,n){let r=t;if(["true","false"].includes(t.toLowerCase()))r=r.toLowerCase();else if(!(i=t,xn(i)||!Number.isNaN(parseFloat(i))||En.includes(i)||Ln(i)||e&&void 0!==hn(e,t)||Ln(t)))try{r=n?.skipExpression?Sn(t):await Tn.call(this,t,e,n?.preserveUnresolvedName)}catch(e){r=Sn(t)}var i;return r}async function In(t,e,n,r){const[i,s]=t,o=r?.argProcessor,a=r?.ignoreIndexNamed;if("function"==typeof o){const i=await o(t,e,n,r);if(i)return i}if(i){const t=s.indexOf(":");return s.slice(0,t).trim()+":"+await jn(s.slice(t+1).trim(),n,r)}{const t=s.trim();if(n&&void 0!==hn(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await jn(s.trim(),n,r)}}function Cn(t,e,n){const r=n?.delimiter??",",i=n?.assigner??"=";let s=[],o=!1,a="",c="",u=!1,f="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==r||o||f)if("\\"===n)c+=n,e++,c+=t[e];else if("("!==n&&"["!==n||o)if(f&&n===f)f="",c+=n;else if("{"!==n||o)'"'===n||"'"===n?(o&&n===a?o=!1:o||(o=!0,a=n),c+=n):n!==i||o||u||!/^[\p{L}\p{N}_ ]+$/u.test(c)?c+=n:(c+=":",u=!0);else{let r,i=e,s=!1,o="",a=-1;for(;i<t.length&&("}"!==(r=t[i])||s||a>0);)"\\"===r?i++:"{"!==r||s?"}"!==r||s?'"'!==r&&"'"!==r||(s&&n===o?s=!1:s||(s=!0,o=n)):a--:a++,i++;i<t.length&&(c+=t.substring(e,i+1),e=i)}else f="("===n?")":"]",c+=n;else c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c]),c="",u=!1}return c&&(c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c])),s}async function On(t,e,n){const r=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!r){if(n?.raiseError)throw new Error("Invalid command format");return}const[,i,s]=r;let o;return s&&(o=await pn(s,e,n)),{command:i.trim(),args:o}}var Nn="__PlacEhoLdeR_";function Mn(t,e){let n=e?.startChar?Array.isArray(e.startChar)?e.startChar:[e.startChar]:['"',"'"],r=e?.endChar?Array.isArray(e.endChar)?e.endChar:[e.endChar]:n;if(n.length!==r.length)throw new Error("start and end characters must have the same length");const i=e?.placeholder??Nn,s=n.every((t,e)=>t===r[e]),o=e?.placehoders??[];if(s){n=n.map(t=>"\\"+t);const e=new RegExp(`(?<!\\\\)(${n.join("|")}).*?(?<!\\\\)\\1`);let r;for(;null!==(r=e.exec(t));){const e=`${i}${o.length}`;t=t.replace(r[0],e),o.push(r[0])}}else{n=n.map(t=>"\\"+t),r=r.map(t=>"\\"+t);for(let e=0;e<n.length;e++){const s=new RegExp(`(?<!\\\\)${n[e]}.*?(?<!\\\\)${r[e]}`);let a;for(;null!==(a=s.exec(t));){const e=`${i}${o.length}`;t=t.replace(a[0],e),o.push(a[0])}}}return[t,o]}function Rn(t,e,n){const r=n?.placeholder??Nn;return e.reduce((t,e,n)=>t.replace(new RegExp(r+n,"g"),e),t)}var zn="[a-zA-Z_$][a-zA-Z_\\d$]*",_n=new RegExp(`^\\s*(\\(\\s*\\)|${zn}|\\(${`${zn}\\s*(,\\s*${zn})*`}\\))\\s*=>`);function Ln(t){return _n.test(t)}async function Dn(t,e){if(e&&(e=Bn(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await pn(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return Pn(t,e)}function Pn(t,e){if(e&&(e=Bn(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);let i=0;for(;i++<100;)try{return fn("expression",n,`return ${t}`)(...r)}catch(t){if(!(t instanceof ReferenceError))throw t;{const e=/(.+)\s+is not defined/.exec(t.message);if(!e)throw t;n.push(e[1]),r.push(void 0)}}}}return fn("expression",[],`return ${t}`)()}var Xn=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Fn=t=>Xn.test(t);function Bn(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter(e=>Fn(e)&&null!==t[e]);if(n===r.length)return t;if(r.length)return t=un(t,r)}}function qn(t){return t?Un(t,[],{dot:""}):[]}function Un(t,e,{dot:n=".",visited:r=new Set}={}){return r.has(t)?[e.join("")]:Array.isArray(t)?(r.add(t),t.flatMap((t,n)=>Un(t,[...e,`[${n}]`],{dot:".",visited:r}))):(i=t)&&i.constructor===Object?(r.add(t),Object.entries(t).flatMap(([t,i])=>Un(i,[...e,n+t],{dot:".",visited:r}))):[e.join("")];var i}function Gn(t){if(t<2)throw new f("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",l.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}import Wn from"path";import*as Zn from"fs";import Jn from"mime-type/with-db";import Hn from"jschardet";function Kn(t){const e=Zn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Qn(t,e,n,r){const i=r?.signal,s=r?.exclude;let o;if(Wn.isAbsolute(t)?o=Kn(t)?t:Vn(Wn.basename(t),[Wn.dirname(t)],{extNames:n,exclude:s,signal:i}):(e||(e=["."]),o=Vn(t,e,{extNames:n,exclude:s,signal:i})),!o)throw new d(t,"loadFileFromPaths");{const t=o;o=Zn.readFileSync(o),r&&(r.filepath=t)}return o}function Vn(t,e,{extNames:n,signal:r,exclude:i=[]}){let s;const o=n?n.map(e=>Ve(t,Ke(e))):void 0;"string"==typeof i&&(i=[i]);for(const a of e){if(r?.aborted)throw r.reason;const e=Wn.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const r=e+(o[t]!==n[t]?n[t]:"");if(!i.includes(r)&&Kn(r)){s=r;break}}else if(!i.includes(e)&&Kn(e)){s=e;break}}return s}function Yn(t,e,n,r,i){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding;return tr(Qn(t,e,n,r),s)}function tr(t,e){void 0===e&&(e=or(t)??"utf8");return new TextDecoder(e).decode(t)}function er(t,e){const n=[],r="string"==typeof t?[{dir:t,level:0}]:[...t.map(t=>({dir:t,level:0}))],i=new Set,s=e?.signal,o=e?.isFileMatched,a=e?.level,c=e?.resolveSymlinks??!0;let u=0;for(;r.length>0;){if(s?.aborted)throw s.reason;const t=r.pop(),e=c?nr(t.dir):t.dir,f=Wn.resolve(e);if(i.has(f))continue;i.add(f);const h=Zn.statSync(e,{throwIfNoEntry:!1});if(h?.isDirectory()){u=t.level+1;const i=Zn.readdirSync(e,{withFileTypes:!0});for(let t=0;t<i.length;t++){let s=i[t],f=Wn.join(e,s.name);const h=f;if(s.isSymbolicLink()){const t=Wn.dirname(f);if(f=Zn.readlinkSync(f),f=Wn.resolve(t,f),s=Zn.statSync(f,{throwIfNoEntry:!1}),!s)continue}if(s.isDirectory())(!a||u<a)&&(o&&!o(f,s)||r.push({dir:f,level:u}));else if(s.isFile()&&(!o||o(f,s))){const t=c?f:h;n.includes(t)||n.push(t)}}}}return n}function nr(t){const e=Zn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Zn.readlinkSync(t)),t}async function rr(t,e){return Ne(ReadableStream.from(Zn.createReadStream(t)),e)}async function ir(t){const e=Wn.basename(t);t=Wn.resolve(t);const n=await Zn.promises.stat(t),r=n.mtime,i=n.ctime,s=n.size,o=sr(s),a=await rr(t,{hashAlgo:o}),c=Jn.lookup(t);return{name:e,mtime:r,ctime:i,size:s,hash:ke[o]+":"+a,mimeType:c,id:"file://"+t}}function sr(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function or(t,e){return Hn.detect(t,e).encoding}import{statSync as ar}from"fs";import cr from"path";import{ConfigFile as ur,registerYamlTag as fr,traverseFolderSync as hr}from"@isdk/util";import{regexp as lr}from"yaml-types";import{mimeType as mr}from"mime-type/with-db";import{ConfigFile as pr,registerYamlTag as dr,parseYaml as yr,stringifyYaml as wr}from"@isdk/util";function br(t,e){const n=[],r=e?.after,i=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,s=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map(t=>t.startsWith(".")?t:"."+t):[".yml",".yaml",".json"];return hr(t,(t,e)=>{if(i?.includes(t)||!e.isFile())return;const o=cr.extname(t),a=ar(t);if(s.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}}),n}function vr(t,e){return br(t,e).map(t=>ur.loadSync(t)).filter(t=>void 0!==t)}function gr(t,e,n=1){return ur.saveSync(t,e,{extLevel:n})}function kr(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function $r(t,e){return t.map(t=>Sr(t,e)).join(" AND ")}function xr(t,e){return t.map(t=>Sr(t,e)).join(" OR ")}function Ar(t,e){const n=[];return Object.keys(e).forEach(r=>{const i=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${kr(i)}`);break;case"<=":case"$lte":n.push(`${t} <= ${kr(i)}`);break;case"$gt":case">":n.push(`${t} > ${kr(i)}`);break;case"$gte":case">=":n.push(`${t} >= ${kr(i)}`);break;case"$ne":case"!=":n.push(`${t} != ${kr(i)}`);break;case"=":case"$eq":n.push(`${t} = ${kr(i)}`);break;case"$in":n.push(`${t} IN (${i.map(t=>kr(t)).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${i.map(t=>kr(t)).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${i.source}'`);break;case"$like":n.push(`${t} LIKE '${i}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${i}'`);break;case"$glob":n.push(`${t} GLOB '${i}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${i}'`);break;default:throw new Error(`Unsupported condition operator: ${r}`)}}),n.join(" AND ")}function Sr(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push($r(t,e));else for(const[r,i]of Object.entries(t))if("$and"===r)n.push(`(${$r(t[r],e)})`);else if("$or"===r)n.push(`(${xr(t[r],e)})`);else{const t=typeof i;if(null==i)n.push(`${e(r)} IS NULL`);else if(i instanceof Date)n.push(`${e(r)}='${i.toISOString()}'`);else if("object"!==t||Array.isArray(i))if("string"===t)n.push(`${e(r)}='${i}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${r}`);n.push(`${e(r)}=${i}`)}else n.push(Ar(e(r),i))}return n.length>1?n.join(" AND "):n[0]}function Er(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function Tr(t,e=0){let n,r=t*10**e;return t>=1e12?(r=Math.round(r/1e12),n="T"):t>=1e9?(r=Math.round(r/1e9),n="B"):t>=1e6?(r=Math.round(r/1e6),n="M"):t>=1e3?(r=Math.round(r/1e3),n="K"):(r=Math.round(r),n=""),r/=10**e,r.toFixed(e)+n}function jr(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new f("Invalid formatted parameter size string.","scaleToSize",l.InvalidArgument);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function Ir(t,e){const n=e?.level||0,r=e?.visiting||new Set,i=e?.objectTag||"*",s=e?.arrayTag||"-",o=!0===e?.title?"name":e?.title;let a=[];const c=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":r.has(t)?a=["[Circular]"]:(r.add(t),a=Array.isArray(t)?t.map(e=>s+u(e,t)):Object.entries(t).map(([e,n])=>i+" `"+e+"`:"+u(n,t)));break;case"string":return t;default:return JSON.stringify(t)}else a=["null"];return a.length?c+a.join("\n"+c):"";function u(t,e){const i=null!=t&&"object"==typeof t;let s="";return o&&"string"==typeof o&&i&&t[o]&&"string"==typeof t[o]&&(s=" "+t[o],delete t[o]),(i?s+"\n":" ")+Ir(t,{level:n+1,visiting:r,parent:e})}}fr(lr);var Cr=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}};import{isAsync as Or}from"util-ex";import{EventEmitter as Nr}from"events-ex";function Mr(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 Rr=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=Mr(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this[n]=t,++e<=this._capacity&&(this._length=e),n}unshift(t){let e=this._length;this.checkCapacity(++e);const n=this._capacity,r=(this._front-1&n-1^n)-n;return this[r]=t,this._front=r,e<=this._capacity&&(this._length=e),r}pop(t){let e=this._length;if(0===e)return;let n=this._front+e-1&this._capacity-1,r=this[n];for(;--e>0&&t&&null==r;)n--,r=this[n];return this[n]=void 0,this._length=e,r}shift(t){let e=this._length;if(0===e)return;let n=this._front,r=this[n];for(;--e>0&&t&&null==r;)n=n+1&this._capacity-1,r=this[n];return this[n]=void 0,this._front=n+1&this._capacity-1,this._length=e,r}get size(){return this._length}get(t){let e;if(t===(0|t)){const n=this._length;t<0&&(t+=n),t>=0&&t<n&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,n=this._capacity;for(let r=0;r<t;++r)this[e+r&n-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const n=this._front,r=this._capacity-1,i=n+t&r,s=this[i];if(t<e/2)this.copyWithin(n+1&r,n,n+t&r),this[n]=void 0,this._front=n+1&r;else{this.copyWithin(i,i+1&r,n+e&r);this[n+e-1&r]=void 0}return this._length=e-1,s}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(Mr(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,r=this._length;if(n+r>e){!function(t,e,n,r,i){for(let s=0;s<i;++s)n[s+r]=t[s+e],t[s+e]=void 0}(this,0,this,e,n+r&e-1)}}};import{AbortError as zr}from"@isdk/common-error";var _r=32;function Lr(t){return"function"==typeof t}function Dr(){return"1"}var Pr=class{constructor(t={}){const{initFn:e=Dr,pauseFn:n,resumeFn:r,capacity:i=_r}=t;if(Lr(n)!==Lr(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new Rr(i),this.emitter=new Nr,this.useDefaultTokens=e===Dr,this.pauseFn=n,this.resumeFn=r,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,n=this.waiting.shift(!0);n?this._dispatchTask(n,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",t=>{this.onReleased(t)})}_newReleaser(t){let e=!1;const n=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(n,t),n}_dispatchTask(t,e){const{resolve:n}=t;n(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,n=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push(t),r=t.reject;return e&&e.addEventListener("abort",()=>{this.waiting[n]=void 0;const t=e.reason instanceof Error?e.reason:new zr(e.reason||"aborted");e.alreadyRejected=!0,r(t)}),n};let r=this.tryAcquire(t);const i=r&&Or(r),s=e=>new Promise((r,i)=>{const s={...t,resolve:r,reject:i,token:e};void 0===e?n(s):this._dispatchTask(s,{...t,token:e})});return i?r.then(t=>s(t)):s(r)}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 zr(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},Xr=class extends Pr{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 Rr(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&Or(e)){return e instanceof Promise||(e=e()),e.then(e=>{if(e)return this.lock(t)})}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}};function Fr(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new Xr(n?1:t),i=n?e/t:e;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}import{AbortError as Br}from"@isdk/common-error";var qr=class{constructor(){this._isSignaled=!1,this.waitQueue=[]}get signaled(){return this._isSignaled}signal(t){if(this._isSignaled)return;this._isSignaled=!0,this._signalValue=t;const e=this.waitQueue.slice();for(this.waitQueue.length=0;e.length>0;){const t=e.shift();t?.resolve(this._signalValue)}}reset(){this._isSignaled=!1,this._signalValue=void 0,this.waitQueue.length=0}abort(t){if(this.waitQueue.length){const e=this.waitQueue.slice();this.waitQueue.length=0;const n=new Br(t);for(;e.length>0;){const{reject:t}=e.shift();t(n)}}}async wait(){return new Promise((t,e)=>{this._isSignaled?t(this._signalValue):this.waitQueue.push({resolve:t,reject:e})})}};import{createAbilityInjector as Ur}from"custom-ability";import{defineProperty as Gr}from"util-ex";var Wr,Zr=0,Jr=1,Hr=2,Kr=(t=>(t[t.MultiTask=0]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(Kr||{}),Qr=((Wr=Qr||{})[Wr.MultiTask=1]="MultiTask",Wr[Wr.Cancelable=2]="Cancelable",Wr[Wr.Priority=4]="Priority",Wr),Vr=class extends AbortController{constructor(t){super(),Gr(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new s(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 s(e.reason||"aborted")}}},Yr=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,n=this.__task_semaphore;return e>0&&!n&&(t&&(t=t.bind(this)),n=this.__task_semaphore=new Xr(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Cr.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Cr.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new f("Missing taskId",this.name+".isAborted",l.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new f("Missing taskId",this.name+".getRunningTask",l.InvalidArgument);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(0)){const e=this.__task_aborter;t=e&&Object.entries(e).filter(([t,n])=>{if(!n?.signal.aborted)return!0;e[t]=void 0}).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const n=this.super,r=this.self||this;return t=n?n.call(r,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const r=this.hasAsyncFeature(0);if(!r&&n&&this.getRunningTask())throw new f("The task is running",this.name,l.TooManyRequests);const i=t?.aborter||new Vr(this);if(!(i instanceof Vr)){if(!(i instanceof AbortController))throw new f("aborter should be an AbortController",this.name,l.InvalidArgument);Object.setPrototypeOf(i,new Vr(this))}if(r){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),i.id=e,t[e]=i}else this.__task_aborter=i;const s=[...ti(t?.signal),...ti(t?.signals)];s.length&&function(t,e){if(!e.length)return;const n=[],r=()=>{for(const t of n)try{t()}catch{}n.length=0},i=e.find(t=>t.aborted);if(i){const e=i.reason;try{t.abort(e||"aborted")}catch{}return}for(const r of e){const e=()=>{const e=r.reason;try{t.abort(e||"aborted")}catch(t){console.log(t)}};r.addEventListener("abort",e,{once:!0}),n.push(()=>r.removeEventListener("abort",e))}const s=()=>r();t.signal.addEventListener("abort",s,{once:!0}),n.push(()=>t.signal.removeEventListener("abort",s))}(i,s);const o=t?.timeout;return o>0&&(i.timeoutId=setTimeout(()=>{i.timeoutId=void 0,this.abort("timeout",{timeout:o})},o)),i.signal.addEventListener("abort",()=>{const t=i.timeoutId;t&&(i.timeoutId=void 0,clearTimeout(t));const e=i.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{try{i.streamController?.error?.(e.reason)}catch{}}}),i}$cleanMultiTaskAborter(t,e){const n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(0)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,n){const r=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=r);let i=t(e,r).then(t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(r)},n=He({onStart:t=>{Gr(r,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=r.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(r);return t}).catch(t=>{throw this.cleanTaskAborter(r),t}).finally(()=>{r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=void 0)});return i.task=r,i}runAsyncCancelableTask(t={},e,n){let r=this.createTaskPromise(e,t,n);const i=this.getSemaphore(n?.isReadyFn);if(i){const t=r,e=t.task;r=i.acquire({signal:e.signal}).then(()=>t).finally(()=>{i.release()}),r.task=e}return r}abort(t,e){let n=this.__task_aborter;if(n){const r=n;if(this.hasAsyncFeature(0)){const t=e?.taskId;if(null==t)throw new f("Missing data.taskId",this.name+".abort",l.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};function ti(t){return t?Array.isArray(t)?t.filter(Boolean):[t]:[]}Yr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Yr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var ei=Ur(Yr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Qr.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=n}});function ni(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let r,i=0;for(;null!==(r=n.exec(t));)i++;return i}import ri from"memoizee";import{canonicalize as ii}from"json-canonicalize";function si(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const r=e?.normalizer;return ri(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return je(ii(t))}})}import oi from"path";import{packageDirectorySync as ai}from"package-directory";function ci(t){const e=ai({cwd:t});if(e)return e;const n=t.split(oi.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(oi.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(oi.sep);throw new Error("can not find package directory")}import ui from"path";function fi(t,e){try{const n=ui.relative(ui.resolve(t),ui.resolve(e));return!n.startsWith("..")&&!ui.isAbsolute(n)}catch{return!1}}function hi(t,e){return e?.some(e=>fi(e,t))}function li(t,e){for(const n of e)hi(n,t)||t.push(n);return t}function mi(t){const e=t.slice();return pi(e),e}function pi(t){const e=t.length;if(e<=1)return;const n=new Map,r=[];for(let i=0;i<e;i++){const e=di(t[i]);n.has(e)||(r.push(e),n.set(e,i))}const i=[...r].sort(),s=new Set;for(let t=0;t<i.length;t++){const e=i[t];let n=!1;for(const t of s)if(fi(t,e)){n=!0;break}n||s.add(e)}let o=0;for(let n=0;n<e;n++)s.has(r[n])&&(o!==n&&(t[o]=t[n]),o++);t.length=o}function di(t){let e=ui.normalize(t);return e=e.split(/[/\\]/).join(ui.posix.sep),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}import{isRegExp as yi,isRegExpStr as wi}from"util-ex";function bi(t){return wi(t)||yi(t)}function vi(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}import gi from"path";import{fileURLToPath as ki}from"url";import{AutoTokenizer as $i}from"@huggingface/transformers";var xi=ki(import.meta.url),Ai=gi.dirname(xi),Si=gi.join(ci(Ai),".cache"),Ei=new Map,Ti={"deepseek-ai/DeepSeek-V2-Lite-Chat":"deepseek2","Qwen/Qwen2.5-0.5B":"Qwen2.5","Xenova/gpt-4":"gpt-4 / gpt-3.5-turbo / text-embedding-ada-002","Xenova/text-davinci-003":"text-davinci-003 / text-davinci-002","Xenova/gpt-3":"gpt-3","Xenova/grok-1-tokenizer":"Grok-1","Xenova/claude-tokenizer":"Claude","Xenova/mistral-tokenizer-v3":"Mistral v3","Xenova/mistral-tokenizer-v1":"Mistral v1","Xenova/gemma-tokenizer":"Gemma","Xenova/gemma2-tokenizer":"Gemma2","Xenova/llama3-tokenizer-new":"Llama 3","unsloth/Llama-3.2-1B-Instruct":"Llama 3.2","Xenova/llama-tokenizer":"LLaMA / Llama 2","Xenova/c4ai-command-r-v01-tokenizer":"Cohere Command-R","Xenova/t5-small":"T5","Xenova/bert-base-cased":"bert-base-cased"},ji={deepseek2:"deepseek-ai/DeepSeek-V2-Lite-Chat","qwen2.5":"Qwen/Qwen2.5-0.5B","gpt-4":"Xenova/gpt-4","gpt-3.5-turbo":"Xenova/gpt-4","text-embedding-ada-002":"Xenova/gpt-4","text-davinci-003":"Xenova/text-davinci-003","text-davinci-002":"Xenova/text-davinci-003","gpt-3":"Xenova/gpt-3","grok-1":"Xenova/grok-1-tokenizer",claude:"Xenova/claude-tokenizer",mistral:"Xenova/mistral-tokenizer-v3",mistral3:"Xenova/mistral-tokenizer-v3",mistral1:"Xenova/mistral-tokenizer-v1",gemma:"Xenova/gemma-tokenizer",gemma2:"Xenova/gemma2-tokenizer",llama3:"Xenova/llama3-tokenizer-new",llama2:"Xenova/llama-tokenizer",llama:"Xenova/llama-tokenizer","llama3.2":"unsloth/Llama-3.2-1B-Instruct","cohere-command-r":"Xenova/c4ai-command-r-v01-tokenizer",t5:"Xenova/t5-small","bert-cased":"Xenova/bert-base-cased"};async function Ii(t){let e=Ei.get(t);return e||(e=$i.from_pretrained(t,{cache_dir:Si}),Ei.set(t,e)),e}async function Ci(t,e="qwen2.5"){ji[e]&&(e=ji[e]);return(await Ii(e)).encode(t)}async function Oi(t,e="qwen2.5"){return(await Ci(t,e)).length}function Ni(t,e){const n=e?.capitalize??!0;let r=e?.delimiter??/[_-]/g;r instanceof RegExp&&(r.flags.includes("g")||(r=new RegExp(r.source,r.flags+"g")));let i=(t=t.replace(r," ")).split(" ").map(t=>t.trim()).filter(Boolean);return n&&(i=i.map(t=>t.charAt(0).toUpperCase()+t.slice(1))),t=i.join(" ")}async function Mi(t,e){let n,r=1984,i=!0,s=!1,o=!0,a=Oi,c=!0;if(e&&(n=e.modelId,e.size>=0&&(r=e.size),void 0!==e.corrected&&(i=e.corrected),void 0!==e.completeSentence&&(s=e.completeSentence),void 0!==e.truncLastSection&&(o=e.truncLastSection),"function"==typeof e.countLLMTokens&&(a=e.countLLMTokens),void 0!==e.bySentence&&(c=e.bySentence)),!c)throw new w("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(r>0){let c=await a(t,n);const u=e?.sentences??pt(t,e);if(c>r)for(c=await a(u.join("\n"),n);c>r&&u.length;){const e=u.pop();if(e){if(c-=await a(e+"\n",n),s||i)t=u.join("\n");else{const n=t.lastIndexOf(e);if(-1===n)throw new f(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n)}if(c<=1)throw new f(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(c<=r&&o){const e=u[u.length-1];if(e&&vt(e)){if(c-await a(e,n)>9){const n=t.lastIndexOf(e);if(-1===n)throw new f(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n).trimEnd()}}}}else c--}else t=u.join("\n")}if(!t)throw new f(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function Ri(t,e){let n,r=1984,i=!0,s=Oi,o=!0;if(e&&(n=e.modelId,e.size>=0&&(r=e.size),void 0!==e.truncLastSection&&(i=e.truncLastSection),"function"==typeof e.countLLMTokens&&(s=e.countLLMTokens),void 0!==e.bySentence&&(o=e.bySentence)),!o)throw new w("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(r>0){const e=(t=t.slice()).join("\n");let o=await s(e,n);if(o>r)for(;o>r&&t.length;){const e=t.pop();if(e){if(o-=await s(e,n),o<=1)throw new f(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(o<=r&&i){const e=t[t.length-1];if(e&&vt(e)){o-await s(e,n)>9&&t.pop()}}}}}if(!t.length)throw new f(`Empty. Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function zi(t,e){let n,r=1984,i=Oi;if(e&&(n=e.modelId,"function"==typeof e.countLLMTokens&&(e.size>=0&&(r=e.size),i=e.countLLMTokens)),r>0){await i(t,n)}}import _i from"fs";async function*Li(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,r=e.modelId,i=e.metaInfo?.size??(await _i.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=tr(await _i.promises.readFile(t));if(s=await Oi(i,r),s<=n)yield i;else do{const t=await Mi(i,{...e,modelId:r,size:n});yield t,i=i.slice(t.length)}while(i)}else{const i=ReadableStream.from(_i.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=tr(o);const a=pt(s,e);let c=a.pop();if(c){const t=s.lastIndexOf(c);c=s.slice(t),s=s.slice(0,t)}if(s.length>=n){const t=await Mi(s,{...e,modelId:r,size:n,sentences:a});s=s.slice(t.length),yield t}for(;s.length>n;){const t=pt(s,e),i=await Mi(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}void 0!==c&&(s+=c)}for(;s;){const t=pt(s,e),i=await Mi(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}}}async function*Di(t,e){const n=e?.size??1984,r=e?.modelId,i=e?.metaInfo?.size??(await _i.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=tr(await _i.promises.readFile(t));if(s=await Oi(i,r),s<=n)yield pt(i,e);else{let t=pt(i,e);do{const i=await Ri(t,{...e,modelId:r,size:n});yield i,t=t.slice(i.length)}while(t.length)}}else{const i=ReadableStream.from(_i.createReadStream(t)).getReader();let s="";const o=e?.completeSentence,a=e?.corrected,c=!o&&!a;let u;for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=tr(o),u=pt(s,e);let a=u.pop();if(s.length>=n){const t=await Ri(u,{...e,modelId:r,size:n});s=c?s.slice(t.length):u.join("\n"),u=u.slice(t.length),s=u.join("\n"),yield t}for(;s.length>n;){const t=await Ri(u,{...e,modelId:r,size:n});u=u.slice(t.length),s=u.join("\n"),yield t}a&&u.push(a)}if(u)for(;u.length;){const t=await Ri(u,{...e,modelId:r,size:n});u=u.slice(t.length),yield t}}}async function Pi(t,e){const n=e?.size??1984,r=e?.modelId;let i=pt(t,e);const s=[];if(await Oi(t,r)<=n)s.push(i);else do{const t=await Ri(i,{...e,modelId:r,size:n});s.push(t),i=i.slice(t.length)}while(i.length);return s}import{YAMLMap as Xi}from"yaml";var Fi=class{constructor(t){t&&Object.assign(this,t)}};function Bi(t,e){const n={tag:t,collection:"map",nodeClass:class extends Xi{constructor(){super(...arguments),this.tag=t}toJSON(t,n){n={...n,mapAsMap:!1};const r=super.toJSON(t,n);return new e(r)}},identify:t=>t instanceof e};return n}function qi(t,e){let n=t.length===e.length;if(n){const r=Te(t),i=Te(e);n=r.every((t,e)=>t===i[e])}return n}import{defaultsDeep as Ui,get as Gi,omit as Wi,set as Zi}from"lodash-es";import Ji from"path";var Hi=".ai";function Ki(t,e=["."]){if(Ji.isAbsolute(t))return pr.loadSync(t);const n=e.map(e=>pr.loadSync(Ji.resolve(e,t))).filter(Boolean);return Ui({},...n.reverse())}function Qi(t,e){const n={...process.env,...e};return n.HOME||(n.HOME=process.env.USERPROFILE),W(t,{processEnv:n,parsed:n})}function Vi(t,e){let n=pr.loadSync(Ji.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:Ji.join(e.dataDir,"brain"),agentDirs:[Ji.join(e.dataDir,"agent")],promptDirs:[Ji.join(e.dataDir,"prompt")],chatsDir:Ji.join(e.dataDir,"log","chats"),inputsDir:Ji.join(e.dataDir,"log","inputs")});const r=ts(e);for(const[t,e]of Object.entries(r))n[t]=e;Qi(n,n);const i=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Qi(Ki(t,i),n);return Ui(s,Wi(n,Object.keys(r))),rs(s),s}function Yi(t){return Vi(".ai",t)}function ts(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:Ji.dirname(t.options.root)}}function es(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Qi(t,e)}function ns(t,e){return t.map(t=>es(t,e))}function rs(t,e=["configDirs","brainDir","agentDirs","promptDirs","chatsDir","inputsDir"],n){for(const r of e){const e=Gi(t,r);if(!e)continue;let i;Array.isArray(e)&&e.length?i=ns(e,n):"string"==typeof e&&(i=es(e,n)),i&&Zi(t,r,i)}}var{exit:is}=process,ss=!1,os=!1,as=["SIGINT","SIGTERM","exit"],cs=[],us=(t,e)=>t.forEach(t=>process.once(t,e));async function fs(t="shutdown",e=0){if(!ss){ss=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of cs)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return is(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function hs(t){if(os||ls(),!cs.some(e=>e===t))return cs.push(t),t}function ls(){var t;os||(os=!0,process.exit=t=>{ss||fs(void 0,t).then()},us(as,(t=3e5,()=>{setTimeout(()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),is(1)),t).unref()})),us(as,fs))}var ms=["<BOS>","<EOS>","<PAD>","<UNK>"],ps=".,!?;?!",ds=[" ","\n","\t","▁"," "],ys=["the","a","an","的","是","在"];function ws(t,e){const n=e?.exclude?function(t){const e=new Set;if(t.controlSymbols&&ms.forEach(t=>e.add(t)),t.punctuation)for(let t=0;t<7;t++)e.add(ps[t]);return t.stopWords&&ys.forEach(t=>e.add(t)),t.whitespace&&ds.forEach(t=>e.add(t)),Array.isArray(t.tokens)&&t.tokens.forEach(t=>e.add(t)),[...e]}(e.exclude):void 0;return n&&n.length&&(t=t.filter(t=>!n.includes(t.token.trim()))),bs(t)}function bs(t){if(!Array.isArray(t)||0===t.length)return;const e=t.reduce((t,e)=>t+e.probability,0);return Math.exp(-e/t.length)}import{mergeWith as vs}from"lodash-es";var gs=/^\s*@inheritMerge\s*(?:[(]\s*(?<arg>\.start|\.end|false)[)])?/,ks=Symbol("MergeWay"),$s={replace:0,start:1,end:2};function xs(t,...e){return vs(t,...e,(t,e)=>Array.isArray(t)&&Array.isArray(e)?As(t,e):void 0!==t&&"object"!=typeof t?t:void 0)}function As(t,e){let n=t[ks];return void 0===n&&(t=function(t){const e=t[0];let n=".start";if("string"==typeof e){const r=gs.exec(e);r&&(r.groups?.arg&&(n=r.groups?.arg),t=t.slice(1))}else e&&"object"==typeof e&&e.hasOwnProperty("@inheritMerge")&&(n=e["@inheritMerge"]||n,t=t.slice(1));n&&(n=n.toLowerCase());let r=$s.start;"false"===n||"no"===n||"not"===n?r=$s.replace:".end"===n&&(r=$s.end);return Object.defineProperty(t,ks,{value:r,enumerable:!1}),t}(t),n=t[ks]),t=n===$s.replace?e:n===$s.end?t.concat(e):e.concat(t),Object.defineProperty(t,ks,{value:n,enumerable:!1}),t}function Ss(t,e=" "){return Es(t).join(e)}function Es(t){return t.split(/(?<=[a-z])(?=[A-Z])|(?<=\d)(?=[A-Za-z])|(?<=[A-Z])(?=[A-Z][a-z])|[\s_]+/g).filter(t=>t.length>0)}function Ts(t,e){if(void 0!==t){const n=JSON.stringify(t);if("{}"!==n&&"[]"!==n&&'""'!==n){const t="p="+encodeURIComponent(n);return e?t:"?"+t}}return""}var js=class t extends r{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const r=this.get(n);let i=r.tags;if("string"==typeof i){if(i===t){e=r;break}}else if(Array.isArray(i)&&i.indexOf(t)>=0){e=r;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const r=this.get(n);let i=r.tags;"string"==typeof i?i===t&&e.push(r):Array.isArray(i)&&i.indexOf(t)>=0&&e.push(r)}return e}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures??0;return e._asyncFeatures&&(n|=e._asyncFeatures),Cr.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new d(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new d(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const n=this.get(t);if(n)return n.runWithPos(...e);throw new d(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new d(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let r=!!this.get(e);if(r)r=!1;else{if(!(n instanceof t))return r=new this(n),r.register();if(this.items[e]=n,n.alias){const t=n.alias;if("string"==typeof t)this.aliases[t]&&b(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const n of t)this.aliases[n]&&b(`Alias ${n} already exists for ${e}`),this.aliases[n]=e}r=n}return r}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,n=this.depends;if(n){const e=Object.keys(n);for(const r of e){const e=n[r];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},n=Object.keys(this.params);let r=Math.min(n.length,t.length);for(let i=0;i<r;i++)e[n[i]]=t[i];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let r=Math.min(n.length,this.params.length);for(let i=0;i<r;i++)e.push(t[n[i]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);b("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??0;return this._asyncFeatures&&(e|=this._asyncFeatures),Cr.has(e,t)}isStream(t){let e=this.stream;if(e){const n=this.params;n?.stream&&(e=t?.stream)}return e}},Is={name:{type:"string"},description:{type:"string"},title:{type:"string"},func:{type:"function",assign(t,e,n,r,s){let o=t;const a=typeof t;return s.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=i(t,e.scope)),o}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"},alias:{type:["array","string"]}};js.defineProperties(js,Is);var Cs=Symbol("meta");function Os(t,r,i=!0){if(r&&"object"==typeof r){if("function"==typeof t)return r=i?e({},t[Cs],r):n({},t[Cs],r),t[Cs]=r,t;if(t instanceof js)return t.assign(r)}}function Ns(t){return"function"==typeof t?t[Cs]:t instanceof js?t.toObject():void 0}var Ms=class extends js{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Rs=new Ms(Ft);import{Cache as zs}from"secondary-cache";import{LRUCache as _s}from"secondary-cache";var Ls=zs;function Ds({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function Ps(t,e){let n=js.get(t);return n||(n=new js(t,{func:Ds,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),n.cache=new zs(e)),n}var Xs=Ps("lrucache");import{defaultsDeep as Fs}from"lodash-es";var Bs="A client transport has not been set. Use ClientTools.setTransport() or transport.mount(ClientTools) first.",qs=class t extends js{static get apiRoot(){return this._transport||b(Bs,"ClientTools"),this._transport.apiRoot}static setTransport(t){if(t){this._transport=t;const e=this.constructor;t.Tools!==e&&(t.Tools=e)}}static get transport(){return this._transport}static async loadFrom(t){return t||(this._transport||b(Bs,"ClientTools"),t=await this._transport.loadApis()),t&&this.loadFromSync(t),t}static loadFromSync(e){for(const n in e){const r=this.get(n),i=e[n];r?r instanceof t?r.assign(i):b(`${n} already registered as ${r.constructor.name}`,"ClientTools"):this.register(i)}}static async fetch(t,e,...n){const r=this.get(t);if(r&&r.fetch)return r.fetch(e,...n)}get apiRoot(){return this.constructor.apiRoot}async fetch(t,e,n,r){const i=this.constructor;if(i._transport)return r=Fs(r,this.fetchOptions),i._transport.fetch(this.name,t,e,n,r);b(Bs,"ClientTools")}async func(t){return await this.fetch(t)}},Us={...x};qs.defineProperties(qs,Us);var Gs=class extends qs{async fetch(t,e,n,r){return t||(t={}),e?.startsWith("$")&&(t.act=e,e="post"),await super.fetch(t,e,n,r)}async _func(t,e,n){return await this.fetch(e,t,null,n)}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))}}},Ws={methods:{type:"array",assign(t,e,n,r,i){i?.isExported||e.assignMethods(t)}}};Gs.defineProperties(Gs,Ws);var Zs=class extends Gs{async fetch(t,e,...n){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||b("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e,...n)}};import{defaultsDeep as Js}from"lodash-es";var Hs=class extends Zs{constructor(){super(...arguments),this._sseListeners={},this._forwardEvents=new Set,this.description="subscribe server event",this.ebListener=async function(...t){const e=t[0];let n=t[1];const r=this.type;("string"!=typeof e||n&&"object"!=typeof n||t.length>2)&&(n=t,e&&e===this.target.name&&(n=t.slice(1))),this.target.publish&&await this.target.publish({data:n,event:r})}}static setPubSubTransport(t){t?.setApiRoot&&this.apiRoot&&t.setApiRoot(this.apiRoot),this._pubSubTransport=t}static get pubSubTransport(){if(!this._pubSubTransport)throw new Error("EventClient pubSubTransport not set");return this._pubSubTransport}get clientId(){return this._stream?.clientId}async getEvtSource(){let t=this._stream;return t&&2!==t.readyState||(t=await this.initEventStream(this._streamEvents)),t}get active(){return!!this._stream&&2!==this._stream.readyState}async setActive(t){t!==this.active&&(t?await this.initEventStream(this._streamEvents):this._stream&&this.close())}async initEventStream(t){const e="string"==typeof t?[t]:t;if(this._stream&&2!==this._stream.readyState){if(!this._streamEvents||e&&e.every(t=>this._streamEvents.includes(t)))return this._stream;this._stream.close()}const n=e?{event:e}:void 0,r=this._stream=await this.constructor.pubSubTransport.connect(this.name,n);return r.clientId&&(this.fetchOptions=Js({clientId:r.clientId},this.fetchOptions)),Object.entries(this._sseListeners).forEach(([t,e])=>{r.on(t,e)}),this._streamEvents=e,r}esListener(t,e,n){if(!this._forwardEvents.has(t)){const n=this.emitter;n&&t&&(Array.isArray(e)?n.emit(t,...e):n.emit(t,e))}}async subscribe(t){this.active||await this.initEventStream(t);const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=await this.getEvtSource();for(const e of t)if(!this._sseListeners[e]){const t=this._sseListeners[e]=(t,n)=>this.esListener(e,t,n);n.on(e,t)}return e}async unsubscribe(t){"string"==typeof t&&(t=[t]);const e=await this.unsub({event:t}),n=await this.getEvtSource();for(const e of t){const t=this._sseListeners[e];t&&(delete this._sseListeners[e],n.off(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.setActive(!1),await this.initEventStream(t),t)return await this.subscribe(t)}close(){const t=this._stream;if(t)return this._stream=void 0,t.close()}},Ks=new Hs(Xt);import{getAllNames as Qs}from"util-ex";var Vs=class t extends js{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];(r instanceof t||r.isApi)&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}run(t,e){return e&&(t._req=e.req,t._res=e.reply),super.run(t)}func(t){}},Ys={...x};Vs.defineProperties(Vs,Ys);var to=class extends Vs{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);Qs(Object.getPrototypeOf(this)).filter(t=>t.startsWith("$")&&"function"==typeof this[t]).forEach(e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])})}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new d(e,this.name)}},eo={methods:{type:"array"}};to.defineProperties(to,eo);var no=class extends to{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=$}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id?e="list":t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},ro=Rs.runSync(),io="client:",so=class t extends no{constructor(){super(...arguments),this.description="subscribe server event",this.result="event",this.depends={[Ft]:Rs}}static{this.autoInjectToLocalBus=!1}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){return this._pubSubTransport||console.warn("EventServer pubSubTransport not set"),this._pubSubTransport}get pubSubTransport(){return this.constructor.pubSubTransport}static publish(t,e,n){return this.pubSubTransport?.publish(t,e,n)}static ebListener(t,...e){this.pubSubTransport?.publish(t,e)}static alreadyForward(t){const e=ro.listeners(t);for(const t of e)if(t===this._boundEbListener)return!0}publishServerEvent(t,e){return this.constructor.publish(t,e)}forward(e){Array.isArray(e)||(e=[e]);const n=this.constructor;n._boundEbListener||(n._boundEbListener=function(...t){return n.ebListener(this.type,...t)});for(const r of e)t.alreadyForward(r)||ro.on(r,n._boundEbListener)}unforward(t){"string"==typeof t&&(t=[t]);const e=this.constructor;if(e._boundEbListener)for(const n of t)ro.off(n,e._boundEbListener)}list({_req:t,_res:e,event:n}){if(this.pubSubTransport)return this.pubSubTransport.connect({req:t,res:e,events:n});b("PubSub transport not available","list",l.NotImplemented)}$sub({event:t,_req:e}){if(this.pubSubTransport||b("PubSub transport not available","sub",l.NotImplemented),t){this.forward(t);const n=e&&this.pubSubTransport.getSessionFromReq?.(e);return n?(this.pubSubTransport.subscribe(n,Array.isArray(t)?t:[t]),{forward:!0,subscribed:!0,event:t,clientId:n.clientId}):(this.pubSubTransport.getSessionFromReq?console.warn("$sub: No session found for request"):e?console.warn(`$sub: The ${this.pubSubTransport.name} Transport does not support dynamic subscription`):console.warn("$sub: missing _req"),{forward:!0,event:t})}b("event is required","sub",l.InvalidArgument)}$unsub({event:t,_req:e}){if(this.pubSubTransport||b("PubSub transport not available","unsub",l.NotImplemented),t){this.unforward(t);const n=e&&this.pubSubTransport.getSessionFromReq?.(e);return n?(this.pubSubTransport.unsubscribe(n,Array.isArray(t)?t:[t]),{forward:!1,subscribed:!1,event:t,clientId:n.clientId}):(this.pubSubTransport.getSessionFromReq?console.warn("$unsub: No session found for request"):e?console.warn(`$unsub: The ${this.pubSubTransport.name} Transport does not support dynamic subscription`):console.warn("$sub: missing _req"),{forward:!1,event:t})}b("event is required","unsub",l.InvalidArgument)}$publish({event:t,data:e,_req:n}){if(t&&e){const r=n&&this.pubSubTransport?.getSessionFromReq?.(n),i=r?.clientId,s=this.constructor;"string"==typeof t&&(t=[t]);for(const n of t)s.autoInjectToLocalBus&&ro.emit(io+n,e,{event:n,sender:r}),this.publishServerEvent(n,e);return{event:t,senderId:i}}b("event or data is required","pub",l.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},oo=new so(Xt);function ao(){Rs.register(),Xs.register()}export{k as PASSING_SCORE,$ as ActionNames,x as RemoteToolFuncSchema,s as AbortError,o as AbortErrorCode,a as AlreadyExistsError,c as AlreadyExistsErrorCode,u as BaseError,f as CommonError,h as createError,l as ErrorCode,m as InternalErrorCode,p as NotFoundErrorCode,d as NotFoundError,y as NotImplementedErrorCode,w as NotImplementationError,b as throwError,S as parseDateFormat,N as DefaultDateFormat,M as toDateTime,R as textToDate,z as dateToText,T as add,j as formatISO,I as parseISO,C as toDate,_ as AITextGenerationFinishReasons,L as AIMessageTypes,D as AIChatRoles,P as StrangeHumanName,X as messagesToText,Q as sortedValues,V as FewShotPromptTemplate,et as PromptExampleSelector,F as StringTemplate,B as EnvStringTemplate,q as FStringTemplate,U as GolangStringTemplate,G as expandEnv,W as expandObjEnv,Z as defaultTemplateFormat,J as getEnvVairables,H as createHfValueFunc,pt as splitSentence,dt as completeSentences,wt as concatText,bt as isSentenceEnding,vt as isSectionString,gt as isTitleString,kt as isListItemString,$t as isSepLineString,xt as isPunctuationChar,St as isLangUsingSpaces,Et as findIndexNonEmptyFrom,Tt as removeMarkdownBold,jt as removeMarkdownItalic,It as removeMarkdownBoldAndItalic,Ct as splitParagraph,Ot as truncTo,Nt as sleep,Mt as wait,Rt as yieldExec,Xt as EventName,Ft as EventBusName,Bt as backendEventable,_t as EventEmitter,Lt as eventable,Dt as states,Pt as wrapEventEmitter,ae as uuid,Kt as v1,Qt as v4,Vt as v5,Yt as v6,te as v7,ee as stringify,ne as parse,re as validate,ie as version,se as NIL,ke as HashAlgorithm,Se as xxhash32,Ee as xxhash64,Te as xxhash,je as xxhashAsStr,Ie as canonicalize,Oe as base32768,Ne as hashStream,Me as hash,Re as hashObject,qt as nanoid,_e as SSEChannelAlreadyClosedErrCode,Le as SSEChannel,De as isWebStream,Pe as RStreamErrCode,Xe as ResponseRStreamErrCode,Fe as ReadableStreamError,Be as getResponseErrorReadableStream,qe as createEmptyReadableStream,Ge as createEventStreamTransformer,We as trimStartOfStreamHelper,Ze as AIStream,Je as readableFromAsyncIterable,He as createCallbacksTransformer,Ke as extNameLevel,Qe as FilenameReservedRegex,Ve as getMultiLevelExtname,Ye as isValidFilename,tn as isValidFilepath,en as sanitizeFilename,nn as sanitizeFilepath,rn as WindowsReservedNameRegex,an as isModelNameMatched,cn as getAllEnumKeys,pn as parseObjectArguments,yn as ObjectArgsToArgsInfo,wn as simplifyObjectArguments,bn as parseObjectArgumentInfos,vn as ChoiceArgProcessor,gn as TemplateArgProcessor,kn as AIArgProcessor,$n as isQuoted,xn as isStrWrapped,An as ensureQuoted,Sn as quoteStr,In as parseObjectArgInfo,Cn as parseObjectArgumentsAsArgInfos,On as parseCommand,Mn as replaceWithPlaceholder,Rn as restoreFromPlacehoders,Dn as parseJsJson,Pn as parseJsJsonSimpleSync,Bn as filterValidFnScope,qn as getKeysPath,Gn as createEndWithRepetitionDetector,Kn as fileIsExists,Qn as loadFileFromPaths,Yn as loadTextFromPaths,tr as decodeCharset,er as readFilenamesRecursiveSync,nr as getRealFilepath,rr as hashFile,ir as getFileMetaInfo,sr as getHashAlgoBySize,or as detectCharset,br as getConfigFileNames,vr as getConfigs,gr as saveConfigFile,mr as mimeType,pr as ConfigFile,dr as registerYamlTag,yr as parseYaml,wr as stringifyYaml,Sr as jsonFilterToWhere,Er as matchUrlProtocol,Tr as paramsSizeToScaleStr,jr as scaleStrToParamsSize,Ir as jsonToMarkdownStr,Cr as IntSet,_r as DefaultAsyncSemaphoreCapacity,Pr as BinarySemaphore,Xr as Semaphore,Fr as RateLimit,qr as SignalGate,Zr as ToolAsyncMultiTaskBit,Jr as ToolAsyncCancelableBit,Hr as ToolAsyncPriorityBit,Kr as AsyncFeatureBits,Qr as AsyncFeatures,Vr as TaskAbortController,Yr as CancelableAbility,ei as makeToolFuncCancelable,ni as countRegexMatches,si as memoize,ci as getPackageDir,fi as isSubdirectory,hi as hasDirectoryIn,li as assignDirs,mi as pruneSubdirectories,pi as pruneSubdirectoriesInPlace,di as normalizePath,bi as isRegExp,vi as stripConsoleColor,Ti as LLM_TOKENIZER_NAMES,ji as LLM_TOKENIZER_NAMES_MAP,Ii as getLLMTokenizer,Ci as encodeLLMTokens,Oi as countLLMTokens,Ni as formatTextWithSpace,Mi as truncateToTokenLimit,Ri as truncateToTokenLimitEx,zi as truncateByToken,Li as readTextFileChunks,Di as readTextFileChunksEx,Pi as splitChunks,Fi as YamlTypeBaseObject,Bi as createYamlObjectTag,qi as isSameString,Hi as DEFAULT_CONFIG_NAME,Ki as loadConfigFile,Qi as expandConfig,Vi as loadConfig,Yi as loadAIConfig,ts as getXDGConfigs,es as expandPath,ns as expandPaths,rs as expandPathInObject,as as SHUTDOWN_SIGNALS,fs as shutdown,hs as beforeShutdown,ls as initShutdown,ws as calcPerplexity,bs as calcPerplexitySimple,ks as ArrayMergeWaySymbol,$s as ArrayMergeWay,xs as defaultsWithConcat,As as mergeArray,Ss as joinSplitWords,Es as splitWords,Ts as genUrlParamsStr,v as createAbilityInjector,g as toRegExp,js as ToolFunc,Is as ToolFuncSchema,Cs as FuncMetaSymbol,Os as funcWithMeta,Ns as funcGetMeta,qs as ClientTools,Us as ClientToolFuncSchema,Vs as ServerTools,Ys as ServerToolFuncSchema,Ms as EventToolFunc,Rs as event,Ls as SecondaryCache,Ds as _lrucache,Ps as createLRUCache,Xs as lrucache,_s as LRUCache,Gs as RpcMethodsClientTool,Ws as RpcMethodsClientToolSchema,Zs as ResClientTools,Hs as EventClient,Ks as eventClient,to as RpcMethodsServerTool,eo as RpcMethodsServerToolSchema,no as ResServerTools,io as ClientEventPrefix,so as EventServer,oo as eventServer,ao as registerCoreTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import n from"net";async function r(r,t=10){return new Promise((o,e)=>{void 0===r?r=0:("string"==typeof r&&(r=parseInt(r)),r>=0||(r=0));const s=n.createServer();s.on("error",n=>{"EADDRINUSE"===n.code&&(r++,--t>0)?s.listen(r):e(n)}),s.on("listening",async()=>{const n=s.address().port;s.close()
|
|
1
|
+
import n from"net";async function r(r,t=10){return new Promise((o,e)=>{void 0===r?r=0:("string"==typeof r&&(r=parseInt(r)),r>=0||(r=0));const s=n.createServer();s.on("error",n=>{"EADDRINUSE"===n.code&&(r++,--t>0)?s.listen(r):e(n)}),s.on("listening",async()=>{const n=s.address().port;s.close(r=>{r?e(r):o(n)})}),s.listen(r)})}export{r as findPort};
|
package/dist/funcs.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
export { ae as EventClient, ad as EventClientFuncParams,
|
|
1
|
+
export { ag as ClientEventPrefix, ae as EventClient, ad as EventClientFuncParams, ai as EventServer, ah as EventServerFuncParams, a7 as EventToolFunc, a9 as SecondaryCache, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, aj as eventServer, ac as lrucache, a6 as registerCoreTools } from './index-BLW3R7VS.mjs';
|
|
2
2
|
export { LRUCache } from 'secondary-cache';
|
|
3
3
|
import 'events-ex';
|
|
4
4
|
import 'property-manager';
|
|
5
5
|
import 'custom-ability';
|
|
6
6
|
import '@isdk/common-error';
|
|
7
|
-
import 'http';
|
package/dist/funcs.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
export { ae as EventClient, ad as EventClientFuncParams,
|
|
1
|
+
export { ag as ClientEventPrefix, ae as EventClient, ad as EventClientFuncParams, ai as EventServer, ah as EventServerFuncParams, a7 as EventToolFunc, a9 as SecondaryCache, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, aj as eventServer, ac as lrucache, a6 as registerCoreTools } from './index-BLW3R7VS.js';
|
|
2
2
|
export { LRUCache } from 'secondary-cache';
|
|
3
3
|
import 'events-ex';
|
|
4
4
|
import 'property-manager';
|
|
5
5
|
import 'custom-ability';
|
|
6
6
|
import '@isdk/common-error';
|
|
7
|
-
import 'http';
|
package/dist/funcs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t,e=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,h=(t,e,n,h)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let a of r(e))o.call(t,a)||a===n||s(t,a,{get:()=>e[a],enumerable:!(h=i(e,a))||h.enumerable});return t},a=(t,i,r)=>(r=null!=t?e(n(t)):{},h(!i&&t&&t.__esModule?r:s(r,"default",{value:t,enumerable:!0}),t)),c={};((t,e)=>{for(var i in e)s(t,i,{get:e[i],enumerable:!0})})(c,{EventClient:()=>bt,EventServer:()=>Tt,EventToolFunc:()=>st,LRUCache:()=>nt.LRUCache,SecondaryCache:()=>ot,_lrucache:()=>ht,createLRUCache:()=>at,event:()=>it,eventClient:()=>mt,eventServer:()=>xt,lrucache:()=>ct,registerCoreTools:()=>jt}),module.exports=(t=c,h(s({},"__esModule",{value:!0}),t));var u=(()=>"undefined"==typeof document?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href)(),f=require("events-ex"),l=(require("lodash-es"),require("property-manager")),p=require("util-ex"),d=require("@isdk/common-error"),y=(require("custom-ability"),require("util-ex"),["get","post","put","delete","patch","list","res"]),b={action:{type:"string",assign:(t,e,s,i,r)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},m=(require("date-fns"),require("date-fns"),require("@isdk/template-engines"),require("@isdk/template-engines"));function v(t){return Object.keys(t).sort().map(e=>t[e])}var g=class extends m.StringTemplate{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof m.StringTemplate?t.examplePrompt:m.StringTemplate.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const s=await this.examplePrompt.format(t);e.push(s)}else if("string"==typeof t)e.push(t);else if(t){const s=v(t);s.length>0&&e.push(...s)}const s=[this.prefix,...e,this.suffix].join(this.exampleSeparator),i=this.templateFormat;return await m.StringTemplate.format({template:s,data:t,templateFormat:i})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};m.StringTemplate.register(g,{name:"fewshot",aliases:["few_shot"]});(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then(t=>{0});require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var w=require("custom-ability"),q=(require("events-ex"),"event"),k="event-bus";(0,w.createAbilityInjector)(function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(k)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.on(e,s)}once(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.once(e,s)}off(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.off(e,s)}emit(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,s):i.emit.call(this,e,this.name,...s)}emitError(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emit.call(this,"error",e,this.name,...s)}async emitAsync(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emitAsync.call(this,e,this.name,...s)}}},!0),require("eventsource-parser");require("uuid"),a(require("base32768")),require("uuid");var A=a(require("xxhashjs")),{h32:T,h64:x}=(a(require("base32768")),require("json-canonicalize"),require("hash-wasm"),A.default),j=(require("json-canonicalize"),a(require("base32768")),require("@isdk/util"),require("util-ex"),require("lodash-es"),require("util-ex"),require("lodash-es"),require("util-ex"),"[a-zA-Z_$][a-zA-Z_\\d$]*"),S=(new RegExp(`^\\s*(\\(\\s*\\)|${j}|\\(${`${j}\\s*(,\\s*${j})*`}\\))\\s*=>`),a(require("mime-type/with-db")),a(require("jschardet")),require("@isdk/util")),E=require("yaml-types");require("mime-type/with-db"),require("@isdk/util");(0,S.registerYamlTag)(E.regexp);var $=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}},C=require("util-ex"),F=require("events-ex");function R(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 P=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=R(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const s=this._front+e&this._capacity-1;return this[s]=t,++e<=this._capacity&&(this._length=e),s}unshift(t){let e=this._length;this.checkCapacity(++e);const s=this._capacity,i=(this._front-1&s-1^s)-s;return this[i]=t,this._front=i,e<=this._capacity&&(this._length=e),i}pop(t){let e=this._length;if(0===e)return;let s=this._front+e-1&this._capacity-1,i=this[s];for(;--e>0&&t&&null==i;)s--,i=this[s];return this[s]=void 0,this._length=e,i}shift(t){let e=this._length;if(0===e)return;let s=this._front,i=this[s];for(;--e>0&&t&&null==i;)s=s+1&this._capacity-1,i=this[s];return this[s]=void 0,this._front=s+1&this._capacity-1,this._length=e,i}get size(){return this._length}get(t){let e;if(t===(0|t)){const s=this._length;t<0&&(t+=s),t>=0&&t<s&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,s=this._capacity;for(let i=0;i<t;++i)this[e+i&s-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const s=this._front,i=this._capacity-1,r=s+t&i,n=this[r];if(t<e/2)this.copyWithin(s+1&i,s,s+t&i),this[s]=void 0,this._front=s+1&i;else{this.copyWithin(r,r+1&i,s+e&i);this[s+e-1&i]=void 0}return this._length=e-1,n}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(R(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const s=this._front,i=this._length;if(s+i>e){!function(t,e,s,i,r){for(let n=0;n<r;++n)s[n+i]=t[n+e],t[n+e]=void 0}(this,0,this,e,s+i&e-1)}}},O=require("@isdk/common-error"),M=32;function _(t){return"function"==typeof t}function z(){return"1"}var W,B=class{constructor(t={}){const{initFn:e=z,pauseFn:s,resumeFn:i,capacity:r=M}=t;if(_(s)!==_(i))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new P(r),this.emitter=new F.EventEmitter,this.useDefaultTokens=e===z,this.pauseFn=s,this.resumeFn=i,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,s=this.waiting.shift(!0);s?this._dispatchTask(s,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",t=>{this.onReleased(t)})}_newReleaser(t){let e=!1;const s=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(s,t),s}_dispatchTask(t,e){const{resolve:s}=t;s(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,s=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const s=this.waiting.push(t),i=t.reject;return e&&e.addEventListener("abort",()=>{this.waiting[s]=void 0;const t=e.reason instanceof Error?e.reason:new O.AbortError(e.reason||"aborted");e.alreadyRejected=!0,i(t)}),s};let i=this.tryAcquire(t);const r=i&&(0,C.isAsync)(i),n=e=>new Promise((i,r)=>{const n={...t,resolve:i,reject:r,token:e};void 0===e?s(n):this._dispatchTask(n,{...t,token:e})});return r?i.then(t=>n(t)):n(i)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new O.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},U=class extends B{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 P(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,C.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)}},I=(require("@isdk/common-error"),require("custom-ability")),L=require("util-ex"),N=((W=N||{})[W.MultiTask=1]="MultiTask",W[W.Cancelable=2]="Cancelable",W[W.Priority=4]="Priority",W),J=class extends AbortController{constructor(t){super(),(0,L.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new d.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 d.AbortError(e.reason||"aborted")}}},Z=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,s=this.__task_semaphore;return e>0&&!s&&(t&&(t=t.bind(this)),s=this.__task_semaphore=new U(e-1,{isReadyFn:t})),s}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures;return e._asyncFeatures&&(s|=e._asyncFeatures),$.has(s,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),$.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new d.CommonError("Missing taskId",this.name+".isAborted",d.ErrorCode.InvalidArgument);s=s[t]}return!s||s.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new d.CommonError("Missing taskId",this.name+".getRunningTask",d.ErrorCode.InvalidArgument);s=s[t]}return s?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,s=void 0),s}getRunningTaskCount(){let t;if(this.hasAsyncFeature(0)){const e=this.__task_aborter;t=e&&Object.entries(e).filter(([t,s])=>{if(!s?.signal.aborted)return!0;e[t]=void 0}).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const s=this.super,i=this.self||this;return t=s?s.call(i,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,s=!0){const i=this.hasAsyncFeature(0);if(!i&&s&&this.getRunningTask())throw new d.CommonError("The task is running",this.name,d.ErrorCode.TooManyRequests);const r=t?.aborter||new J(this);if(!(r instanceof J)){if(!(r instanceof AbortController))throw new d.CommonError("aborter should be an AbortController",this.name,d.ErrorCode.InvalidArgument);Object.setPrototypeOf(r,new J(this))}if(i){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),r.id=e,t[e]=r}else this.__task_aborter=r;const n=[...D(t?.signal),...D(t?.signals)];n.length&&function(t,e){if(!e.length)return;const s=[],i=()=>{for(const t of s)try{t()}catch{}s.length=0},r=e.find(t=>t.aborted);if(r){const e=r.reason;try{t.abort(e||"aborted")}catch{}return}for(const i of e){const e=()=>{const e=i.reason;try{t.abort(e||"aborted")}catch(t){console.log(t)}};i.addEventListener("abort",e,{once:!0}),s.push(()=>i.removeEventListener("abort",e))}const n=()=>i();t.signal.addEventListener("abort",n,{once:!0}),s.push(()=>t.signal.removeEventListener("abort",n))}(r,n);const o=t?.timeout;return o>0&&(r.timeoutId=setTimeout(()=>{r.timeoutId=void 0,this.abort("timeout",{timeout:o})},o)),r.signal.addEventListener("abort",()=>{const t=r.timeoutId;t&&(r.timeoutId=void 0,clearTimeout(t));const e=r.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{try{r.streamController?.error?.(e.reason)}catch{}}}),r}$cleanMultiTaskAborter(t,e){const s=this.super,i=this.self||this;s?s.call(i,t,e):i._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(0)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,s){const i=this.createAborter(e,s?.taskId,s?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=i);let r=t(e,i).then(t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(i)},s=function(t){const e=t||{};return new TransformStream({async start(t){const s=t.error;if(t.error=i=>{s.call(t,i),e.onError&&e.onError(i)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,s){try{let i;e.onTransform&&(i=await e.onTransform(t,s)),i||(i=t),s.enqueue(i)}catch(t){s.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,L.defineProperty)(i,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=i.id),t)});t=t.pipeThrough(s)}else this.cleanTaskAborter(i);return t}).catch(t=>{throw this.cleanTaskAborter(i),t}).finally(()=>{i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=void 0)});return r.task=i,r}runAsyncCancelableTask(t={},e,s){let i=this.createTaskPromise(e,t,s);const r=this.getSemaphore(s?.isReadyFn);if(r){const t=i,e=t.task;i=r.acquire({signal:e.signal}).then(()=>t).finally(()=>{r.release()}),i.task=e}return i}abort(t,e){let s=this.__task_aborter;if(s){const i=s;if(this.hasAsyncFeature(0)){const t=e?.taskId;if(null==t)throw new d.CommonError("Missing data.taskId",this.name+".abort",d.ErrorCode.InvalidArgument);s=s[t],this.cleanMultiTaskAborter(t,i)}else this.__task_aborter=void 0;s&&!s.signal.aborted&&s.abort(t,e)}}};function D(t){return t?Array.isArray(t)?t.filter(Boolean):[t]:[]}Z.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Z.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,I.createAbilityInjector)(Z,"abort",{afterInjection:function(t,e){let s=t.prototype._asyncFeatures||0;s|=N.Cancelable,e&&(e.asyncFeatures&&(s|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=s}}),a(require("memoizee")),require("json-canonicalize");var G=a(require("path")),H=require("package-directory");require("util-ex");var K=a(require("path")),Q=require("url"),V=(require("@huggingface/transformers"),(0,Q.fileURLToPath)(u)),X=K.default.dirname(V),{exit:Y}=(K.default.join(function(t){const e=(0,H.packageDirectorySync)({cwd:t});if(e)return e;const s=t.split(G.default.sep);let i=s.lastIndexOf("dist");if(i>0)return s.slice(0,i).join(G.default.sep);if(i=s.lastIndexOf("src"),i>0)return s.slice(0,i).join(G.default.sep);throw new Error("can not find package directory")}(X),".cache"),require("yaml"),require("lodash-es"),process);require("lodash-es"),Symbol("MergeWay");var tt=class t extends l.AdvancePropertyManager{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const s in this.list()){const i=this.get(s);let r=i.tags;if("string"==typeof r){if(r===t){e=i;break}}else if(Array.isArray(r)&&r.indexOf(t)>=0){e=i;break}}return e}static getAllByTag(t){let e=[];for(const s in this.list()){const i=this.get(s);let r=i.tags;"string"==typeof r?r===t&&e.push(i):Array.isArray(r)&&r.indexOf(t)>=0&&e.push(i)}return e}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures??0;return e._asyncFeatures&&(s|=e._asyncFeatures),$.has(s,t)}static run(t,e){const s=this.get(t);if(s)return s.run(e);throw new d.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const s=this.get(t);if(s)return s.runSync(e);throw new d.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const s=this.get(t);if(s)return s.runWithPos(...e);throw new d.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const s=this.get(t);if(s)return s.runWithPosSync(...e);throw new d.NotFoundError(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,s={}){switch(typeof e){case"string":s.name=e;break;case"function":s.func=e;break;case"object":s=e}e=s.name;let i=!!this.get(e);if(i)i=!1;else{if(!(s instanceof t))return i=new this(s),i.register();if(this.items[e]=s,s.alias){const t=s.alias;if("string"==typeof t)this.aliases[t]&&(0,d.throwError)(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const s of t)this.aliases[s]&&(0,d.throwError)(`Alias ${s} already exists for ${e}`),this.aliases[s]=e}i=s}return i}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,s=this.depends;if(s){const e=Object.keys(s);for(const i of e){const e=s[i];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},s=Object.keys(this.params);let i=Math.min(s.length,t.length);for(let r=0;r<i;r++)e[s[r]]=t[r];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const s=Object.keys(t);let i=Math.min(s.length,this.params.length);for(let r=0;r<i;r++)e.push(t[s[r]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,d.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??0;return this._asyncFeatures&&(e|=this._asyncFeatures),$.has(e,t)}isStream(t){let e=this.stream;if(e){const s=this.params;s?.stream&&(e=t?.stream)}return e}},et={name:{type:"string"},description:{type:"string"},title:{type:"string"},func:{type:"function",assign(t,e,s,i,r){let n=t;const o=typeof t;return r.isExported?n="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),n=(0,p._createFunction)(t,e.scope)),n}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"},alias:{type:["array","string"]}};tt.defineProperties(tt,et);Symbol("meta");var st=class extends tt{constructor(){super(...arguments),this._emitter=new f.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},it=new st(k),rt=require("secondary-cache"),nt=require("secondary-cache"),ot=rt.Cache;function ht({key:t,value:e,options:s}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,s):this.cache.get(t):(s&&this.cache.setDefaultOptions(s),this.cache)}function at(t,e){let s=tt.get(t);return s||(s=new tt(t,{func:ht,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),s.cache=new rt.Cache(e)),s}var ct=at("lrucache"),ut="A client transport has not been set. Use ClientTools.setTransport() or transport.mount(ClientTools) first.",ft=class t extends tt{static get apiRoot(){return this._transport||(0,d.throwError)(ut,"ClientTools"),this._transport.apiRoot}static setTransport(t){if(t){this._transport=t;const e=this.constructor;t.Tools!==e&&(t.Tools=e)}}static get transport(){return this._transport}static async loadFrom(t){return t||(this._transport||(0,d.throwError)(ut,"ClientTools"),t=await this._transport.loadApis()),t&&this.loadFromSync(t),t}static loadFromSync(e){for(const s in e){const i=this.get(s),r=e[s];i?i instanceof t?i.assign(r):(0,d.throwError)(`${s} already registered as ${i.constructor.name}`,"ClientTools"):this.register(r)}}static async fetch(t,e,...s){const i=this.get(t);if(i&&i.fetch)return i.fetch(e,...s)}get apiRoot(){return this.constructor.apiRoot}async fetch(t,e,s){const i=this.constructor;if(i._transport)return i._transport.fetch(this.name,t,e,s,this.fetchOptions);(0,d.throwError)(ut,"ClientTools")}async func(t){return await this.fetch(t)}},lt={...b};ft.defineProperties(ft,lt);var pt=class extends ft{async fetch(t,e,s){return t||(t={}),e?.startsWith("$")&&(t.act=e,e="post"),await super.fetch(t,e,s)}async _func(t,e){return await this.fetch(e,t)}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))}}},dt={methods:{type:"array",assign(t,e,s,i,r){r?.isExported||e.assignMethods(t)}}};pt.defineProperties(pt,dt);var yt=class extends pt{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let s=t.id;return s||(0,d.throwError)("id is required"),"string"==typeof s&&(s=encodeURIComponent(s)),delete t.id,super.fetch(t,e,s)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},bt=class extends yt{constructor(){super(...arguments),this._sseListeners={},this._forwardEvents=new Set,this.description="subscribe server event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){if(!this._pubSubTransport)throw new Error("EventClient pubSubTransport not set");return this._pubSubTransport}get evtSource(){let t=this._stream;return t&&2!==t.readyState||(t=this.initEventStream(this._streamEvents)),t}get active(){return!!this._stream&&2!==this._stream.readyState}set active(t){t!==this.active&&(t?this.initEventStream(this._streamEvents):this._stream&&this.close())}initEventStream(t){const e="string"==typeof t?[t]:t;if(this._stream&&2!==this._stream.readyState){if(!this._streamEvents||e&&e.every(t=>this._streamEvents.includes(t)))return this._stream;this._stream.close()}const s=e?function(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}({event:e}):"",i=`${this.apiRoot}/${this.name}${s}`,r=this._stream=this.constructor.pubSubTransport.connect(i);return Object.entries(this._sseListeners).forEach(([t,e])=>{r.on(t,e)}),this._streamEvents=e,r}esListener(t,e,s){if(!this._forwardEvents.has(t)){const s=this.emitter;s&&t&&(Array.isArray(e)?s.emit(t,...e):s.emit(t,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const s=this.evtSource;for(const e of t)if(!this._sseListeners[e]){const t=this._sseListeners[e]=(t,s)=>this.esListener(e,t,s);s.on(e,t)}return e}async unsubscribe(t){"string"==typeof t&&(t=[t]);const e=await this.unsub({event:t}),s=this.evtSource;for(const e of t){const t=this._sseListeners[e];t&&(delete this._sseListeners[e],s.off(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.initEventStream(t),t)return await this.subscribe(t)}close(){const t=this._stream;if(t)return this._stream=void 0,t.close()}},mt=new bt(q),vt=require("util-ex"),gt=class t extends tt{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const s in this.items){let i=this.items[s];(i instanceof t||i.isApi)&&(i.allowExportFunc||(i=i.toJSON(),delete i.func),e[s]=i)}return e}run(t,e){return e&&(t._req=e.req,t._res=e.reply),super.run(t)}func(t){}},wt={...b};gt.defineProperties(gt,wt);var qt=class extends gt{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const s=this.methods=[];this.initRpcMethods(s)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const s of e)"function"==typeof this[s]&&t.push(s);(0,vt.getAllNames)(Object.getPrototypeOf(this)).filter(t=>t.startsWith("$")&&"function"==typeof this[t]).forEach(e=>{t.push(e);const s=e.slice(1);void 0===this[s]&&(this[s]=this[e])})}cast(t,e){let s=this.params[t];return s&&("string"!=typeof s&&(s=s.type),"number"===s&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new d.NotFoundError(e,this.name)}};qt.defineProperties(qt,{methods:{type:"array"}});var kt=class extends qt{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=y}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},At=it.runSync(),Tt=class t extends kt{constructor(){super(...arguments),this.description="subscribe server event",this.result="event",this.depends={[k]:it}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){return this._pubSubTransport||console.warn("EventServer pubSubTransport not set"),this._pubSubTransport}get pubSubTransport(){return this.constructor.pubSubTransport}static publish(t,e,s){return this.pubSubTransport?.publish(e,t,s)}static ebListener(t,...e){this.pubSubTransport?.publish(t,e)}static subscribe(t,e,s,i){return this.pubSubTransport?.subscribe(s,{...i,req:t,res:e})}static alreadyForward(t){const e=At.listeners(t);for(const t of e)if(t===this._boundEbListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,s){return"string"==typeof s&&(s=[s]),this.constructor.subscribe(t,e,s)}forward(e){Array.isArray(e)||(e=[e]);const s=this.constructor;s._boundEbListener||(s._boundEbListener=function(...t){return s.ebListener(this.type,...t)});for(const i of e)t.alreadyForward(i)||At.on(i,s._boundEbListener)}unforward(t){"string"==typeof t&&(t=[t]);const e=this.constructor;if(e._boundEbListener)for(const s of t)At.off(s,e._boundEbListener)}list({_req:t,_res:e,event:s}){t&&e&&this.subscribeSSE(t,e,s)}$sub({event:t}){if(t)return this.forward(t),{event:t};(0,d.throwError)("event is required","sub",d.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,d.throwError)("event is required","unsub",d.ErrorCode.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const s of t)this.publishSSE(e,s);return{event:t}}(0,d.throwError)("event or data is required","pub",d.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},xt=new Tt(q);function jt(){it.register(),ct.register()}
|
|
1
|
+
"use strict";var t,e=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,h=(t,e,n,h)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let a of r(e))o.call(t,a)||a===n||s(t,a,{get:()=>e[a],enumerable:!(h=i(e,a))||h.enumerable});return t},a=(t,i,r)=>(r=null!=t?e(n(t)):{},h(!i&&t&&t.__esModule?r:s(r,"default",{value:t,enumerable:!0}),t)),c={};((t,e)=>{for(var i in e)s(t,i,{get:e[i],enumerable:!0})})(c,{ClientEventPrefix:()=>jt,EventClient:()=>mt,EventServer:()=>St,EventToolFunc:()=>st,LRUCache:()=>nt.LRUCache,SecondaryCache:()=>ot,_lrucache:()=>ht,createLRUCache:()=>at,event:()=>it,eventClient:()=>wt,eventServer:()=>Et,lrucache:()=>ct,registerCoreTools:()=>$t}),module.exports=(t=c,h(s({},"__esModule",{value:!0}),t));var u=(()=>"undefined"==typeof document?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href)(),l=require("events-ex"),f=(require("lodash-es"),require("property-manager")),d=require("util-ex"),p=require("@isdk/common-error"),y=(require("custom-ability"),require("util-ex"),["get","post","put","delete","patch","list","res"]),b={action:{type:"string",assign:(t,e,s,i,r)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},v=(require("date-fns"),require("date-fns"),require("@isdk/template-engines"),require("@isdk/template-engines"));function m(t){return Object.keys(t).sort().map(e=>t[e])}var w=class extends v.StringTemplate{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof v.StringTemplate?t.examplePrompt:v.StringTemplate.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const s=await this.examplePrompt.format(t);e.push(s)}else if("string"==typeof t)e.push(t);else if(t){const s=m(t);s.length>0&&e.push(...s)}const s=[this.prefix,...e,this.suffix].join(this.exampleSeparator),i=this.templateFormat;return await v.StringTemplate.format({template:s,data:t,templateFormat:i})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};v.StringTemplate.register(w,{name:"fewshot",aliases:["few_shot"]});(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then(t=>{0});require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var g=require("custom-ability"),q=(require("events-ex"),"event"),k="event-bus";(0,g.createAbilityInjector)(function(t,e){const s=e?.eventBusName||k;return class{static get emitter(){if(!this._emitter){const t=this.get(s)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.on(e,s)}once(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.once(e,s)}off(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.off(e,s)}emit(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,s):i.emit.call(this,e,this.name,...s)}emitError(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emit.call(this,"error",e,this.name,...s)}async emitAsync(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emitAsync.call(this,e,this.name,...s)}}},!0),require("nanoid"),require("uuid"),a(require("base32768")),require("uuid");var A=a(require("xxhashjs")),{h32:T,h64:x}=(a(require("base32768")),require("json-canonicalize"),require("hash-wasm"),A.default);require("json-canonicalize"),a(require("base32768")),require("eventsource-parser");require("@isdk/util"),require("util-ex"),require("lodash-es"),require("util-ex"),require("lodash-es"),require("util-ex");var j="[a-zA-Z_$][a-zA-Z_\\d$]*",S=(new RegExp(`^\\s*(\\(\\s*\\)|${j}|\\(${`${j}\\s*(,\\s*${j})*`}\\))\\s*=>`),a(require("mime-type/with-db")),a(require("jschardet")),require("@isdk/util")),E=require("yaml-types");require("mime-type/with-db"),require("@isdk/util");(0,S.registerYamlTag)(E.regexp);var $=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}},C=require("util-ex"),P=require("events-ex");function F(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 R=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=F(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const s=this._front+e&this._capacity-1;return this[s]=t,++e<=this._capacity&&(this._length=e),s}unshift(t){let e=this._length;this.checkCapacity(++e);const s=this._capacity,i=(this._front-1&s-1^s)-s;return this[i]=t,this._front=i,e<=this._capacity&&(this._length=e),i}pop(t){let e=this._length;if(0===e)return;let s=this._front+e-1&this._capacity-1,i=this[s];for(;--e>0&&t&&null==i;)s--,i=this[s];return this[s]=void 0,this._length=e,i}shift(t){let e=this._length;if(0===e)return;let s=this._front,i=this[s];for(;--e>0&&t&&null==i;)s=s+1&this._capacity-1,i=this[s];return this[s]=void 0,this._front=s+1&this._capacity-1,this._length=e,i}get size(){return this._length}get(t){let e;if(t===(0|t)){const s=this._length;t<0&&(t+=s),t>=0&&t<s&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,s=this._capacity;for(let i=0;i<t;++i)this[e+i&s-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const s=this._front,i=this._capacity-1,r=s+t&i,n=this[r];if(t<e/2)this.copyWithin(s+1&i,s,s+t&i),this[s]=void 0,this._front=s+1&i;else{this.copyWithin(r,r+1&i,s+e&i);this[s+e-1&i]=void 0}return this._length=e-1,n}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(F(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const s=this._front,i=this._length;if(s+i>e){!function(t,e,s,i,r){for(let n=0;n<r;++n)s[n+i]=t[n+e],t[n+e]=void 0}(this,0,this,e,s+i&e-1)}}},O=require("@isdk/common-error"),_=32;function M(t){return"function"==typeof t}function I(){return"1"}var z,W=class{constructor(t={}){const{initFn:e=I,pauseFn:s,resumeFn:i,capacity:r=_}=t;if(M(s)!==M(i))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new R(r),this.emitter=new P.EventEmitter,this.useDefaultTokens=e===I,this.pauseFn=s,this.resumeFn=i,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,s=this.waiting.shift(!0);s?this._dispatchTask(s,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",t=>{this.onReleased(t)})}_newReleaser(t){let e=!1;const s=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(s,t),s}_dispatchTask(t,e){const{resolve:s}=t;s(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,s=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const s=this.waiting.push(t),i=t.reject;return e&&e.addEventListener("abort",()=>{this.waiting[s]=void 0;const t=e.reason instanceof Error?e.reason:new O.AbortError(e.reason||"aborted");e.alreadyRejected=!0,i(t)}),s};let i=this.tryAcquire(t);const r=i&&(0,C.isAsync)(i),n=e=>new Promise((i,r)=>{const n={...t,resolve:i,reject:r,token:e};void 0===e?s(n):this._dispatchTask(n,{...t,token:e})});return r?i.then(t=>n(t)):n(i)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new O.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},B=class extends W{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 R(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,C.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)}},U=(require("@isdk/common-error"),require("custom-ability")),L=require("util-ex"),N=((z=N||{})[z.MultiTask=1]="MultiTask",z[z.Cancelable=2]="Cancelable",z[z.Priority=4]="Priority",z),Z=class extends AbortController{constructor(t){super(),(0,L.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new p.AbortError(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new p.AbortError(e.reason||"aborted")}}},J=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,s=this.__task_semaphore;return e>0&&!s&&(t&&(t=t.bind(this)),s=this.__task_semaphore=new B(e-1,{isReadyFn:t})),s}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures;return e._asyncFeatures&&(s|=e._asyncFeatures),$.has(s,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),$.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".isAborted",p.ErrorCode.InvalidArgument);s=s[t]}return!s||s.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".getRunningTask",p.ErrorCode.InvalidArgument);s=s[t]}return s?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,s=void 0),s}getRunningTaskCount(){let t;if(this.hasAsyncFeature(0)){const e=this.__task_aborter;t=e&&Object.entries(e).filter(([t,s])=>{if(!s?.signal.aborted)return!0;e[t]=void 0}).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const s=this.super,i=this.self||this;return t=s?s.call(i,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,s=!0){const i=this.hasAsyncFeature(0);if(!i&&s&&this.getRunningTask())throw new p.CommonError("The task is running",this.name,p.ErrorCode.TooManyRequests);const r=t?.aborter||new Z(this);if(!(r instanceof Z)){if(!(r instanceof AbortController))throw new p.CommonError("aborter should be an AbortController",this.name,p.ErrorCode.InvalidArgument);Object.setPrototypeOf(r,new Z(this))}if(i){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),r.id=e,t[e]=r}else this.__task_aborter=r;const n=[...D(t?.signal),...D(t?.signals)];n.length&&function(t,e){if(!e.length)return;const s=[],i=()=>{for(const t of s)try{t()}catch{}s.length=0},r=e.find(t=>t.aborted);if(r){const e=r.reason;try{t.abort(e||"aborted")}catch{}return}for(const i of e){const e=()=>{const e=i.reason;try{t.abort(e||"aborted")}catch(t){console.log(t)}};i.addEventListener("abort",e,{once:!0}),s.push(()=>i.removeEventListener("abort",e))}const n=()=>i();t.signal.addEventListener("abort",n,{once:!0}),s.push(()=>t.signal.removeEventListener("abort",n))}(r,n);const o=t?.timeout;return o>0&&(r.timeoutId=setTimeout(()=>{r.timeoutId=void 0,this.abort("timeout",{timeout:o})},o)),r.signal.addEventListener("abort",()=>{const t=r.timeoutId;t&&(r.timeoutId=void 0,clearTimeout(t));const e=r.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{try{r.streamController?.error?.(e.reason)}catch{}}}),r}$cleanMultiTaskAborter(t,e){const s=this.super,i=this.self||this;s?s.call(i,t,e):i._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(0)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,s){const i=this.createAborter(e,s?.taskId,s?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=i);let r=t(e,i).then(t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(i)},s=function(t){const e=t||{};return new TransformStream({async start(t){const s=t.error;if(t.error=i=>{s.call(t,i),e.onError&&e.onError(i)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,s){try{let i;e.onTransform&&(i=await e.onTransform(t,s)),i||(i=t),s.enqueue(i)}catch(t){s.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,L.defineProperty)(i,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=i.id),t)});t=t.pipeThrough(s)}else this.cleanTaskAborter(i);return t}).catch(t=>{throw this.cleanTaskAborter(i),t}).finally(()=>{i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=void 0)});return r.task=i,r}runAsyncCancelableTask(t={},e,s){let i=this.createTaskPromise(e,t,s);const r=this.getSemaphore(s?.isReadyFn);if(r){const t=i,e=t.task;i=r.acquire({signal:e.signal}).then(()=>t).finally(()=>{r.release()}),i.task=e}return i}abort(t,e){let s=this.__task_aborter;if(s){const i=s;if(this.hasAsyncFeature(0)){const t=e?.taskId;if(null==t)throw new p.CommonError("Missing data.taskId",this.name+".abort",p.ErrorCode.InvalidArgument);s=s[t],this.cleanMultiTaskAborter(t,i)}else this.__task_aborter=void 0;s&&!s.signal.aborted&&s.abort(t,e)}}};function D(t){return t?Array.isArray(t)?t.filter(Boolean):[t]:[]}J.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},J.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,U.createAbilityInjector)(J,"abort",{afterInjection:function(t,e){let s=t.prototype._asyncFeatures||0;s|=N.Cancelable,e&&(e.asyncFeatures&&(s|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=s}}),a(require("memoizee")),require("json-canonicalize");var G=a(require("path")),H=require("package-directory");require("util-ex");var K=a(require("path")),Q=require("url"),V=(require("@huggingface/transformers"),(0,Q.fileURLToPath)(u)),X=K.default.dirname(V),{exit:Y}=(K.default.join(function(t){const e=(0,H.packageDirectorySync)({cwd:t});if(e)return e;const s=t.split(G.default.sep);let i=s.lastIndexOf("dist");if(i>0)return s.slice(0,i).join(G.default.sep);if(i=s.lastIndexOf("src"),i>0)return s.slice(0,i).join(G.default.sep);throw new Error("can not find package directory")}(X),".cache"),require("yaml"),require("lodash-es"),process),tt=(require("lodash-es"),Symbol("MergeWay"),class t extends f.AdvancePropertyManager{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const s in this.list()){const i=this.get(s);let r=i.tags;if("string"==typeof r){if(r===t){e=i;break}}else if(Array.isArray(r)&&r.indexOf(t)>=0){e=i;break}}return e}static getAllByTag(t){let e=[];for(const s in this.list()){const i=this.get(s);let r=i.tags;"string"==typeof r?r===t&&e.push(i):Array.isArray(r)&&r.indexOf(t)>=0&&e.push(i)}return e}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures??0;return e._asyncFeatures&&(s|=e._asyncFeatures),$.has(s,t)}static run(t,e){const s=this.get(t);if(s)return s.run(e);throw new p.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const s=this.get(t);if(s)return s.runSync(e);throw new p.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const s=this.get(t);if(s)return s.runWithPos(...e);throw new p.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const s=this.get(t);if(s)return s.runWithPosSync(...e);throw new p.NotFoundError(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,s={}){switch(typeof e){case"string":s.name=e;break;case"function":s.func=e;break;case"object":s=e}e=s.name;let i=!!this.get(e);if(i)i=!1;else{if(!(s instanceof t))return i=new this(s),i.register();if(this.items[e]=s,s.alias){const t=s.alias;if("string"==typeof t)this.aliases[t]&&(0,p.throwError)(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const s of t)this.aliases[s]&&(0,p.throwError)(`Alias ${s} already exists for ${e}`),this.aliases[s]=e}i=s}return i}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,s=this.depends;if(s){const e=Object.keys(s);for(const i of e){const e=s[i];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},s=Object.keys(this.params);let i=Math.min(s.length,t.length);for(let r=0;r<i;r++)e[s[r]]=t[r];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const s=Object.keys(t);let i=Math.min(s.length,this.params.length);for(let r=0;r<i;r++)e.push(t[s[r]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,p.throwError)("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures??0;return this._asyncFeatures&&(e|=this._asyncFeatures),$.has(e,t)}isStream(t){let e=this.stream;if(e){const s=this.params;s?.stream&&(e=t?.stream)}return e}}),et={name:{type:"string"},description:{type:"string"},title:{type:"string"},func:{type:"function",assign(t,e,s,i,r){let n=t;const o=typeof t;return r.isExported?n="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),n=(0,d._createFunction)(t,e.scope)),n}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"},alias:{type:["array","string"]}};tt.defineProperties(tt,et);Symbol("meta");var st=class extends tt{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}},it=new st(k),rt=require("secondary-cache"),nt=require("secondary-cache"),ot=rt.Cache;function ht({key:t,value:e,options:s}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,s):this.cache.get(t):(s&&this.cache.setDefaultOptions(s),this.cache)}function at(t,e){let s=tt.get(t);return s||(s=new tt(t,{func:ht,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),s.cache=new rt.Cache(e)),s}var ct=at("lrucache"),ut=require("lodash-es"),lt="A client transport has not been set. Use ClientTools.setTransport() or transport.mount(ClientTools) first.",ft=class t extends tt{static get apiRoot(){return this._transport||(0,p.throwError)(lt,"ClientTools"),this._transport.apiRoot}static setTransport(t){if(t){this._transport=t;const e=this.constructor;t.Tools!==e&&(t.Tools=e)}}static get transport(){return this._transport}static async loadFrom(t){return t||(this._transport||(0,p.throwError)(lt,"ClientTools"),t=await this._transport.loadApis()),t&&this.loadFromSync(t),t}static loadFromSync(e){for(const s in e){const i=this.get(s),r=e[s];i?i instanceof t?i.assign(r):(0,p.throwError)(`${s} already registered as ${i.constructor.name}`,"ClientTools"):this.register(r)}}static async fetch(t,e,...s){const i=this.get(t);if(i&&i.fetch)return i.fetch(e,...s)}get apiRoot(){return this.constructor.apiRoot}async fetch(t,e,s,i){const r=this.constructor;if(r._transport)return i=(0,ut.defaultsDeep)(i,this.fetchOptions),r._transport.fetch(this.name,t,e,s,i);(0,p.throwError)(lt,"ClientTools")}async func(t){return await this.fetch(t)}},dt={...b};ft.defineProperties(ft,dt);var pt=class extends ft{async fetch(t,e,s,i){return t||(t={}),e?.startsWith("$")&&(t.act=e,e="post"),await super.fetch(t,e,s,i)}async _func(t,e,s){return await this.fetch(e,t,null,s)}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))}}},yt={methods:{type:"array",assign(t,e,s,i,r){r?.isExported||e.assignMethods(t)}}};pt.defineProperties(pt,yt);var bt=class extends pt{async fetch(t,e,...s){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let s=t.id;return s||(0,p.throwError)("id is required"),"string"==typeof s&&(s=encodeURIComponent(s)),delete t.id,super.fetch(t,e,s)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e,...s)}},vt=require("lodash-es"),mt=class extends bt{constructor(){super(...arguments),this._sseListeners={},this._forwardEvents=new Set,this.description="subscribe server event",this.ebListener=async function(...t){const e=t[0];let s=t[1];const i=this.type;("string"!=typeof e||s&&"object"!=typeof s||t.length>2)&&(s=t,e&&e===this.target.name&&(s=t.slice(1))),this.target.publish&&await this.target.publish({data:s,event:i})}}static setPubSubTransport(t){t?.setApiRoot&&this.apiRoot&&t.setApiRoot(this.apiRoot),this._pubSubTransport=t}static get pubSubTransport(){if(!this._pubSubTransport)throw new Error("EventClient pubSubTransport not set");return this._pubSubTransport}get clientId(){return this._stream?.clientId}async getEvtSource(){let t=this._stream;return t&&2!==t.readyState||(t=await this.initEventStream(this._streamEvents)),t}get active(){return!!this._stream&&2!==this._stream.readyState}async setActive(t){t!==this.active&&(t?await this.initEventStream(this._streamEvents):this._stream&&this.close())}async initEventStream(t){const e="string"==typeof t?[t]:t;if(this._stream&&2!==this._stream.readyState){if(!this._streamEvents||e&&e.every(t=>this._streamEvents.includes(t)))return this._stream;this._stream.close()}const s=e?{event:e}:void 0,i=this._stream=await this.constructor.pubSubTransport.connect(this.name,s);return i.clientId&&(this.fetchOptions=(0,vt.defaultsDeep)({clientId:i.clientId},this.fetchOptions)),Object.entries(this._sseListeners).forEach(([t,e])=>{i.on(t,e)}),this._streamEvents=e,i}esListener(t,e,s){if(!this._forwardEvents.has(t)){const s=this.emitter;s&&t&&(Array.isArray(e)?s.emit(t,...e):s.emit(t,e))}}async subscribe(t){this.active||await this.initEventStream(t);const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const s=await this.getEvtSource();for(const e of t)if(!this._sseListeners[e]){const t=this._sseListeners[e]=(t,s)=>this.esListener(e,t,s);s.on(e,t)}return e}async unsubscribe(t){"string"==typeof t&&(t=[t]);const e=await this.unsub({event:t}),s=await this.getEvtSource();for(const e of t){const t=this._sseListeners[e];t&&(delete this._sseListeners[e],s.off(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.setActive(!1),await this.initEventStream(t),t)return await this.subscribe(t)}close(){const t=this._stream;if(t)return this._stream=void 0,t.close()}},wt=new mt(q),gt=require("util-ex"),qt=class t extends tt{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const s in this.items){let i=this.items[s];(i instanceof t||i.isApi)&&(i.allowExportFunc||(i=i.toJSON(),delete i.func),e[s]=i)}return e}run(t,e){return e&&(t._req=e.req,t._res=e.reply),super.run(t)}func(t){}},kt={...b};qt.defineProperties(qt,kt);var At=class extends qt{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const s=this.methods=[];this.initRpcMethods(s)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const s of e)"function"==typeof this[s]&&t.push(s);(0,gt.getAllNames)(Object.getPrototypeOf(this)).filter(t=>t.startsWith("$")&&"function"==typeof this[t]).forEach(e=>{t.push(e);const s=e.slice(1);void 0===this[s]&&(this[s]=this[e])})}cast(t,e){let s=this.params[t];return s&&("string"!=typeof s&&(s=s.type),"number"===s&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new p.NotFoundError(e,this.name)}};At.defineProperties(At,{methods:{type:"array"}});var Tt=class extends At{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=y}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id?e="list":t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},xt=it.runSync(),jt="client:",St=class t extends Tt{constructor(){super(...arguments),this.description="subscribe server event",this.result="event",this.depends={[k]:it}}static{this.autoInjectToLocalBus=!1}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){return this._pubSubTransport||console.warn("EventServer pubSubTransport not set"),this._pubSubTransport}get pubSubTransport(){return this.constructor.pubSubTransport}static publish(t,e,s){return this.pubSubTransport?.publish(t,e,s)}static ebListener(t,...e){this.pubSubTransport?.publish(t,e)}static alreadyForward(t){const e=xt.listeners(t);for(const t of e)if(t===this._boundEbListener)return!0}publishServerEvent(t,e){return this.constructor.publish(t,e)}forward(e){Array.isArray(e)||(e=[e]);const s=this.constructor;s._boundEbListener||(s._boundEbListener=function(...t){return s.ebListener(this.type,...t)});for(const i of e)t.alreadyForward(i)||xt.on(i,s._boundEbListener)}unforward(t){"string"==typeof t&&(t=[t]);const e=this.constructor;if(e._boundEbListener)for(const s of t)xt.off(s,e._boundEbListener)}list({_req:t,_res:e,event:s}){if(this.pubSubTransport)return this.pubSubTransport.connect({req:t,res:e,events:s});(0,p.throwError)("PubSub transport not available","list",p.ErrorCode.NotImplemented)}$sub({event:t,_req:e}){if(this.pubSubTransport||(0,p.throwError)("PubSub transport not available","sub",p.ErrorCode.NotImplemented),t){this.forward(t);const s=e&&this.pubSubTransport.getSessionFromReq?.(e);return s?(this.pubSubTransport.subscribe(s,Array.isArray(t)?t:[t]),{forward:!0,subscribed:!0,event:t,clientId:s.clientId}):(this.pubSubTransport.getSessionFromReq?console.warn("$sub: No session found for request"):e?console.warn(`$sub: The ${this.pubSubTransport.name} Transport does not support dynamic subscription`):console.warn("$sub: missing _req"),{forward:!0,event:t})}(0,p.throwError)("event is required","sub",p.ErrorCode.InvalidArgument)}$unsub({event:t,_req:e}){if(this.pubSubTransport||(0,p.throwError)("PubSub transport not available","unsub",p.ErrorCode.NotImplemented),t){this.unforward(t);const s=e&&this.pubSubTransport.getSessionFromReq?.(e);return s?(this.pubSubTransport.unsubscribe(s,Array.isArray(t)?t:[t]),{forward:!1,subscribed:!1,event:t,clientId:s.clientId}):(this.pubSubTransport.getSessionFromReq?console.warn("$unsub: No session found for request"):e?console.warn(`$unsub: The ${this.pubSubTransport.name} Transport does not support dynamic subscription`):console.warn("$sub: missing _req"),{forward:!1,event:t})}(0,p.throwError)("event is required","unsub",p.ErrorCode.InvalidArgument)}$publish({event:t,data:e,_req:s}){if(t&&e){const i=s&&this.pubSubTransport?.getSessionFromReq?.(s),r=i?.clientId,n=this.constructor;"string"==typeof t&&(t=[t]);for(const s of t)n.autoInjectToLocalBus&&xt.emit(jt+s,e,{event:s,sender:i}),this.publishServerEvent(s,e);return{event:t,senderId:r}}(0,p.throwError)("event or data is required","pub",p.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},Et=new St(q);function $t(){it.register(),ct.register()}
|
package/dist/funcs.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ClientEventPrefix as m,EventClient as o,EventServer as r,EventToolFunc as p,LRUCache as t,SecondaryCache as c,_lrucache as h,createLRUCache as i,event as j,eventClient as k,eventServer as n,lrucache as s,registerCoreTools as u}from"./chunk-4FKBOPZI.mjs";import"./chunk-TGTHY57V.mjs";export{m as ClientEventPrefix,o as EventClient,r as EventServer,p as EventToolFunc,t as LRUCache,c as SecondaryCache,h as _lrucache,i as createLRUCache,j as event,k as eventClient,n as eventServer,s as lrucache,u as registerCoreTools};
|