@isdk/ai-tool 0.6.0 → 0.7.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/README.cn.md +103 -237
- package/README.md +101 -186
- package/dist/chunk-LNTIQQNN.mjs +1 -0
- package/dist/chunk-VIG2GB47.mjs +1 -1
- package/dist/funcs.d.mts +1 -1
- package/dist/funcs.d.ts +1 -1
- package/dist/funcs.js +1 -1
- package/dist/funcs.mjs +1 -1
- package/dist/index-BCco-g_I.d.mts +1781 -0
- package/dist/index-BCco-g_I.d.ts +1781 -0
- package/dist/index.d.mts +1068 -9
- package/dist/index.d.ts +1068 -9
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/test/util.js +1 -1
- package/docs/api/README.md +165 -0
- package/docs/{_media → api/_media}/CONTRIBUTING.md +3 -3
- package/docs/api/_media/pubsub.md +326 -0
- package/docs/api/_media/server_client_tools.md +88 -0
- package/docs/api/_media/toolFunc.md +183 -0
- package/docs/api/_media/transport.md +137 -0
- package/docs/{classes → api/classes}/AbortError.md +139 -54
- package/docs/api/classes/AlreadyExistsError.md +431 -0
- package/docs/api/classes/BaseError.md +440 -0
- package/docs/{classes → api/classes}/BinarySemaphore.md +25 -25
- package/docs/{classes → api/classes}/CancelableAbility.md +25 -25
- package/docs/api/classes/ClientToolTransport.md +310 -0
- package/docs/{classes → api/classes}/ClientTools.md +642 -180
- package/docs/{classes → api/classes}/CommonError.md +139 -54
- package/docs/{classes → api/classes}/ConfigFile.md +54 -5
- package/docs/{classes → api/classes}/EnvPromptTemplate.md +94 -48
- package/docs/{classes → api/classes}/EventClient.md +725 -232
- package/docs/{classes → api/classes}/EventEmitter.md +12 -12
- package/docs/{classes → api/classes}/EventServer.md +658 -205
- package/docs/{classes → api/classes}/EventToolFunc.md +561 -109
- package/docs/{classes → api/classes}/FStringPromptTemplate.md +94 -48
- package/docs/{classes → api/classes}/FewShotPromptTemplate.md +100 -52
- package/docs/{classes → api/classes}/GolangPromptTemplate.md +99 -53
- package/docs/api/classes/HttpClientToolTransport.md +324 -0
- package/docs/api/classes/HttpServerToolTransport.md +324 -0
- package/docs/{classes → api/classes}/IntSet.md +12 -12
- package/docs/{classes → api/classes}/LRUCache.md +26 -26
- package/docs/api/classes/NotFoundError.md +431 -0
- package/docs/api/classes/NotImplementationError.md +431 -0
- package/docs/{classes → api/classes}/PromptExampleSelector.md +9 -9
- package/docs/{classes → api/classes}/PromptTemplate.md +91 -47
- package/docs/api/classes/ReadableStreamError.md +451 -0
- package/docs/api/classes/ResClientTools.md +2878 -0
- package/docs/api/classes/ResServerTools.md +2856 -0
- package/docs/api/classes/SSEChannel.md +272 -0
- package/docs/{classes → api/classes}/Semaphore.md +26 -26
- package/docs/api/classes/ServerToolTransport.md +323 -0
- package/docs/{classes → api/classes}/ServerTools.md +579 -120
- package/docs/{classes → api/classes}/SignalGate.md +9 -9
- package/docs/api/classes/SseClientPubSubTransport.md +92 -0
- package/docs/api/classes/SseServerPubSubTransport.md +234 -0
- package/docs/{classes → api/classes}/TaskAbortController.md +9 -9
- package/docs/api/classes/ToolFunc.md +2665 -0
- package/docs/api/classes/ToolTransport.md +143 -0
- package/docs/api/classes/YamlTypeBaseObject.md +31 -0
- package/docs/api/enumerations/AsyncFeatureBits.md +33 -0
- package/docs/api/enumerations/AsyncFeatures.md +33 -0
- package/docs/api/enumerations/ErrorCode.md +177 -0
- package/docs/api/enumerations/HashAlgorithm.md +97 -0
- package/docs/{functions → api/functions}/AIArgProcessor.md +1 -1
- package/docs/{functions → api/functions}/AIStream.md +1 -1
- package/docs/{functions → api/functions}/ChoiceArgProcessor.md +1 -1
- package/docs/api/functions/DefaultDateFormat.md +21 -0
- package/docs/{functions → api/functions}/ObjectArgsToArgsInfo.md +1 -1
- package/docs/{functions → api/functions}/RateLimit.md +1 -1
- package/docs/{functions → api/functions}/TemplateArgProcessor.md +1 -1
- package/docs/api/functions/addDate.md +71 -0
- package/docs/{functions → api/functions}/assignDirs.md +1 -1
- package/docs/{functions → api/functions}/backendEventable.md +1 -1
- package/docs/{functions → api/functions}/beforeShutdown.md +1 -1
- package/docs/api/functions/calcPerplexity.md +60 -0
- package/docs/api/functions/calcPerplexitySimple.md +42 -0
- package/docs/api/functions/canonicalize.md +33 -0
- package/docs/{functions → api/functions}/completeSentences.md +1 -1
- package/docs/{functions → api/functions}/concatText.md +1 -1
- package/docs/{functions → api/functions}/countLLMTokens.md +1 -1
- package/docs/{functions → api/functions}/countRegexMatches.md +1 -1
- package/docs/{functions → api/functions}/createAbilityInjector.md +4 -4
- package/docs/{functions → api/functions}/createCallbacksTransformer.md +1 -1
- package/docs/{functions → api/functions}/createEmptyReadableStream.md +1 -1
- package/docs/{functions → api/functions}/createEndWithRepetitionDetector.md +1 -1
- package/docs/{functions → api/functions}/createError.md +1 -1
- package/docs/{functions → api/functions}/createEventStreamTransformer.md +1 -1
- package/docs/{functions → api/functions}/createHfValueFunc.md +1 -1
- package/docs/{functions → api/functions}/createLRUCache.md +1 -1
- package/docs/{functions → api/functions}/createYamlObjectTag.md +1 -1
- package/docs/{functions → api/functions}/dateToText.md +1 -1
- package/docs/{functions → api/functions}/decodeCharset.md +1 -1
- package/docs/api/functions/defaultsWithConcat.md +74 -0
- package/docs/{functions → api/functions}/detectCharset.md +1 -1
- package/docs/{functions → api/functions}/encodeLLMTokens.md +1 -1
- package/docs/{functions → api/functions}/ensureQuoted.md +1 -1
- package/docs/{functions → api/functions}/eventable.md +1 -1
- package/docs/{functions → api/functions}/expandConfig.md +1 -1
- package/docs/{functions → api/functions}/expandEnv.md +1 -1
- package/docs/{functions → api/functions}/expandObjEnv.md +1 -1
- package/docs/{functions → api/functions}/expandPath.md +1 -1
- package/docs/api/functions/expandPathInObject.md +29 -0
- package/docs/api/functions/expandPaths.md +25 -0
- package/docs/{functions → api/functions}/extNameLevel.md +1 -1
- package/docs/{functions → api/functions}/fileIsExists.md +1 -1
- package/docs/{functions → api/functions}/filterValidFnScope.md +1 -1
- package/docs/{functions → api/functions}/findIndexNonEmptyFrom.md +1 -1
- package/docs/{functions → api/functions}/findPort.md +1 -1
- package/docs/{functions → api/functions}/formatISO.md +1 -1
- package/docs/{functions → api/functions}/formatTextWithSpace.md +1 -1
- package/docs/api/functions/funcGetMeta.md +27 -0
- package/docs/api/functions/funcWithMeta.md +41 -0
- package/docs/api/functions/genUrlParamsStr.md +27 -0
- package/docs/{functions → api/functions}/getAllEnumKeys.md +1 -1
- package/docs/{functions → api/functions}/getConfigFileNames.md +1 -1
- package/docs/{functions → api/functions}/getConfigs.md +1 -1
- package/docs/{functions → api/functions}/getEnvVairables.md +1 -1
- package/docs/{functions → api/functions}/getFileMetaInfo.md +1 -1
- package/docs/{functions → api/functions}/getHashAlgoBySize.md +1 -1
- package/docs/{functions → api/functions}/getKeysPath.md +1 -1
- package/docs/{functions → api/functions}/getLLMTokenizer.md +1 -1
- package/docs/{functions → api/functions}/getMultiLevelExtname.md +1 -1
- package/docs/{functions → api/functions}/getPackageDir.md +1 -1
- package/docs/{functions → api/functions}/getRealFilepath.md +1 -1
- package/docs/{functions → api/functions}/getResponseErrorReadableStream.md +1 -1
- package/docs/{functions → api/functions}/getXDGConfigs.md +1 -1
- package/docs/{functions → api/functions}/hasDirectoryIn.md +1 -1
- package/docs/{functions → api/functions}/hash.md +1 -1
- package/docs/{functions → api/functions}/hashFile.md +1 -1
- package/docs/api/functions/hashObject.md +25 -0
- package/docs/{functions → api/functions}/hashStream.md +1 -1
- package/docs/api/functions/initShutdown.md +15 -0
- package/docs/{functions → api/functions}/isLangUsingSpaces.md +1 -1
- package/docs/{functions → api/functions}/isListItemString.md +1 -1
- package/docs/{functions → api/functions}/isModelNameMatched.md +1 -1
- package/docs/{functions → api/functions}/isPunctuationChar.md +1 -1
- package/docs/{functions → api/functions}/isQuoted.md +1 -1
- package/docs/{functions → api/functions}/isRegExp.md +1 -1
- package/docs/{functions → api/functions}/isSameString.md +1 -1
- package/docs/{functions → api/functions}/isSectionString.md +1 -1
- package/docs/{functions → api/functions}/isSentenceEnding.md +1 -1
- package/docs/{functions → api/functions}/isSepLineString.md +1 -1
- package/docs/{functions → api/functions}/isStrWrapped.md +1 -1
- package/docs/{functions → api/functions}/isSubdirectory.md +2 -2
- package/docs/{functions → api/functions}/isTitleString.md +1 -1
- package/docs/{functions → api/functions}/isValidFilename.md +1 -1
- package/docs/{functions → api/functions}/isValidFilepath.md +1 -1
- package/docs/{functions → api/functions}/isWebStream.md +1 -1
- package/docs/api/functions/joinSplitWords.md +46 -0
- package/docs/{functions → api/functions}/jsonFilterToWhere.md +1 -1
- package/docs/{functions → api/functions}/jsonToMarkdownStr.md +9 -1
- package/docs/{functions → api/functions}/loadAIConfig.md +1 -1
- package/docs/{functions → api/functions}/loadConfig.md +1 -1
- package/docs/{functions → api/functions}/loadConfigFile.md +1 -1
- package/docs/{functions → api/functions}/loadFileFromPaths.md +1 -1
- package/docs/{functions → api/functions}/loadTextFromPaths.md +1 -1
- package/docs/{functions → api/functions}/lrucache.md +1 -1
- package/docs/{functions → api/functions}/makeToolFuncCancelable.md +1 -1
- package/docs/{functions → api/functions}/matchUrlProtocol.md +1 -1
- package/docs/{functions → api/functions}/memoize.md +1 -1
- package/docs/api/functions/mergeArray.md +57 -0
- package/docs/{functions → api/functions}/messagesToText.md +1 -1
- package/docs/api/functions/normalizePath.md +21 -0
- package/docs/{functions → api/functions}/paramsSizeToScaleStr.md +1 -1
- package/docs/{functions → api/functions}/parseCommand.md +1 -1
- package/docs/{functions → api/functions}/parseDateFormat.md +1 -1
- package/docs/{functions → api/functions}/parseISO.md +1 -1
- package/docs/{functions → api/functions}/parseJsJson.md +1 -1
- package/docs/{functions → api/functions}/parseJsJsonSimpleSync.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArgInfo.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArgumentInfos.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArguments.md +1 -1
- package/docs/{functions → api/functions}/parseObjectArgumentsAsArgInfos.md +1 -1
- package/docs/{functions → api/functions}/parseYaml.md +1 -1
- package/docs/api/functions/pruneSubdirectories.md +35 -0
- package/docs/api/functions/pruneSubdirectoriesInPlace.md +38 -0
- package/docs/{functions → api/functions}/quoteStr.md +1 -1
- package/docs/{functions → api/functions}/readFilenamesRecursiveSync.md +1 -1
- package/docs/{functions → api/functions}/readTextFileChunks.md +1 -1
- package/docs/{functions → api/functions}/readTextFileChunksEx.md +1 -1
- package/docs/{functions → api/functions}/readableFromAsyncIterable.md +1 -1
- package/docs/{functions → api/functions}/registerCoreTools.md +1 -1
- package/docs/{functions → api/functions}/registerYamlTag.md +1 -1
- package/docs/{functions → api/functions}/removeMarkdownBold.md +1 -1
- package/docs/{functions → api/functions}/removeMarkdownBoldAndItalic.md +1 -1
- package/docs/{functions → api/functions}/removeMarkdownItalic.md +1 -1
- package/docs/{functions → api/functions}/replaceWithPlaceholder.md +1 -1
- package/docs/{functions → api/functions}/restoreFromPlacehoders.md +1 -1
- package/docs/{functions → api/functions}/sanitizeFilename.md +1 -1
- package/docs/{functions → api/functions}/sanitizeFilepath.md +1 -1
- package/docs/{functions → api/functions}/saveConfigFile.md +1 -1
- package/docs/{functions → api/functions}/scaleStrToParamsSize.md +1 -1
- package/docs/{functions → api/functions}/shutdown.md +1 -1
- package/docs/{functions → api/functions}/simplifyObjectArguments.md +1 -1
- package/docs/api/functions/sleep.md +36 -0
- package/docs/{functions → api/functions}/sortedValues.md +1 -1
- package/docs/{functions → api/functions}/splitChunks.md +1 -1
- package/docs/{functions → api/functions}/splitParagraph.md +1 -1
- package/docs/{functions → api/functions}/splitSentence.md +1 -1
- package/docs/api/functions/splitWords.md +42 -0
- package/docs/{functions → api/functions}/stringifyYaml.md +1 -1
- package/docs/{functions → api/functions}/stripConsoleColor.md +1 -1
- package/docs/{functions → api/functions}/textToDate.md +1 -1
- package/docs/{functions → api/functions}/throwError.md +3 -3
- package/docs/{functions → api/functions}/toDate.md +1 -1
- package/docs/{functions → api/functions}/toDateTime.md +1 -1
- package/docs/{functions → api/functions}/toRegExp.md +1 -1
- package/docs/{functions → api/functions}/trimStartOfStreamHelper.md +1 -1
- package/docs/{functions → api/functions}/truncTo.md +1 -1
- package/docs/{functions → api/functions}/truncateByToken.md +1 -1
- package/docs/{functions → api/functions}/truncateToTokenLimit.md +1 -1
- package/docs/{functions → api/functions}/truncateToTokenLimitEx.md +1 -1
- package/docs/{functions → api/functions}/uuid.md +1 -1
- package/docs/{functions → api/functions}/uuidParse.md +1 -1
- package/docs/{functions → api/functions}/uuidStringify.md +1 -1
- package/docs/{functions → api/functions}/uuidValidate.md +1 -1
- package/docs/{functions → api/functions}/uuidVersion.md +1 -1
- package/docs/{functions → api/functions}/uuidv1.md +9 -5
- package/docs/{functions → api/functions}/uuidv4.md +9 -5
- package/docs/{functions → api/functions}/uuidv5.md +9 -5
- package/docs/api/functions/wait.md +45 -0
- package/docs/{functions → api/functions}/wrapEventEmitter.md +1 -1
- package/docs/{functions → api/functions}/xxhash.md +1 -1
- package/docs/{functions → api/functions}/xxhash32.md +1 -1
- package/docs/{functions → api/functions}/xxhash64.md +1 -1
- package/docs/{functions → api/functions}/xxhashAsStr.md +1 -1
- package/docs/api/functions/yieldExec.md +27 -0
- package/docs/{globals.md → api/globals.md} +44 -1
- package/docs/api/interfaces/AIChatAssistantMessageParam.md +129 -0
- package/docs/api/interfaces/AIChatContentPartImage.md +29 -0
- package/docs/api/interfaces/AIChatContentPartText.md +25 -0
- package/docs/api/interfaces/AIChatMessageParamBase.md +68 -0
- package/docs/api/interfaces/AIChatMessageToolCall.md +41 -0
- package/docs/{interfaces → api/interfaces}/AIChatSystemMessageParam.md +9 -9
- package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +37 -0
- package/docs/api/interfaces/AIChatToolChoiceObject.md +25 -0
- package/docs/api/interfaces/AIChatToolFunc.md +41 -0
- package/docs/api/interfaces/AIChatToolFuncParam.md +37 -0
- package/docs/api/interfaces/AIChatToolMessageParam.md +113 -0
- package/docs/api/interfaces/AIChatToolParam.md +25 -0
- package/docs/api/interfaces/AIChatToolTypeObject.md +17 -0
- package/docs/api/interfaces/AIChatUserMessageParam.md +137 -0
- package/docs/api/interfaces/AIChoiceConfig.md +65 -0
- package/docs/api/interfaces/AIResult.md +65 -0
- package/docs/{interfaces → api/interfaces}/AIStreamParser.md +2 -2
- package/docs/api/interfaces/AIStreamParserOptions.md +21 -0
- package/docs/api/interfaces/BaseFunc.md +299 -0
- package/docs/api/interfaces/BaseFuncItem.md +221 -0
- package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +25 -0
- package/docs/api/interfaces/BinarySemaphoreOptions.md +57 -0
- package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +25 -0
- package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +37 -0
- package/docs/api/interfaces/CancelableAbilityOptions.md +113 -0
- package/docs/api/interfaces/ClientFuncItem.md +326 -0
- package/docs/api/interfaces/EventClientFuncParams.md +51 -0
- package/docs/api/interfaces/EventServerFuncParams.md +73 -0
- package/docs/{interfaces → api/interfaces}/FewShotPromptTemplateOptions.md +24 -12
- package/docs/api/interfaces/FuncItem.md +281 -0
- package/docs/api/interfaces/FuncParam.md +51 -0
- package/docs/api/interfaces/FuncParams.md +28 -0
- package/docs/api/interfaces/Funcs.md +15 -0
- package/docs/api/interfaces/HashAlgoParams.md +33 -0
- package/docs/api/interfaces/IClientToolTransport.md +155 -0
- package/docs/api/interfaces/IFileMetaInfo.md +65 -0
- package/docs/api/interfaces/IPubSubClientTransport.md +70 -0
- package/docs/api/interfaces/IPubSubServerTransport.md +241 -0
- package/docs/api/interfaces/IReadTextFileChunksOptions.md +143 -0
- package/docs/api/interfaces/IServerToolTransport.md +159 -0
- package/docs/api/interfaces/IToolTransport.md +73 -0
- package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +99 -0
- package/docs/api/interfaces/JsonFilter.md +13 -0
- package/docs/api/interfaces/ParseObjectArgumentOptions.md +89 -0
- package/docs/api/interfaces/ProbabilityItem.md +41 -0
- package/docs/api/interfaces/PromptExampleSelectorOptions.md +34 -0
- package/docs/{interfaces → api/interfaces}/PromptTemplateOptions.md +15 -7
- package/docs/api/interfaces/PubSubClient.md +27 -0
- package/docs/api/interfaces/PubSubClientStream.md +196 -0
- package/docs/api/interfaces/PubSubServerSession.md +103 -0
- package/docs/api/interfaces/RemoteFuncItem.md +316 -0
- package/docs/api/interfaces/ReplacePlacehoderOptions.md +41 -0
- package/docs/api/interfaces/ResClientFuncParams.md +37 -0
- package/docs/api/interfaces/ResServerFuncParams.md +73 -0
- package/docs/api/interfaces/SanitizeFilenameOptions.md +25 -0
- package/docs/api/interfaces/SectionStringOptions.md +25 -0
- package/docs/api/interfaces/SemaphoreOptions.md +89 -0
- package/docs/api/interfaces/SemaphoreTaskItem.md +73 -0
- package/docs/api/interfaces/ServerFuncItem.md +339 -0
- package/docs/api/interfaces/ServerFuncParams.md +41 -0
- package/docs/api/interfaces/SplitSentenceOptions.md +41 -0
- package/docs/{interfaces → api/interfaces}/StreamCallbacksAndOptions.md +5 -5
- package/docs/{interfaces → api/interfaces}/TaskAbortControllers.md +1 -1
- package/docs/{interfaces → api/interfaces}/TaskPromise.md +6 -6
- package/docs/api/interfaces/ToolFuncPackage.md +57 -0
- package/docs/{namespaces → api/namespaces}/EventStates/variables/ABORT.md +1 -1
- package/docs/{namespaces → api/namespaces}/EventStates/variables/CONTINUE.md +1 -1
- package/docs/{namespaces → api/namespaces}/EventStates/variables/DONE.md +1 -1
- package/docs/{namespaces → api/namespaces}/EventStates/variables/STOPPED.md +1 -1
- package/docs/{namespaces → api/namespaces}/uuidv5/variables/DNS.md +1 -1
- package/docs/{namespaces → api/namespaces}/uuidv5/variables/URL.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatContentPart.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatMessageParam.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatRole.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIChatToolChoiceParam.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/AIMessageType.md +1 -1
- package/docs/api/type-aliases/AIModelNameRule.md +14 -0
- package/docs/api/type-aliases/AIModelNameRuleFn.md +28 -0
- package/docs/api/type-aliases/AIModelNameRules.md +13 -0
- package/docs/{type-aliases → api/type-aliases}/AITextGenerationFinishReason.md +1 -1
- package/docs/api/type-aliases/ActionName.md +13 -0
- package/docs/api/type-aliases/ArrayMergeWay.md +11 -0
- package/docs/api/type-aliases/AsyncTaskId.md +11 -0
- package/docs/{type-aliases → api/type-aliases}/BeforeShutdownListener.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/EventErrorListenerFn.md +1 -1
- package/docs/{type-aliases → api/type-aliases}/EventListenerFn.md +1 -1
- package/docs/api/type-aliases/FuncParamType.md +13 -0
- package/docs/{type-aliases → api/type-aliases}/PromptExamples.md +1 -1
- package/docs/api/type-aliases/PubSubClientId.md +14 -0
- package/docs/api/type-aliases/PubSubCtx.md +37 -0
- package/docs/api/type-aliases/RpcMethodHandler.md +34 -0
- package/docs/{type-aliases → api/type-aliases}/SemaphoreIsReadyFuncType.md +1 -1
- package/docs/api/type-aliases/TFunc.md +33 -0
- package/docs/{variables → api/variables}/AIChatRoles.md +1 -1
- package/docs/{variables → api/variables}/AIMessageTypes.md +1 -1
- package/docs/{variables → api/variables}/AITextGenerationFinishReasons.md +1 -1
- package/docs/{variables → api/variables}/AbortErrorCode.md +1 -1
- package/docs/api/variables/ActionNames.md +13 -0
- package/docs/{variables → api/variables}/AlreadyExistsErrorCode.md +1 -1
- package/docs/api/variables/ArrayMergeWay.md +25 -0
- package/docs/api/variables/ArrayMergeWaySymbol.md +11 -0
- package/docs/api/variables/ClientToolFuncSchema.md +83 -0
- package/docs/{variables → api/variables}/DEFAULT_CONFIG_NAME.md +1 -1
- package/docs/{variables → api/variables}/DefaultAsyncSemaphoreCapacity.md +1 -1
- package/docs/api/variables/EventBusName.md +11 -0
- package/docs/api/variables/EventName.md +11 -0
- package/docs/{variables → api/variables}/FilenameReservedRegex.md +1 -1
- package/docs/api/variables/FuncMetaSymbol.md +15 -0
- package/docs/{variables → api/variables}/InternalErrorCode.md +1 -1
- package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES.md +1 -1
- package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES_MAP.md +1 -1
- package/docs/{variables → api/variables}/NotFoundErrorCode.md +1 -1
- package/docs/{variables → api/variables}/NotImplementedErrorCode.md +1 -1
- package/docs/api/variables/PASSING_SCORE.md +13 -0
- package/docs/api/variables/RStreamErrCode.md +11 -0
- package/docs/api/variables/RemoteToolFuncSchema.md +84 -0
- package/docs/api/variables/ResponseRStreamErrCode.md +11 -0
- package/docs/{variables → api/variables}/SHUTDOWN_SIGNALS.md +1 -1
- package/docs/{variables → api/variables}/SSEChannelAlreadyClosedErrCode.md +1 -1
- package/docs/api/variables/SecondaryCache.md +11 -0
- package/docs/api/variables/ServerToolFuncSchema.md +83 -0
- package/docs/api/variables/StrangeHumanName.md +11 -0
- package/docs/api/variables/ToolAsyncCancelableBit.md +11 -0
- package/docs/api/variables/ToolAsyncMultiTaskBit.md +11 -0
- package/docs/api/variables/ToolAsyncPriorityBit.md +11 -0
- package/docs/{variables → api/variables}/ToolFuncSchema.md +14 -1
- package/docs/{variables → api/variables}/WindowsReservedNameRegex.md +1 -1
- package/docs/api/variables/base32768.md +11 -0
- package/docs/{variables → api/variables}/defaultTemplateFormat.md +1 -1
- package/docs/api/variables/event.md +11 -0
- package/docs/api/variables/eventClient.md +11 -0
- package/docs/api/variables/eventServer.md +11 -0
- package/docs/api/variables/lrucache.md +11 -0
- package/docs/{variables → api/variables}/mimeType.md +1 -1
- package/docs/{variables → api/variables}/uuidNIL.md +1 -1
- package/docs/pubsub.md +326 -0
- package/docs/server_client_tools.md +88 -0
- package/docs/toolFunc.md +183 -0
- package/docs/transport.md +137 -0
- package/package.json +38 -40
- package/dist/chunk-OYDBRUZJ.mjs +0 -1
- package/dist/index-BkwhCK1q.d.mts +0 -899
- package/dist/index-BkwhCK1q.d.ts +0 -899
- package/docs/README.md +0 -250
- package/docs/classes/AlreadyExistsError.md +0 -346
- package/docs/classes/BaseError.md +0 -359
- package/docs/classes/NotFoundError.md +0 -346
- package/docs/classes/NotImplementationError.md +0 -346
- package/docs/classes/ReadableStreamError.md +0 -366
- package/docs/classes/ResClientTools.md +0 -2451
- package/docs/classes/ResServerTools.md +0 -2427
- package/docs/classes/SSEChannel.md +0 -270
- package/docs/classes/ToolFunc.md +0 -2201
- package/docs/classes/YamlTypeBaseObject.md +0 -31
- package/docs/enumerations/AsyncFeatureBits.md +0 -33
- package/docs/enumerations/AsyncFeatures.md +0 -33
- package/docs/enumerations/ErrorCode.md +0 -177
- package/docs/enumerations/HashAlgorithm.md +0 -97
- package/docs/functions/canonicalize.md +0 -21
- package/docs/functions/initShutdown.md +0 -15
- package/docs/functions/wait.md +0 -21
- package/docs/interfaces/AIChatAssistantMessageParam.md +0 -129
- package/docs/interfaces/AIChatContentPartImage.md +0 -29
- package/docs/interfaces/AIChatContentPartText.md +0 -25
- package/docs/interfaces/AIChatMessageParamBase.md +0 -68
- package/docs/interfaces/AIChatMessageToolCall.md +0 -41
- package/docs/interfaces/AIChatToolChoiceFuncObject.md +0 -37
- package/docs/interfaces/AIChatToolChoiceObject.md +0 -25
- package/docs/interfaces/AIChatToolFunc.md +0 -41
- package/docs/interfaces/AIChatToolFuncParam.md +0 -37
- package/docs/interfaces/AIChatToolMessageParam.md +0 -113
- package/docs/interfaces/AIChatToolParam.md +0 -25
- package/docs/interfaces/AIChatToolTypeObject.md +0 -17
- package/docs/interfaces/AIChatUserMessageParam.md +0 -137
- package/docs/interfaces/AIChoiceConfig.md +0 -65
- package/docs/interfaces/AIResult.md +0 -65
- package/docs/interfaces/AIStreamParserOptions.md +0 -21
- package/docs/interfaces/BaseFunc.md +0 -157
- package/docs/interfaces/BaseFuncItem.md +0 -101
- package/docs/interfaces/BinarySemaphoreAcquireOptions.md +0 -25
- package/docs/interfaces/BinarySemaphoreOptions.md +0 -57
- package/docs/interfaces/BinarySemaphoreReleaseOptions.md +0 -25
- package/docs/interfaces/BinarySemaphoreReleaserFunc.md +0 -37
- package/docs/interfaces/CancelableAbilityOptions.md +0 -113
- package/docs/interfaces/ClientFuncItem.md +0 -175
- package/docs/interfaces/EventClientFuncParams.md +0 -51
- package/docs/interfaces/EventServerFuncParams.md +0 -67
- package/docs/interfaces/FuncItem.md +0 -143
- package/docs/interfaces/FuncParam.md +0 -61
- package/docs/interfaces/FuncParams.md +0 -13
- package/docs/interfaces/Funcs.md +0 -13
- package/docs/interfaces/HashAlgoParams.md +0 -33
- package/docs/interfaces/IFileMetaInfo.md +0 -65
- package/docs/interfaces/IReadTextFileChunksOptions.md +0 -143
- package/docs/interfaces/ITruncateToTokenLimitOptions.md +0 -99
- package/docs/interfaces/JsonFilter.md +0 -13
- package/docs/interfaces/ParseObjectArgumentOptions.md +0 -89
- package/docs/interfaces/PromptExampleSelectorOptions.md +0 -34
- package/docs/interfaces/RemoteFuncItem.md +0 -164
- package/docs/interfaces/ReplacePlacehoderOptions.md +0 -41
- package/docs/interfaces/ResClientFuncParams.md +0 -37
- package/docs/interfaces/ResServerFuncParams.md +0 -69
- package/docs/interfaces/SanitizeFilenameOptions.md +0 -25
- package/docs/interfaces/SectionStringOptions.md +0 -25
- package/docs/interfaces/SemaphoreOptions.md +0 -89
- package/docs/interfaces/SemaphoreTaskItem.md +0 -73
- package/docs/interfaces/ServerFuncItem.md +0 -183
- package/docs/interfaces/ServerFuncParams.md +0 -35
- package/docs/interfaces/SplitSentenceOptions.md +0 -41
- package/docs/interfaces/ToolFuncPackage.md +0 -47
- package/docs/type-aliases/AIModelNameRule.md +0 -11
- package/docs/type-aliases/AIModelNameRuleFn.md +0 -21
- package/docs/type-aliases/AIModelNameRules.md +0 -11
- package/docs/type-aliases/ActionName.md +0 -11
- package/docs/type-aliases/AsyncTaskId.md +0 -11
- package/docs/type-aliases/FuncParamType.md +0 -11
- package/docs/type-aliases/TFunc.md +0 -25
- package/docs/variables/ActionNames.md +0 -11
- package/docs/variables/ClientToolFuncSchema.md +0 -101
- package/docs/variables/EventBusName.md +0 -11
- package/docs/variables/EventName.md +0 -11
- package/docs/variables/PASSING_SCORE.md +0 -11
- package/docs/variables/RStreamErrCode.md +0 -11
- package/docs/variables/RemoteToolFuncSchema.md +0 -101
- package/docs/variables/ResponseRStreamErrCode.md +0 -11
- package/docs/variables/SecondaryCache.md +0 -11
- package/docs/variables/ServerToolFuncSchema.md +0 -101
- package/docs/variables/ToolAsyncCancelableBit.md +0 -11
- package/docs/variables/ToolAsyncMultiTaskBit.md +0 -11
- package/docs/variables/ToolAsyncPriorityBit.md +0 -11
- package/docs/variables/base32768.md +0 -11
- package/docs/variables/event.md +0 -11
- package/docs/variables/eventClient.md +0 -11
- package/docs/variables/eventServer.md +0 -11
- package/docs/variables/lrucache.md +0 -11
- /package/docs/{_media → api/_media}/LICENSE-MIT +0 -0
- /package/docs/{namespaces → api/namespaces}/EventStates/README.md +0 -0
- /package/docs/{namespaces → api/namespaces}/uuidv5/README.md +0 -0
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:()=>vt,EventServer:()=>xt,EventToolFunc:()=>it,LRUCache:()=>ot.LRUCache,SecondaryCache:()=>ht,_lrucache:()=>at,createLRUCache:()=>ct,event:()=>rt,eventClient:()=>mt,eventServer:()=>St,lrucache:()=>ut,registerCoreTools:()=>jt}),module.exports=(t=c,h(s({},"__esModule",{value:!0}),t));var u=(()=>"undefined"==typeof document?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href)(),l=require("events-ex"),f=require("property-manager"),d=require("util-ex"),p=require("@isdk/common-error"),y=(require("custom-ability"),require("util-ex"),["get","post","put","delete","patch","list","res"]),v={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,s,i,r)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},m=(require("date-fns"),require("date-fns"),require("@isdk/template-engines"),require("@isdk/template-engines"));function b(t){return Object.keys(t).sort().map((e=>t[e]))}var g=class extends m.StringTemplate{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof m.StringTemplate?t.examplePrompt:m.StringTemplate.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const s=await this.examplePrompt.format(t);e.push(s)}else if("string"==typeof t)e.push(t);else if(t){const s=b(t);s.length>0&&e.push(...s)}const s=[this.prefix,...e,this.suffix].join(this.exampleSeparator),i=this.templateFormat;return await m.StringTemplate.format({template:s,data:t,templateFormat:i})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};m.StringTemplate.register(g,{name:"fewshot",aliases:["few_shot"]});(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{0}));require("@isdk/detect-text-language"),new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var w=require("custom-ability"),q=(require("events-ex"),"event"),k="event-bus";(0,w.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(k)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.on(e,s)}once(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.once(e,s)}off(e,s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.off(e,s)}emit(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,s):i.emit.call(this,e,this.name,...s)}emitError(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emit.call(this,"error",e,this.name,...s)}async emitAsync(e,...s){const i=t.emitter;if(!i)throw new TypeError("EventBackend required");return i.emitAsync.call(this,e,this.name,...s)}}}),!0);function A(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var x=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let s,i;this.active||(0,p.throwError)("Channel closed","SSEChannel",498);let r=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(r=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",s="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:r,output:s});else{if(!this.clients.size)return;s="data: \n\n"}for([...this.clients].filter((t=>!r||A(t.events,r))).forEach(((t,e)=>{t.res.write(s)}));this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e,s){this.active||(0,p.throwError)("Channel closed","SSEChannel",498);const i={req:t,res:e,events:s},r=this.options.maxStreamDuration;let n="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";r>0&&(n+=", s-maxage="+(Math.floor(r/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":n,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),i.req.socket.setNoDelay(!0),i.res.writeHead(200,o);let h="retry: "+this.options.clientRetryInterval+"\n\n";const a=Number.parseInt(t.headers["last-event-id"],10),c=Number.isNaN(a)?this.options.rewind:this.nextID-1-a;return c&&this.messages.filter((t=>A(i.events,t.eventName))).slice(0-c).forEach((t=>{h+=t.output})),i.res.write(h),this.clients.add(i),r>0&&setTimeout((()=>{i.res.writableEnded||this.unsubscribe(i)}),r),i.res.on("close",(()=>this.unsubscribe(i))),i}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const s=e.req.socket.remoteAddress??"";s in t||(t[s]=0),t[s]++})),t}getSubscriberCount(){return this.clients.size}};require("eventsource-parser");require("uuid"),a(require("base32768")),require("uuid");var S=a(require("xxhashjs")),{h32:j,h64:E}=(a(require("base32768")),require("json-canonicalize"),require("hash-wasm"),S.default),C=(require("json-canonicalize"),a(require("base32768")),require("@isdk/util"),require("util-ex"),require("lodash-es"),require("util-ex"),require("lodash-es"),require("util-ex"),"[a-zA-Z_$][a-zA-Z_\\d$]*"),T=(new RegExp(`^\\s*(\\(\\s*\\)|${C}|\\(${`${C}\\s*(,\\s*${C})*`}\\))\\s*=>`),a(require("mime-type/with-db")),a(require("jschardet")),require("@isdk/util")),O=require("yaml-types");require("mime-type/with-db"),require("@isdk/util");(0,T.registerYamlTag)(O.regexp);var R=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}},$=require("util-ex"),F=require("events-ex");function P(t=0){return e=Math.min(Math.max(16,t),1073741824),e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,1+(e|=e>>16);var e}var M=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=P(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const s=this._front+e&this._capacity-1;return this[s]=t,++e<=this._capacity&&(this._length=e),s}unshift(t){let e=this._length;this.checkCapacity(++e);const s=this._capacity,i=(this._front-1&s-1^s)-s;return this[i]=t,this._front=i,e<=this._capacity&&(this._length=e),i}pop(t){let e=this._length;if(0===e)return;let s=this._front+e-1&this._capacity-1,i=this[s];for(;--e>0&&t&&null==i;)s--,i=this[s];return this[s]=void 0,this._length=e,i}shift(t){let e=this._length;if(0===e)return;let s=this._front,i=this[s];for(;--e>0&&t&&null==i;)s=s+1&this._capacity-1,i=this[s];return this[s]=void 0,this._front=s+1&this._capacity-1,this._length=e,i}get size(){return this._length}get(t){let e;if(t===(0|t)){const s=this._length;t<0&&(t+=s),t>=0&&t<s&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,s=this._capacity;for(let i=0;i<t;++i)this[e+i&s-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const s=this._front,i=this._capacity-1,r=s+t&i,n=this[r];if(t<e/2)this.copyWithin(s+1&i,s,s+t&i),this[s]=void 0,this._front=s+1&i;else{this.copyWithin(r,r+1&i,s+e&i);this[s+e-1&i]=void 0}return this._length=e-1,n}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(P(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const s=this._front,i=this._length;if(s+i>e){!function(t,e,s,i,r){for(let n=0;n<r;++n)s[n+i]=t[n+e],t[n+e]=void 0}(this,0,this,e,s+i&e-1)}}},_=require("@isdk/common-error"),I=32;function N(t){return"function"==typeof t}function z(){return"1"}var J,U=class{constructor(t={}){const{initFn:e=z,pauseFn:s,resumeFn:i,capacity:r=I}=t;if(N(s)!==N(i))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new M(r),this.emitter=new F.EventEmitter,this.useDefaultTokens=e===z,this.pauseFn=s,this.resumeFn=i,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,s=this.waiting.shift(!0);s?this._dispatchTask(s,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",(t=>{this.onReleased(t)}))}_newReleaser(t){let e=!1;const s=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(s,t),s}_dispatchTask(t,e){const{resolve:s}=t;s(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,s=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const s=this.waiting.push(t),i=t.reject;return e&&e.addEventListener("abort",(()=>{this.waiting[s]=void 0;const t=e.reason instanceof Error?e.reason:new _.AbortError(e.reason||"aborted");e.alreadyRejected=!0,i(t)})),s};let i=this.tryAcquire(t);const r=i&&(0,$.isAsync)(i),n=e=>new Promise(((i,r)=>{const n={...t,resolve:i,reject:r,token:e};void 0===e?s(n):this._dispatchTask(n,{...t,token:e})}));return r?i.then((t=>n(t))):n(i)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new _.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},W=class extends U{constructor(t,e){if("number"==typeof t)(e=e||{}).maxConcurrency=t;else{if("number"!=typeof(e=t).maxConcurrency)throw new Error("maxConcurrency must be set");t=e.maxConcurrency}super(e),this.maxConcurrency=e.maxConcurrency,e.isReadyFn&&(this.isReady=e.isReadyFn)}initFree(t){const e=t.maxConcurrency=Math.max(1,t.maxConcurrency);this.free=new M(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,$.isAsync)(e)){return e instanceof Promise||(e=e()),e.then((e=>{if(e)return this.lock(t)}))}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}},B=(require("@isdk/common-error"),require("custom-ability")),L=require("util-ex"),Z=((J=Z||{})[J.MultiTask=1]="MultiTask",J[J.Cancelable=2]="Cancelable",J[J.Priority=4]="Priority",J),D=class extends AbortController{constructor(t){super(),(0,L.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new p.AbortError(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new p.AbortError(e.reason||"aborted")}}},G=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,s=this.__task_semaphore;return e>0&&!s&&(t&&(t=t.bind(this)),s=this.__task_semaphore=new W(e-1,{isReadyFn:t})),s}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures;return e._asyncFeatures&&(s|=e._asyncFeatures),R.has(s,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),R.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".isAborted",p.ErrorCode.InvalidArgument);s=s[t]}return!s||s.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let s=this.__task_aborter;if(s&&e){if(null==t)throw new p.CommonError("Missing taskId",this.name+".getRunningTask",p.ErrorCode.InvalidArgument);s=s[t]}return s?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,s=void 0),s}getRunningTaskCount(){let t;if(this.hasAsyncFeature(0)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,s])=>{if(!s?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const s=this.super,i=this.self||this;return t=s?s.call(i,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,s=!0){const i=this.hasAsyncFeature(0);if(!i&&s&&this.getRunningTask())throw new p.CommonError("The task is running",this.name,p.ErrorCode.TooManyRequests);const r=t?.aborter||new D(this);if(!(r instanceof D)){if(!(r instanceof AbortController))throw new p.CommonError("aborter should be an AbortController",this.name,p.ErrorCode.InvalidArgument);Object.setPrototypeOf(r,new D(this))}if(i){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),r.id=e,t[e]=r}else this.__task_aborter=r;const n=t?.timeout;return n>0&&(r.timeoutId=setTimeout((()=>{r.timeoutId=void 0,this.abort("timeout",{timeout:n})}),n)),r.signal.addEventListener("abort",(()=>{const t=r.timeoutId;t&&(r.timeoutId=void 0,clearTimeout(t));const e=r.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{r.streamController?.error(e.reason)}})),r}$cleanMultiTaskAborter(t,e){const s=this.super,i=this.self||this;s?s.call(i,t,e):i._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(0)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,s){const i=this.createAborter(e,s?.taskId,s?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=i);let r=t(e,i).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(i)},s=function(t){const e=t||{};return new TransformStream({async start(t){const s=t.error;if(t.error=i=>{s.call(t,i),e.onError&&e.onError(i)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,s){try{let i;e.onTransform&&(i=await e.onTransform(t,s)),i||(i=t),s.enqueue(i)}catch(t){s.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}({onStart:t=>{(0,L.defineProperty)(i,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=i.id),t)});t=t.pipeThrough(s)}else this.cleanTaskAborter(i);return t})).catch((t=>{throw this.cleanTaskAborter(i),t})).finally((()=>{i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=void 0)}));return r.task=i,r}runAsyncCancelableTask(t={},e,s){let i=this.createTaskPromise(e,t,s);const r=this.getSemaphore(s?.isReadyFn);if(r){const t=i,e=t.task;i=r.acquire({signal:e.signal}).then((()=>t)).finally((()=>{r.release()})),i.task=e}return i}abort(t,e){let s=this.__task_aborter;if(s){const i=s;if(this.hasAsyncFeature(0)){const t=e?.taskId;if(null==t)throw new p.CommonError("Missing data.taskId",this.name+".abort",p.ErrorCode.InvalidArgument);s=s[t],this.cleanMultiTaskAborter(t,i)}else this.__task_aborter=void 0;s&&!s.signal.aborted&&s.abort(t,e)}}};G.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},G.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,B.createAbilityInjector)(G,"abort",{afterInjection:function(t,e){let s=t.prototype._asyncFeatures||0;s|=Z.Cancelable,e&&(e.asyncFeatures&&(s|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=s}}),a(require("memoizee")),require("json-canonicalize");var H=a(require("path")),K=require("pkg-dir");require("util-ex");var Q=a(require("path")),V=require("url"),X=(require("@xenova/transformers"),(0,V.fileURLToPath)(u)),Y=Q.default.dirname(X),{exit:tt}=(Q.default.join(function(t){const e=(0,K.packageDirectorySync)({cwd:t});if(e)return e;const s=t.split(H.default.sep);let i=s.lastIndexOf("dist");if(i>0)return s.slice(0,i).join(H.default.sep);if(i=s.lastIndexOf("src"),i>0)return s.slice(0,i).join(H.default.sep);throw new Error("can not find package directory")}(Y),".cache"),require("yaml"),require("lodash-es"),process),et=class t extends f.AdvancePropertyManager{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const s in this.list()){const i=this.get(s);let r=i.tags;if("string"==typeof r){if(r===t){e=i;break}}else if(Array.isArray(r)&&r.indexOf(t)>=0){e=i;break}}return e}static getAllByTag(t){let e=[];for(const s in this.list()){const i=this.get(s);let r=i.tags;"string"==typeof r?r===t&&e.push(i):Array.isArray(r)&&r.indexOf(t)>=0&&e.push(i)}return e}static hasAsyncFeature(t){const e=this.prototype;let s=e.asyncFeatures;return e._asyncFeatures&&(s|=e._asyncFeatures),R.has(s,t)}static run(t,e){const s=this.get(t);if(s)return s.run(e);throw new p.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const s=this.get(t);if(s)return s.runSync(e);throw new p.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const s=this.get(t);if(s)return s.runWithPos(...e);throw new p.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const s=this.get(t);if(s)return s.runWithPosSync(...e);throw new p.NotFoundError(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,s={}){switch(typeof e){case"string":s.name=e;break;case"function":s.func=e;break;case"object":s=e}e=s.name;let i=!!this.get(e);if(i)i=!1;else{if(!(s instanceof t))return i=new this(s),i.register();if(this.items[e]=s,s.alias){const t=s.alias;if("string"==typeof t)this.aliases[t]&&(0,p.throwError)(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const s of t)this.aliases[s]&&(0,p.throwError)(`Alias ${s} already exists for ${e}`),this.aliases[s]=e}i=s}return i}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,s=this.depends;if(s){const e=Object.keys(s);for(const i of e){const e=s[i];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},s=Object.keys(this.params);let i=Math.min(s.length,t.length);for(let r=0;r<i;r++)e[s[r]]=t[r];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const s=Object.keys(t);let i=Math.min(s.length,this.params.length);for(let r=0;r<i;r++)e.push(t[s[r]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,p.throwError)("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),R.has(e,t)}isStream(t){return this.stream}},st={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,s,i,r){let n=t;const o=typeof t;return r.isExported?n="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),n=(0,d._createFunction)(t,e.scope)),n}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"},alias:{type:["array","string"]}};et.defineProperties(et,st);var it=class extends et{constructor(){super(...arguments),this._emitter=new l.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},rt=new it(k),nt=require("secondary-cache"),ot=require("secondary-cache"),ht=nt.Cache;function at({key:t,value:e,options:s}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,s):this.cache.get(t):(s&&this.cache.setDefaultOptions(s),this.cache)}function ct(t,e){let s=et.get(t);return s||(s=new et(t,{func:at,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),s.cache=new nt.Cache(e)),s}var ut=ct("lrucache"),lt=class t extends et{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static async loadFrom(){if(this._apiRoot){const t=await fetch(this._apiRoot,{headers:{"Content-Type":"application/json"}}),e=await t.json();e&&this.loadFromSync(e)}else(0,p.throwError)("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const s in e){const i=this.get(s),r=e[s];i?i instanceof t?i.assign(r):(0,p.throwError)(`${s} already registered as ${i.constructor.name}`,"ClientTools"):this.register(r)}}static async fetch(t,e){const s=this.get(t);if(s&&s.fetch)return s.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,s){const i={...this.fetchOptions},r=["post","put","patch"];let n;e||(e=this.action||"post"),"res"===e&&(e="get"),i.headers&&i.headers["Content-Type"]||!r.includes(e)||(i.headers={"Content-Type":"application/json",...i.headers}),t?.stream&&!i.headers.Connection&&(i.headers.Connection="keep-alive"),s?("string"!=typeof s&&(s=JSON.stringify(s)),s=this.name+"/"+s):s=this.name,i.method=e.toUpperCase(),"get"===e||"delete"===e?n=s+this.getUrlParams(t):(i.body=JSON.stringify(t),n=s),i.headers&&!r.includes(e)&&delete i.headers["Content-Type"];const o=await fetch(`${this.apiRoot}/${n}`,i);if(!o.ok){throw await this.errorFrom(o)}return o}async errorFrom(t){let e,s=t.status,i=t.statusText,r=this.name;if(t.body){const s=await t.text();try{const t=JSON.parse(s);t&&(t.error&&(i=t.error),t.name&&(r=t.name),t.data&&(e=t.data,e.name=r,e.what&&(e.msg=i,i=e.what)),t.message&&(i=i+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return(0,p.createError)(i,r,s)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},ft={...v};lt.defineProperties(lt,ft);var dt=class extends lt{async _func(t,e){const s=await this.fetch(e,t);if(e?.stream)return s;return await s.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},pt={methods:{type:"array",assign(t,e,s,i,r){r?.isExported||e.assignMethods(t)}}};dt.defineProperties(dt,pt);var yt=class extends dt{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let s=t.id;return s||(0,p.throwError)("id is required"),"string"==typeof s&&(s=encodeURIComponent(s)),delete t.id,super.fetch(t,e,s)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}},vt=class extends yt{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=q,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",s=`${this.apiRoot}/${this.name}${e}`,i=this._es=new EventSource(s);return Object.entries(this._sseEvents).forEach((([t,e])=>{i.addEventListener(t,e)})),this._esEvents=t,i}esListener(t){const e=t.data?JSON.parse(t.data):void 0,s=t.type;if(!this._forwardEvents.has(s)){const t=this.emitter;t&&e&&s&&(Array.isArray(e)?t.emit(s,...e):t.emit(s,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const s=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);s.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},mt=new vt(q),bt=require("util-ex"),gt=class t extends et{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const s in this.items){let i=this.items[s];(i instanceof t||i.isApi)&&(i.allowExportFunc||(i=i.toJSON(),delete i.func),e[s]=i)}return e}func({}){}},wt={...v};gt.defineProperties(gt,wt);var qt=class extends gt{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const s=this.methods=[];this.initRpcMethods(s)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const s of e)"function"==typeof this[s]&&t.push(s);(0,bt.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const s=e.slice(1);void 0===this[s]&&(this[s]=this[e])}))}cast(t,e){let s=this.params[t];return s&&("string"!=typeof s&&(s=s.type),"number"===s&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new p.NotFoundError(e,this.name)}};qt.defineProperties(qt,{methods:{type:"array"}});var kt=class extends qt{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=y}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},At=rt.runSync(),xt=class t extends kt{constructor(){super(...arguments),this.name=q,this.description="subscribe server sent event",this.result="event",this.depends={[k]:rt}}static get sse(){return this._sse||(this._sse=new x),this._sse}get sse(){return this.constructor.sse}static publish(e,s){return t.sse.publish(e,s)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,s,i){return t.sse.subscribe(e,s,i)}static alreadyForward(e){const s=At.listeners(e);for(const e of s)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,s){return"string"==typeof s&&(s=[s]),this.constructor.subscribe(t,e,s)}forward(e){Array.isArray(e)||(e=[e]);for(const s of e)t.alreadyForward(s)||At.on(s,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const s of e)At.off(s,t.ebListener)}list({_req:t,_res:e,event:s}){t&&e&&this.subscribeSSE(t,e,s)}$sub({event:t}){if(t)return this.forward(t),{event:t};(0,p.throwError)("event is required","sub",p.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,p.throwError)("event is required","unsub",p.ErrorCode.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const s of t)this.publishSSE(e,s);return{event:t}}(0,p.throwError)("event or data is required","pub",p.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},St=new xt(q);function jt(){rt.register(),ut.register()}
|
|
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()}
|
package/dist/funcs.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventClient as m,EventServer as o,EventToolFunc as r,LRUCache as p,SecondaryCache as t,_lrucache as
|
|
1
|
+
import{EventClient as m,EventServer as o,EventToolFunc as r,LRUCache as p,SecondaryCache as t,_lrucache as N,createLRUCache as c,event as h,eventClient as i,eventServer as j,lrucache as k,registerCoreTools as n}from"./chunk-LNTIQQNN.mjs";import"./chunk-VIG2GB47.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as LRUCache,t as SecondaryCache,N as _lrucache,c as createLRUCache,h as event,i as eventClient,j as eventServer,k as lrucache,n as registerCoreTools};
|