@luckylillia-dev/luckylillia 0.0.0-stage → 9.0.1
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/chunks/preload-helper-D5R8FHQt.js +342 -0
- package/chunks/preload-helper-D5R8FHQt.js.map +1 -0
- package/default_config.json +83 -0
- package/llbot-core.js +35013 -0
- package/llbot-core.js.map +1 -0
- package/llbot.js +138 -0
- package/llbot.js.map +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/commands.d.ts +86 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/commands.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/config.d.ts +14 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/config.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/ffmpeg.d.ts +41 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/ffmpeg.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/http.d.ts +88 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/http.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/index.d.ts +17 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/index.js +6 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/internal.d.ts +430 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/internal.js +7 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/manifest.d.ts +68 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/manifest.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/server.d.ts +23 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/server.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/storage.d.ts +21 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/storage.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/testing.d.ts +71 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/testing.js +1123 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/universal.d.ts +299 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/universal.js +1 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/webui.d.ts +762 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/lib/webui.js +9 -0
- package/node_modules/@luckylillia-dev/plugin-sdk/package.json +63 -0
- package/node_modules/@satorijs/element/jsx-dev-runtime.d.ts +3 -0
- package/node_modules/@satorijs/element/jsx-runtime.d.ts +3 -0
- package/node_modules/@satorijs/element/lib/index.cjs +447 -0
- package/node_modules/@satorijs/element/lib/index.d.ts +116 -0
- package/node_modules/@satorijs/element/lib/index.mjs +455 -0
- package/node_modules/@satorijs/element/package.json +60 -0
- package/node_modules/@satorijs/element/src/index.ts +559 -0
- package/node_modules/@satorijs/protocol/lib/index.cjs +187 -0
- package/node_modules/@satorijs/protocol/lib/index.d.ts +328 -0
- package/node_modules/@satorijs/protocol/lib/index.mjs +148 -0
- package/node_modules/@satorijs/protocol/package.json +44 -0
- package/node_modules/@satorijs/protocol/src/index.ts +513 -0
- package/node_modules/@standard-schema/spec/LICENSE +21 -0
- package/node_modules/@standard-schema/spec/README.md +198 -0
- package/node_modules/@standard-schema/spec/dist/index.cjs +18 -0
- package/node_modules/@standard-schema/spec/dist/index.d.cts +119 -0
- package/node_modules/@standard-schema/spec/dist/index.d.ts +119 -0
- package/node_modules/@standard-schema/spec/dist/index.js +0 -0
- package/node_modules/@standard-schema/spec/package.json +52 -0
- package/node_modules/cordis/README.md +10 -0
- package/node_modules/cordis/bin.js +16 -0
- package/node_modules/cordis/lib/context.d.ts +32 -0
- package/node_modules/cordis/lib/events.d.ts +62 -0
- package/node_modules/cordis/lib/fiber.d.ts +85 -0
- package/node_modules/cordis/lib/index.d.ts +7 -0
- package/node_modules/cordis/lib/index.js +1577 -0
- package/node_modules/cordis/lib/logger.d.ts +74 -0
- package/node_modules/cordis/lib/reflect.d.ts +54 -0
- package/node_modules/cordis/lib/registry.d.ts +78 -0
- package/node_modules/cordis/lib/service.d.ts +19 -0
- package/node_modules/cordis/lib/utils.d.ts +50 -0
- package/node_modules/cordis/package.json +49 -0
- package/node_modules/cosmokit/LICENSE +21 -0
- package/node_modules/cosmokit/README.md +24 -0
- package/node_modules/cosmokit/lib/index.cjs +419 -0
- package/node_modules/cosmokit/lib/index.cjs.map +6 -0
- package/node_modules/cosmokit/lib/index.d.ts +142 -0
- package/node_modules/cosmokit/lib/index.mjs +357 -0
- package/node_modules/cosmokit/lib/index.mjs.map +6 -0
- package/node_modules/cosmokit/package.json +57 -0
- package/node_modules/cosmokit/src/array.ts +35 -0
- package/node_modules/cosmokit/src/index.ts +5 -0
- package/node_modules/cosmokit/src/misc.ts +57 -0
- package/node_modules/cosmokit/src/string.ts +101 -0
- package/node_modules/cosmokit/src/time.ts +91 -0
- package/node_modules/cosmokit/src/types.ts +131 -0
- package/node_modules/schemastery/README.md +342 -0
- package/node_modules/schemastery/lib/index.cjs +648 -0
- package/node_modules/schemastery/lib/index.cjs.map +6 -0
- package/node_modules/schemastery/lib/index.d.ts +138 -0
- package/node_modules/schemastery/lib/index.mjs +656 -0
- package/node_modules/schemastery/lib/index.mjs.map +6 -0
- package/node_modules/schemastery/package.json +32 -0
- package/node_modules/schemastery/src/index.ts +841 -0
- package/node_modules/undici/LICENSE +21 -0
- package/node_modules/undici/README.md +741 -0
- package/node_modules/undici/docs/docs/api/Agent.md +84 -0
- package/node_modules/undici/docs/docs/api/BalancedPool.md +99 -0
- package/node_modules/undici/docs/docs/api/CacheStorage.md +30 -0
- package/node_modules/undici/docs/docs/api/CacheStore.md +164 -0
- package/node_modules/undici/docs/docs/api/Client.md +290 -0
- package/node_modules/undici/docs/docs/api/ClientStats.md +27 -0
- package/node_modules/undici/docs/docs/api/Connector.md +115 -0
- package/node_modules/undici/docs/docs/api/ContentType.md +57 -0
- package/node_modules/undici/docs/docs/api/Cookies.md +128 -0
- package/node_modules/undici/docs/docs/api/Debug.md +62 -0
- package/node_modules/undici/docs/docs/api/DiagnosticsChannel.md +317 -0
- package/node_modules/undici/docs/docs/api/Dispatcher.md +1393 -0
- package/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md +159 -0
- package/node_modules/undici/docs/docs/api/Errors.md +49 -0
- package/node_modules/undici/docs/docs/api/EventSource.md +45 -0
- package/node_modules/undici/docs/docs/api/Fetch.md +60 -0
- package/node_modules/undici/docs/docs/api/GlobalInstallation.md +139 -0
- package/node_modules/undici/docs/docs/api/H2CClient.md +263 -0
- package/node_modules/undici/docs/docs/api/MockAgent.md +603 -0
- package/node_modules/undici/docs/docs/api/MockCallHistory.md +197 -0
- package/node_modules/undici/docs/docs/api/MockCallHistoryLog.md +43 -0
- package/node_modules/undici/docs/docs/api/MockClient.md +81 -0
- package/node_modules/undici/docs/docs/api/MockErrors.md +12 -0
- package/node_modules/undici/docs/docs/api/MockPool.md +555 -0
- package/node_modules/undici/docs/docs/api/Pool.md +84 -0
- package/node_modules/undici/docs/docs/api/PoolStats.md +35 -0
- package/node_modules/undici/docs/docs/api/ProxyAgent.md +229 -0
- package/node_modules/undici/docs/docs/api/RedirectHandler.md +93 -0
- package/node_modules/undici/docs/docs/api/RetryAgent.md +50 -0
- package/node_modules/undici/docs/docs/api/RetryHandler.md +118 -0
- package/node_modules/undici/docs/docs/api/RoundRobinPool.md +145 -0
- package/node_modules/undici/docs/docs/api/SnapshotAgent.md +616 -0
- package/node_modules/undici/docs/docs/api/Socks5ProxyAgent.md +275 -0
- package/node_modules/undici/docs/docs/api/Util.md +25 -0
- package/node_modules/undici/docs/docs/api/WebSocket.md +141 -0
- package/node_modules/undici/docs/docs/api/api-lifecycle.md +91 -0
- package/node_modules/undici/docs/docs/best-practices/client-certificate.md +64 -0
- package/node_modules/undici/docs/docs/best-practices/crawling.md +58 -0
- package/node_modules/undici/docs/docs/best-practices/mocking-request.md +190 -0
- package/node_modules/undici/docs/docs/best-practices/proxy.md +127 -0
- package/node_modules/undici/docs/docs/best-practices/undici-vs-builtin-fetch.md +224 -0
- package/node_modules/undici/docs/docs/best-practices/writing-tests.md +63 -0
- package/node_modules/undici/index-fetch.js +65 -0
- package/node_modules/undici/index.d.ts +3 -0
- package/node_modules/undici/index.js +234 -0
- package/node_modules/undici/lib/api/abort-signal.js +59 -0
- package/node_modules/undici/lib/api/api-connect.js +110 -0
- package/node_modules/undici/lib/api/api-pipeline.js +252 -0
- package/node_modules/undici/lib/api/api-request.js +214 -0
- package/node_modules/undici/lib/api/api-stream.js +209 -0
- package/node_modules/undici/lib/api/api-upgrade.js +111 -0
- package/node_modules/undici/lib/api/index.js +7 -0
- package/node_modules/undici/lib/api/readable.js +580 -0
- package/node_modules/undici/lib/cache/memory-cache-store.js +279 -0
- package/node_modules/undici/lib/cache/sqlite-cache-store.js +467 -0
- package/node_modules/undici/lib/core/connect.js +159 -0
- package/node_modules/undici/lib/core/constants.js +143 -0
- package/node_modules/undici/lib/core/diagnostics.js +227 -0
- package/node_modules/undici/lib/core/errors.js +477 -0
- package/node_modules/undici/lib/core/request.js +485 -0
- package/node_modules/undici/lib/core/socks5-client.js +422 -0
- package/node_modules/undici/lib/core/socks5-utils.js +212 -0
- package/node_modules/undici/lib/core/symbols.js +76 -0
- package/node_modules/undici/lib/core/tree.js +160 -0
- package/node_modules/undici/lib/core/util.js +992 -0
- package/node_modules/undici/lib/dispatcher/agent.js +162 -0
- package/node_modules/undici/lib/dispatcher/balanced-pool.js +221 -0
- package/node_modules/undici/lib/dispatcher/client-h1.js +1744 -0
- package/node_modules/undici/lib/dispatcher/client-h2.js +1056 -0
- package/node_modules/undici/lib/dispatcher/client.js +669 -0
- package/node_modules/undici/lib/dispatcher/dispatcher-base.js +196 -0
- package/node_modules/undici/lib/dispatcher/dispatcher.js +48 -0
- package/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js +146 -0
- package/node_modules/undici/lib/dispatcher/fixed-queue.js +135 -0
- package/node_modules/undici/lib/dispatcher/h2c-client.js +51 -0
- package/node_modules/undici/lib/dispatcher/pool-base.js +214 -0
- package/node_modules/undici/lib/dispatcher/pool.js +118 -0
- package/node_modules/undici/lib/dispatcher/proxy-agent.js +319 -0
- package/node_modules/undici/lib/dispatcher/retry-agent.js +35 -0
- package/node_modules/undici/lib/dispatcher/round-robin-pool.js +137 -0
- package/node_modules/undici/lib/dispatcher/socks5-proxy-agent.js +260 -0
- package/node_modules/undici/lib/encoding/index.js +33 -0
- package/node_modules/undici/lib/global.js +59 -0
- package/node_modules/undici/lib/handler/cache-handler.js +824 -0
- package/node_modules/undici/lib/handler/cache-revalidation-handler.js +124 -0
- package/node_modules/undici/lib/handler/decorator-handler.js +67 -0
- package/node_modules/undici/lib/handler/deduplication-handler.js +504 -0
- package/node_modules/undici/lib/handler/redirect-handler.js +245 -0
- package/node_modules/undici/lib/handler/retry-handler.js +504 -0
- package/node_modules/undici/lib/handler/unwrap-handler.js +106 -0
- package/node_modules/undici/lib/handler/wrap-handler.js +105 -0
- package/node_modules/undici/lib/interceptor/cache.js +621 -0
- package/node_modules/undici/lib/interceptor/decompress.js +561 -0
- package/node_modules/undici/lib/interceptor/deduplicate.js +117 -0
- package/node_modules/undici/lib/interceptor/dns.js +571 -0
- package/node_modules/undici/lib/interceptor/dump.js +99 -0
- package/node_modules/undici/lib/interceptor/redirect.js +21 -0
- package/node_modules/undici/lib/interceptor/response-error.js +95 -0
- package/node_modules/undici/lib/interceptor/retry.js +19 -0
- package/node_modules/undici/lib/llhttp/constants.d.ts +195 -0
- package/node_modules/undici/lib/llhttp/constants.js +531 -0
- package/node_modules/undici/lib/llhttp/llhttp-wasm.js +15 -0
- package/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js +15 -0
- package/node_modules/undici/lib/llhttp/utils.d.ts +2 -0
- package/node_modules/undici/lib/llhttp/utils.js +12 -0
- package/node_modules/undici/lib/mock/mock-agent.js +232 -0
- package/node_modules/undici/lib/mock/mock-call-history.js +248 -0
- package/node_modules/undici/lib/mock/mock-client.js +68 -0
- package/node_modules/undici/lib/mock/mock-errors.js +29 -0
- package/node_modules/undici/lib/mock/mock-interceptor.js +209 -0
- package/node_modules/undici/lib/mock/mock-pool.js +68 -0
- package/node_modules/undici/lib/mock/mock-symbols.js +32 -0
- package/node_modules/undici/lib/mock/mock-utils.js +486 -0
- package/node_modules/undici/lib/mock/pending-interceptors-formatter.js +43 -0
- package/node_modules/undici/lib/mock/snapshot-agent.js +353 -0
- package/node_modules/undici/lib/mock/snapshot-recorder.js +588 -0
- package/node_modules/undici/lib/mock/snapshot-utils.js +158 -0
- package/node_modules/undici/lib/util/cache.js +676 -0
- package/node_modules/undici/lib/util/date.js +670 -0
- package/node_modules/undici/lib/util/promise.js +28 -0
- package/node_modules/undici/lib/util/runtime-features.js +124 -0
- package/node_modules/undici/lib/util/stats.js +32 -0
- package/node_modules/undici/lib/util/timers.js +425 -0
- package/node_modules/undici/lib/web/cache/cache.js +864 -0
- package/node_modules/undici/lib/web/cache/cachestorage.js +152 -0
- package/node_modules/undici/lib/web/cache/util.js +45 -0
- package/node_modules/undici/lib/web/cookies/constants.js +12 -0
- package/node_modules/undici/lib/web/cookies/index.js +201 -0
- package/node_modules/undici/lib/web/cookies/parse.js +315 -0
- package/node_modules/undici/lib/web/cookies/util.js +371 -0
- package/node_modules/undici/lib/web/eventsource/eventsource-stream.js +575 -0
- package/node_modules/undici/lib/web/eventsource/eventsource.js +504 -0
- package/node_modules/undici/lib/web/eventsource/util.js +29 -0
- package/node_modules/undici/lib/web/fetch/LICENSE +21 -0
- package/node_modules/undici/lib/web/fetch/body.js +509 -0
- package/node_modules/undici/lib/web/fetch/constants.js +131 -0
- package/node_modules/undici/lib/web/fetch/data-url.js +596 -0
- package/node_modules/undici/lib/web/fetch/formdata-parser.js +586 -0
- package/node_modules/undici/lib/web/fetch/formdata.js +259 -0
- package/node_modules/undici/lib/web/fetch/global.js +40 -0
- package/node_modules/undici/lib/web/fetch/headers.js +719 -0
- package/node_modules/undici/lib/web/fetch/index.js +2413 -0
- package/node_modules/undici/lib/web/fetch/request.js +1115 -0
- package/node_modules/undici/lib/web/fetch/response.js +641 -0
- package/node_modules/undici/lib/web/fetch/util.js +1522 -0
- package/node_modules/undici/lib/web/infra/index.js +243 -0
- package/node_modules/undici/lib/web/subresource-integrity/Readme.md +9 -0
- package/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js +307 -0
- package/node_modules/undici/lib/web/webidl/index.js +1006 -0
- package/node_modules/undici/lib/web/websocket/connection.js +339 -0
- package/node_modules/undici/lib/web/websocket/constants.js +126 -0
- package/node_modules/undici/lib/web/websocket/events.js +331 -0
- package/node_modules/undici/lib/web/websocket/frame.js +133 -0
- package/node_modules/undici/lib/web/websocket/permessage-deflate.js +105 -0
- package/node_modules/undici/lib/web/websocket/receiver.js +520 -0
- package/node_modules/undici/lib/web/websocket/sender.js +109 -0
- package/node_modules/undici/lib/web/websocket/stream/websocketerror.js +104 -0
- package/node_modules/undici/lib/web/websocket/stream/websocketstream.js +496 -0
- package/node_modules/undici/lib/web/websocket/util.js +347 -0
- package/node_modules/undici/lib/web/websocket/websocket.js +758 -0
- package/node_modules/undici/package.json +152 -0
- package/node_modules/undici/scripts/strip-comments.js +10 -0
- package/node_modules/undici/types/README.md +6 -0
- package/node_modules/undici/types/agent.d.ts +32 -0
- package/node_modules/undici/types/api.d.ts +43 -0
- package/node_modules/undici/types/balanced-pool.d.ts +30 -0
- package/node_modules/undici/types/cache-interceptor.d.ts +179 -0
- package/node_modules/undici/types/cache.d.ts +36 -0
- package/node_modules/undici/types/client-stats.d.ts +15 -0
- package/node_modules/undici/types/client.d.ts +153 -0
- package/node_modules/undici/types/connector.d.ts +36 -0
- package/node_modules/undici/types/content-type.d.ts +21 -0
- package/node_modules/undici/types/cookies.d.ts +30 -0
- package/node_modules/undici/types/diagnostics-channel.d.ts +74 -0
- package/node_modules/undici/types/dispatcher.d.ts +275 -0
- package/node_modules/undici/types/env-http-proxy-agent.d.ts +22 -0
- package/node_modules/undici/types/errors.d.ts +177 -0
- package/node_modules/undici/types/eventsource.d.ts +66 -0
- package/node_modules/undici/types/fetch.d.ts +231 -0
- package/node_modules/undici/types/formdata.d.ts +114 -0
- package/node_modules/undici/types/global-dispatcher.d.ts +9 -0
- package/node_modules/undici/types/global-origin.d.ts +7 -0
- package/node_modules/undici/types/h2c-client.d.ts +73 -0
- package/node_modules/undici/types/handlers.d.ts +14 -0
- package/node_modules/undici/types/header.d.ts +160 -0
- package/node_modules/undici/types/index.d.ts +91 -0
- package/node_modules/undici/types/interceptors.d.ts +82 -0
- package/node_modules/undici/types/mock-agent.d.ts +68 -0
- package/node_modules/undici/types/mock-call-history.d.ts +111 -0
- package/node_modules/undici/types/mock-client.d.ts +27 -0
- package/node_modules/undici/types/mock-errors.d.ts +12 -0
- package/node_modules/undici/types/mock-interceptor.d.ts +94 -0
- package/node_modules/undici/types/mock-pool.d.ts +27 -0
- package/node_modules/undici/types/patch.d.ts +29 -0
- package/node_modules/undici/types/pool-stats.d.ts +19 -0
- package/node_modules/undici/types/pool.d.ts +41 -0
- package/node_modules/undici/types/proxy-agent.d.ts +29 -0
- package/node_modules/undici/types/readable.d.ts +68 -0
- package/node_modules/undici/types/retry-agent.d.ts +8 -0
- package/node_modules/undici/types/retry-handler.d.ts +125 -0
- package/node_modules/undici/types/round-robin-pool.d.ts +41 -0
- package/node_modules/undici/types/snapshot-agent.d.ts +109 -0
- package/node_modules/undici/types/socks5-proxy-agent.d.ts +25 -0
- package/node_modules/undici/types/util.d.ts +18 -0
- package/node_modules/undici/types/utility.d.ts +7 -0
- package/node_modules/undici/types/webidl.d.ts +347 -0
- package/node_modules/undici/types/websocket.d.ts +188 -0
- package/node_modules/ws/LICENSE +20 -0
- package/node_modules/ws/README.md +548 -0
- package/node_modules/ws/browser.js +8 -0
- package/node_modules/ws/index.js +22 -0
- package/node_modules/ws/lib/buffer-util.js +131 -0
- package/node_modules/ws/lib/constants.js +19 -0
- package/node_modules/ws/lib/event-target.js +292 -0
- package/node_modules/ws/lib/extension.js +203 -0
- package/node_modules/ws/lib/limiter.js +55 -0
- package/node_modules/ws/lib/permessage-deflate.js +530 -0
- package/node_modules/ws/lib/receiver.js +743 -0
- package/node_modules/ws/lib/sender.js +607 -0
- package/node_modules/ws/lib/stream.js +161 -0
- package/node_modules/ws/lib/subprotocol.js +62 -0
- package/node_modules/ws/lib/validation.js +152 -0
- package/node_modules/ws/lib/websocket-server.js +562 -0
- package/node_modules/ws/lib/websocket.js +1407 -0
- package/node_modules/ws/package.json +74 -0
- package/node_modules/ws/wrapper.mjs +21 -0
- package/package.json +17 -4
- package/webui/assets/group-bot-profile-CYK81678.jpg +0 -0
- package/webui/assets/group-bot-settings-BBQBbfgh.jpg +0 -0
- package/webui/assets/index-CuH0UYYo.js +28 -0
- package/webui/assets/index-DjbPiYmB.css +2 -0
- package/webui/favicon.ico +0 -0
- package/webui/index.html +26 -0
- package/webui/logo-128.webp +0 -0
- package/webui/logo-192.webp +0 -0
- package/webui/logo-256.webp +0 -0
- package/webui/logo-64.webp +0 -0
- package/webui/logo.jpg +0 -0
- package/webui/plugin-shared/plugin-sdk-webui.js +3 -0
- package/webui/plugin-shared/react-dom.js +3 -0
- package/webui/plugin-shared/react-jsx-runtime.js +3 -0
- package/webui/plugin-shared/react.js +3 -0
- package//344/275/277/347/224/250/350/257/264/346/230/216.txt +6 -0
- package//346/233/264/346/226/260/346/227/245/345/277/227.txt +1091 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1123 @@
|
|
|
1
|
+
// src/universal/testing.ts
|
|
2
|
+
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import h4 from "@satorijs/element";
|
|
6
|
+
import { Channel as Channel2 } from "@satorijs/protocol";
|
|
7
|
+
import { Context as Context4 } from "cordis";
|
|
8
|
+
import TimerService from "@cordisjs/plugin-timer";
|
|
9
|
+
|
|
10
|
+
// src/universal/bots.ts
|
|
11
|
+
import { Service } from "cordis";
|
|
12
|
+
|
|
13
|
+
// src/universal/fallback.ts
|
|
14
|
+
import h from "@satorijs/element";
|
|
15
|
+
var FEATURES = {
|
|
16
|
+
markdown: "message.markdown",
|
|
17
|
+
button: "message.button",
|
|
18
|
+
"button-group": "message.button",
|
|
19
|
+
card: "message.card",
|
|
20
|
+
face: "message.face"
|
|
21
|
+
};
|
|
22
|
+
var isRecord = (value) => typeof value === "object" && value !== null;
|
|
23
|
+
var str = (value) => typeof value === "string" ? value : value === void 0 || value === null ? "" : String(value);
|
|
24
|
+
async function applyFallbacks(ctx, bot, channelId, content, plugins = true) {
|
|
25
|
+
const features = new Set(bot.features ?? []);
|
|
26
|
+
const visit = async (elements) => {
|
|
27
|
+
const out = [];
|
|
28
|
+
for (const element of features.has("message.button") ? elements : groupButtons(elements)) {
|
|
29
|
+
const feature = FEATURES[element.type];
|
|
30
|
+
if (!feature || features.has(feature)) {
|
|
31
|
+
out.push(element.children.length ? h(element.type, element.attrs, await visit(element.children)) : element);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const custom = plugins ? await ctx.serial("bot/fallback", bot, channelId, element) : void 0;
|
|
35
|
+
out.push(...custom === void 0 ? await visit(fallback(element)) : h.normalize(custom));
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
};
|
|
39
|
+
return await visit(content);
|
|
40
|
+
}
|
|
41
|
+
function groupButtons(elements) {
|
|
42
|
+
const out = [];
|
|
43
|
+
let row = [];
|
|
44
|
+
let blanks = [];
|
|
45
|
+
const close = () => {
|
|
46
|
+
if (row.length) out.push(h("button-group", {}, row));
|
|
47
|
+
out.push(...blanks);
|
|
48
|
+
row = [];
|
|
49
|
+
blanks = [];
|
|
50
|
+
};
|
|
51
|
+
for (const element of elements) {
|
|
52
|
+
if (element.type === "button") {
|
|
53
|
+
row.push(element);
|
|
54
|
+
blanks = [];
|
|
55
|
+
} else if (row.length && element.type === "text" && !str(element.attrs.content).trim()) {
|
|
56
|
+
blanks.push(element);
|
|
57
|
+
} else {
|
|
58
|
+
close();
|
|
59
|
+
out.push(element);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
close();
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
function fallback(element) {
|
|
66
|
+
const { type, attrs, children } = element;
|
|
67
|
+
if (type === "markdown") return markdownToElements(typeof attrs.content === "string" ? attrs.content : sourceOf(children));
|
|
68
|
+
if (type === "button" || type === "button-group") {
|
|
69
|
+
const items = (type === "button" ? [element] : children).map(buttonFallback).filter((item) => !!item);
|
|
70
|
+
if (!items.length) return [];
|
|
71
|
+
return [h("p", {}, items.flatMap((item, index) => index ? [h.text(" "), item] : [item]))];
|
|
72
|
+
}
|
|
73
|
+
if (type === "card") return cardFallback(attrs);
|
|
74
|
+
if (type === "face") return [h.text(`[${str(attrs.name) || "\u8868\u60C5"}]`)];
|
|
75
|
+
return children;
|
|
76
|
+
}
|
|
77
|
+
function sourceOf(children) {
|
|
78
|
+
let source = "";
|
|
79
|
+
for (const child of children) {
|
|
80
|
+
if (child.type === "text") source += str(child.attrs.content);
|
|
81
|
+
else if (child.type === "br") source += "\n";
|
|
82
|
+
else if (child.type === "p") source += (source && !source.endsWith("\n") ? "\n" : "") + sourceOf(child.children) + "\n";
|
|
83
|
+
else source += sourceOf(child.children);
|
|
84
|
+
}
|
|
85
|
+
return source;
|
|
86
|
+
}
|
|
87
|
+
function textOf(children) {
|
|
88
|
+
return children.map((child) => child.type === "text" ? str(child.attrs.content) : textOf(child.children)).join("");
|
|
89
|
+
}
|
|
90
|
+
function buttonFallback(button) {
|
|
91
|
+
if (button.type !== "button") return;
|
|
92
|
+
const attrs = button.attrs;
|
|
93
|
+
const action = isRecord(attrs.action) ? attrs.action : {};
|
|
94
|
+
const render = isRecord(attrs.renderData) ? attrs.renderData : isRecord(attrs.render_data) ? attrs.render_data : {};
|
|
95
|
+
const type = attrs.type ?? action.type;
|
|
96
|
+
const label = textOf(button.children).trim() || str(render.label) || str(attrs.text);
|
|
97
|
+
if (type === "link" || type === 0) {
|
|
98
|
+
const href = str(attrs.href ?? action.data);
|
|
99
|
+
if (!href) return;
|
|
100
|
+
return label && label !== href ? h("a", { href }, label) : h.text(href);
|
|
101
|
+
}
|
|
102
|
+
if (type === "action" || type === 1) return;
|
|
103
|
+
const data = str(attrs.data ?? action.data) || str(attrs.text) || label || str(attrs.id);
|
|
104
|
+
if (!data) return;
|
|
105
|
+
return h.text(label && label !== data ? `${label}\uFF08\u53D1\u9001\u300C${data}\u300D\uFF09` : `\u300C${data}\u300D`);
|
|
106
|
+
}
|
|
107
|
+
function cardFallback(attrs) {
|
|
108
|
+
const title = str(attrs.title);
|
|
109
|
+
const url = str(attrs.url);
|
|
110
|
+
const desc = str(attrs.desc);
|
|
111
|
+
const image = str(attrs.image);
|
|
112
|
+
const out = [];
|
|
113
|
+
if (title) out.push(h("p", {}, url && url !== title ? h("a", { href: url }, title) : title));
|
|
114
|
+
else if (url) out.push(h("p", {}, url));
|
|
115
|
+
if (desc) out.push(h("p", {}, desc));
|
|
116
|
+
if (image) out.push(h.image(image));
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
var INLINE = /\\([\\`*_{}[\]()#+\-.!~|<>])|!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)|\[([^\]]+)\]\(\s*<?([^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)|<(https?:\/\/[^>\s]+)>|`([^`]+)`|\*\*(.+?)\*\*|__(.+?)__|~~(.+?)~~|\*(?!\s)(.+?)\*|(?<![\w\\])_(?!\s)(.+?)_(?!\w)/g;
|
|
120
|
+
function inline(text) {
|
|
121
|
+
const out = [];
|
|
122
|
+
const append = (content) => {
|
|
123
|
+
const last2 = out[out.length - 1];
|
|
124
|
+
if (last2?.type === "text") out[out.length - 1] = h.text(str(last2.attrs.content) + content);
|
|
125
|
+
else out.push(h.text(content));
|
|
126
|
+
};
|
|
127
|
+
let last = 0;
|
|
128
|
+
for (const match of text.matchAll(INLINE)) {
|
|
129
|
+
if (match.index > last) append(text.slice(last, match.index));
|
|
130
|
+
last = match.index + match[0].length;
|
|
131
|
+
const [, escaped, , image, label, href, autolink, code, bold, boldAlt, strike, italic, italicAlt] = match;
|
|
132
|
+
if (escaped !== void 0) append(escaped);
|
|
133
|
+
else if (image !== void 0) out.push(h.image(image));
|
|
134
|
+
else if (href !== void 0) {
|
|
135
|
+
if (label === href) append(href);
|
|
136
|
+
else out.push(h("a", { href }, inline(label)));
|
|
137
|
+
} else if (autolink !== void 0) append(autolink);
|
|
138
|
+
else if (code !== void 0) out.push(h("code", {}, code));
|
|
139
|
+
else if ((bold ?? boldAlt) !== void 0) out.push(h("b", {}, inline(bold ?? boldAlt)));
|
|
140
|
+
else if (strike !== void 0) out.push(h("s", {}, inline(strike)));
|
|
141
|
+
else out.push(h("i", {}, inline(italic ?? italicAlt)));
|
|
142
|
+
}
|
|
143
|
+
if (last < text.length) append(text.slice(last));
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
function markdownToElements(source) {
|
|
147
|
+
const blocks = [];
|
|
148
|
+
let paragraph = [];
|
|
149
|
+
const endParagraph = () => {
|
|
150
|
+
if (paragraph.length) blocks.push(h("p", {}, paragraph));
|
|
151
|
+
paragraph = [];
|
|
152
|
+
};
|
|
153
|
+
const lines = source.replace(/\r\n?/g, "\n").split("\n");
|
|
154
|
+
for (let i = 0; i < lines.length; i++) {
|
|
155
|
+
const line = lines[i];
|
|
156
|
+
const fence = /^\s*(```|~~~)/.exec(line);
|
|
157
|
+
if (fence) {
|
|
158
|
+
endParagraph();
|
|
159
|
+
const code = [];
|
|
160
|
+
while (++i < lines.length && !lines[i].trimStart().startsWith(fence[1])) code.push(lines[i]);
|
|
161
|
+
if (code.length) blocks.push(h("p", {}, h("code", {}, code.join("\n"))));
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (!line.trim()) {
|
|
165
|
+
endParagraph();
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const heading = /^\s{0,3}#{1,6}\s+(.*?)(?:\s+#+)?\s*$/.exec(line);
|
|
169
|
+
const rule = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(line);
|
|
170
|
+
const quote = /^\s{0,3}>\s?(.*)$/.exec(line);
|
|
171
|
+
const item = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
|
|
172
|
+
if (heading || rule || quote || item) endParagraph();
|
|
173
|
+
if (heading) blocks.push(h("p", {}, h("b", {}, inline(heading[1]))));
|
|
174
|
+
else if (rule) blocks.push(h("p", {}, "\u2014\u2014\u2014\u2014\u2014\u2014"));
|
|
175
|
+
else if (quote) blocks.push(h("p", {}, [h.text("\uFF5C"), ...inline(quote[1])]));
|
|
176
|
+
else if (item) {
|
|
177
|
+
const marker = /\d/.test(item[2]) ? item[2] : "\u2022";
|
|
178
|
+
blocks.push(h("p", {}, [h.text(`${" ".repeat(Math.floor(item[1].length / 2))}${marker} `), ...inline(item[3])]));
|
|
179
|
+
} else {
|
|
180
|
+
if (paragraph.length) paragraph.push(h("br"));
|
|
181
|
+
paragraph.push(...inline(line.trim()));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
endParagraph();
|
|
185
|
+
return blocks;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/universal/session.ts
|
|
189
|
+
import h2 from "@satorijs/element";
|
|
190
|
+
import { Channel } from "@satorijs/protocol";
|
|
191
|
+
var Session = class {
|
|
192
|
+
constructor(bot, event, bots) {
|
|
193
|
+
this.bot = bot;
|
|
194
|
+
this.event = event;
|
|
195
|
+
this.bots = bots;
|
|
196
|
+
}
|
|
197
|
+
bot;
|
|
198
|
+
event;
|
|
199
|
+
bots;
|
|
200
|
+
parsed;
|
|
201
|
+
strippedCache;
|
|
202
|
+
get type() {
|
|
203
|
+
return this.event.type;
|
|
204
|
+
}
|
|
205
|
+
get platform() {
|
|
206
|
+
return this.event.platform;
|
|
207
|
+
}
|
|
208
|
+
get selfId() {
|
|
209
|
+
return this.event.self_id;
|
|
210
|
+
}
|
|
211
|
+
get timestamp() {
|
|
212
|
+
return this.event.timestamp;
|
|
213
|
+
}
|
|
214
|
+
get userId() {
|
|
215
|
+
return this.event.user?.id ?? this.event.member?.user?.id;
|
|
216
|
+
}
|
|
217
|
+
get channelId() {
|
|
218
|
+
return this.event.channel?.id;
|
|
219
|
+
}
|
|
220
|
+
get guildId() {
|
|
221
|
+
return this.event.guild?.id;
|
|
222
|
+
}
|
|
223
|
+
get messageId() {
|
|
224
|
+
return this.event.message?.id;
|
|
225
|
+
}
|
|
226
|
+
get isDirect() {
|
|
227
|
+
return this.event.channel?.type === Channel.Type.DIRECT;
|
|
228
|
+
}
|
|
229
|
+
get content() {
|
|
230
|
+
return this.event.message?.content ?? "";
|
|
231
|
+
}
|
|
232
|
+
get elements() {
|
|
233
|
+
return this.parsed ??= h2.parse(this.content);
|
|
234
|
+
}
|
|
235
|
+
get stripped() {
|
|
236
|
+
if (this.strippedCache) return this.strippedCache;
|
|
237
|
+
const rest = this.elements.slice();
|
|
238
|
+
const blank = (element) => element.type === "text" && !String(element.attrs.content ?? "").trim();
|
|
239
|
+
while (rest.length && (rest[0].type === "quote" || blank(rest[0]))) rest.shift();
|
|
240
|
+
const atSelf = rest[0]?.type === "at" && rest[0].attrs.id === this.selfId;
|
|
241
|
+
if (atSelf) rest.shift();
|
|
242
|
+
if (rest[0]?.type === "text") {
|
|
243
|
+
const text = String(rest[0].attrs.content ?? "").trimStart();
|
|
244
|
+
if (text) rest[0] = h2.text(text);
|
|
245
|
+
else rest.shift();
|
|
246
|
+
}
|
|
247
|
+
return this.strippedCache = { content: rest.join(""), atSelf };
|
|
248
|
+
}
|
|
249
|
+
send(content) {
|
|
250
|
+
return this.bot.sendMessage(this.requireChannel(), content, { referrer: this.event.referrer });
|
|
251
|
+
}
|
|
252
|
+
reply(content) {
|
|
253
|
+
return this.bot.sendMessage(this.requireChannel(), content, { quote: this.messageId, referrer: this.event.referrer });
|
|
254
|
+
}
|
|
255
|
+
sendQueued(content, delay) {
|
|
256
|
+
if (!this.bots) return this.send(content);
|
|
257
|
+
return this.bots.sendQueued(this.bot, this.requireChannel(), content, { referrer: this.event.referrer }, delay);
|
|
258
|
+
}
|
|
259
|
+
async prompt(timeout) {
|
|
260
|
+
this.requireChannel();
|
|
261
|
+
if (!this.bots || !this.userId) return;
|
|
262
|
+
return (await this.bots.prompt(this, timeout))?.stripped.content;
|
|
263
|
+
}
|
|
264
|
+
requireChannel() {
|
|
265
|
+
if (!this.channelId) throw new Error(`a ${this.type} event has no channel to send to`);
|
|
266
|
+
return this.channelId;
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
// src/universal/bots.ts
|
|
271
|
+
var PROMPT_TIMEOUT = 6e4;
|
|
272
|
+
var QUEUE_DELAY = 1e3;
|
|
273
|
+
var placeKey = (place) => [place.platform, place.selfId, place.channelId, place.userId].join("\n");
|
|
274
|
+
var BotsService = class extends Service {
|
|
275
|
+
registry = /* @__PURE__ */ new Map();
|
|
276
|
+
state = {};
|
|
277
|
+
prompts = /* @__PURE__ */ new Map();
|
|
278
|
+
queues = /* @__PURE__ */ new Map();
|
|
279
|
+
constructor(ctx) {
|
|
280
|
+
super(ctx, "bots");
|
|
281
|
+
ctx.effect(() => () => {
|
|
282
|
+
for (const resolve2 of this.prompts.values()) resolve2(void 0);
|
|
283
|
+
this.prompts.clear();
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
get size() {
|
|
287
|
+
return this.registry.size;
|
|
288
|
+
}
|
|
289
|
+
get(sid) {
|
|
290
|
+
return this.registry.get(sid);
|
|
291
|
+
}
|
|
292
|
+
[Symbol.iterator]() {
|
|
293
|
+
return this.registry.values();
|
|
294
|
+
}
|
|
295
|
+
register(bot) {
|
|
296
|
+
const ctx = this.ctx;
|
|
297
|
+
return ctx.effect(() => {
|
|
298
|
+
if (this.registry.has(bot.sid)) throw new Error(`bot ${bot.sid} is already registered`);
|
|
299
|
+
this.registry.set(bot.sid, bot);
|
|
300
|
+
ctx.parallel("bot/status", bot).catch((e) => ctx.logger("bots").warn(e));
|
|
301
|
+
return () => {
|
|
302
|
+
if (this.registry.get(bot.sid) !== bot) return;
|
|
303
|
+
this.registry.delete(bot.sid);
|
|
304
|
+
return ctx.parallel("bot/status", bot).catch((e) => ctx.logger("bots").warn(e));
|
|
305
|
+
};
|
|
306
|
+
}, `bots.register(${bot.sid})`);
|
|
307
|
+
}
|
|
308
|
+
/** For the plugin host: until the returned function runs, `policy` places every listener. */
|
|
309
|
+
usePolicy(policy) {
|
|
310
|
+
this.state.policy = policy;
|
|
311
|
+
return () => {
|
|
312
|
+
if (this.state.policy === policy) this.state.policy = void 0;
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/** The entry a context belongs to, by the policy; undefined for the bot's own code. */
|
|
316
|
+
ownerOf(ctx) {
|
|
317
|
+
return this.state.policy?.owner(ctx);
|
|
318
|
+
}
|
|
319
|
+
/** Notes against the plugin `ctx` belongs to that its code for an event threw, e.g. a command's action. */
|
|
320
|
+
reportFailure(ctx, error) {
|
|
321
|
+
const owner = this.ownerOf(ctx);
|
|
322
|
+
if (owner !== void 0) this.state.policy.failed(owner, error);
|
|
323
|
+
}
|
|
324
|
+
/** Whether the plugin `ctx` belongs to takes events from `place`. */
|
|
325
|
+
allows(ctx, place) {
|
|
326
|
+
const owner = this.ownerOf(ctx);
|
|
327
|
+
return owner === void 0 || this.state.policy.accepts(owner, place);
|
|
328
|
+
}
|
|
329
|
+
async dispatch(bot, event) {
|
|
330
|
+
const session = new Session(bot, event, this);
|
|
331
|
+
const tap = this.fanOut("bot/session", session, [session]);
|
|
332
|
+
if (event.type === "message-created" && session.userId !== session.selfId) {
|
|
333
|
+
const waiting = this.prompts.get(placeKey(session));
|
|
334
|
+
if (waiting) {
|
|
335
|
+
this.prompts.delete(placeKey(session));
|
|
336
|
+
waiting(session);
|
|
337
|
+
} else {
|
|
338
|
+
await this.chain("bot/message", session, [session], async () => {
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
} else {
|
|
342
|
+
await this.fanOut("bot/event", session, [session]);
|
|
343
|
+
}
|
|
344
|
+
await tap;
|
|
345
|
+
}
|
|
346
|
+
async beforeSend(bot, channelId, content, options = {}) {
|
|
347
|
+
if (options.relay) return await applyFallbacks(this.ctx, bot, channelId, content, false);
|
|
348
|
+
const place = { platform: bot.platform, selfId: bot.selfId, channelId, isDirect: channelId.startsWith("private:") };
|
|
349
|
+
const outgoing = await this.chain("bot/before-send", place, [bot, channelId, content], async () => content, false);
|
|
350
|
+
return await applyFallbacks(this.ctx, bot, channelId, outgoing);
|
|
351
|
+
}
|
|
352
|
+
/** The next message of the user in the session's channel, undefined after `timeout`; it skips the middleware. */
|
|
353
|
+
prompt(session, timeout = PROMPT_TIMEOUT) {
|
|
354
|
+
const key = placeKey(session);
|
|
355
|
+
this.prompts.get(key)?.(void 0);
|
|
356
|
+
return new Promise((resolve2) => {
|
|
357
|
+
const timer = setTimeout(() => settle(void 0), timeout);
|
|
358
|
+
const settle = (answer) => {
|
|
359
|
+
clearTimeout(timer);
|
|
360
|
+
if (this.prompts.get(key) === settle) this.prompts.delete(key);
|
|
361
|
+
resolve2(answer);
|
|
362
|
+
};
|
|
363
|
+
this.prompts.set(key, settle);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
/** Sends after what was queued for the channel before, then holds the queue for `delay`. */
|
|
367
|
+
sendQueued(bot, channelId, content, options, delay = QUEUE_DELAY) {
|
|
368
|
+
const key = `${bot.sid}
|
|
369
|
+
${channelId}`;
|
|
370
|
+
const sent = (this.queues.get(key) ?? Promise.resolve()).then(() => bot.sendMessage(channelId, content, options));
|
|
371
|
+
const queue = sent.catch(() => {
|
|
372
|
+
}).then(() => new Promise((resolve2) => setTimeout(resolve2, delay)));
|
|
373
|
+
this.queues.set(key, queue);
|
|
374
|
+
queue.then(() => {
|
|
375
|
+
if (this.queues.get(key) === queue) this.queues.delete(key);
|
|
376
|
+
});
|
|
377
|
+
return sent;
|
|
378
|
+
}
|
|
379
|
+
hooks(name, place) {
|
|
380
|
+
const policy = this.state.policy;
|
|
381
|
+
const hooks = this.ctx.events._hooks[name] ?? [];
|
|
382
|
+
if (!policy) return [...hooks];
|
|
383
|
+
return hooks.filter((hook) => {
|
|
384
|
+
if (hook.global) return true;
|
|
385
|
+
const owner = policy.owner(hook.ctx);
|
|
386
|
+
return owner === void 0 || policy.accepts(owner, place);
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
failed(hook, name, error) {
|
|
390
|
+
const owner = this.ownerOf(hook.ctx);
|
|
391
|
+
hook.ctx.logger("bots").warn(`${name} listener failed:`, error);
|
|
392
|
+
if (owner !== void 0) this.state.policy.failed(owner, error);
|
|
393
|
+
}
|
|
394
|
+
/** cordis' parallel, but a listener that throws is noted against its plugin instead of failing the others. */
|
|
395
|
+
async fanOut(name, place, args) {
|
|
396
|
+
await Promise.all(this.hooks(name, place).map(async (hook) => {
|
|
397
|
+
try {
|
|
398
|
+
await hook.callback(...args);
|
|
399
|
+
} catch (error) {
|
|
400
|
+
this.failed(hook, name, error);
|
|
401
|
+
}
|
|
402
|
+
}));
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* cordis' waterfall over the listeners in scope, message listeners in the host's order. A listener that throws is
|
|
406
|
+
* noted and passed by: thrown before next(), the rest still get their turn; after, what they did stands.
|
|
407
|
+
*/
|
|
408
|
+
chain(name, place, args, inner, ranked = true) {
|
|
409
|
+
let hooks = this.hooks(name, place);
|
|
410
|
+
const policy = this.state.policy;
|
|
411
|
+
if (ranked && policy) {
|
|
412
|
+
const rankOf = (hook) => {
|
|
413
|
+
const owner = policy.owner(hook.ctx);
|
|
414
|
+
return (owner === void 0 ? void 0 : policy.rank(owner)) ?? Infinity;
|
|
415
|
+
};
|
|
416
|
+
hooks = hooks.map((hook) => ({ hook, rank: rankOf(hook) })).sort((a, b) => a.rank - b.rank).map(({ hook }) => hook);
|
|
417
|
+
}
|
|
418
|
+
const dispatch = async (index) => {
|
|
419
|
+
const hook = hooks[index];
|
|
420
|
+
if (!hook) return inner();
|
|
421
|
+
let rest;
|
|
422
|
+
const next = () => {
|
|
423
|
+
if (rest) throw new Error("next() called multiple times");
|
|
424
|
+
return rest = dispatch(index + 1);
|
|
425
|
+
};
|
|
426
|
+
try {
|
|
427
|
+
return await hook.callback(...args, next);
|
|
428
|
+
} catch (error) {
|
|
429
|
+
this.failed(hook, name, error);
|
|
430
|
+
return await (rest ?? next());
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
return dispatch(0);
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
var bots_default = BotsService;
|
|
437
|
+
|
|
438
|
+
// src/universal/commands.ts
|
|
439
|
+
import h3 from "@satorijs/element";
|
|
440
|
+
import { Service as Service2 } from "cordis";
|
|
441
|
+
|
|
442
|
+
// src/common/platform.ts
|
|
443
|
+
function normalizePlatform(platform) {
|
|
444
|
+
return platform === "luckylillia" ? "ntqq" : platform;
|
|
445
|
+
}
|
|
446
|
+
function normalizePlatformId(id) {
|
|
447
|
+
return id.startsWith("luckylillia:") ? `ntqq:${id.slice("luckylillia:".length)}` : id;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// src/universal/commands.ts
|
|
451
|
+
var DEFAULT_SETTINGS = { prefixes: ["/"], bare: true, denyNotice: true, owners: [], aliases: [], permissions: [] };
|
|
452
|
+
var ArgvError = class extends Error {
|
|
453
|
+
};
|
|
454
|
+
var TYPES = /* @__PURE__ */ new Set(["string", "text", "number", "integer", "posint", "natural", "user"]);
|
|
455
|
+
var PARAM = /^([<[])([^:>\]]+)(?::([^>\]]+))?[>\]]$/;
|
|
456
|
+
var MENU_DELAY = 2e3;
|
|
457
|
+
function parseParam(token) {
|
|
458
|
+
const match = PARAM.exec(token);
|
|
459
|
+
if (!match) return;
|
|
460
|
+
const type = (match[3] ?? "string").trim();
|
|
461
|
+
if (!TYPES.has(type)) throw new TypeError(`unknown parameter type ${type} in ${token}`);
|
|
462
|
+
return { name: match[2].trim(), type, required: match[1] === "<" };
|
|
463
|
+
}
|
|
464
|
+
function parseDef(def) {
|
|
465
|
+
const [name, ...rest] = def.trim().split(/\s+/);
|
|
466
|
+
if (!name) throw new TypeError("a command needs a name");
|
|
467
|
+
const args = rest.map((token) => {
|
|
468
|
+
const param = parseParam(token);
|
|
469
|
+
if (!param) throw new TypeError(`expected <param> or [param] in "${def}", got ${token}`);
|
|
470
|
+
return param;
|
|
471
|
+
});
|
|
472
|
+
if (args.slice(0, -1).some((arg) => arg.type === "text")) throw new TypeError(`only the last parameter of "${def}" can be text`);
|
|
473
|
+
return { name, args };
|
|
474
|
+
}
|
|
475
|
+
function parseOption(name, syntax, config = {}) {
|
|
476
|
+
const tokens = syntax.trim().split(/\s+/).filter(Boolean);
|
|
477
|
+
const flags = [];
|
|
478
|
+
let param;
|
|
479
|
+
let i = 0;
|
|
480
|
+
for (; i < tokens.length; i++) {
|
|
481
|
+
const token = tokens[i].replace(/,$/, "");
|
|
482
|
+
if (/^--?[^-\s\d]/.test(token)) {
|
|
483
|
+
flags.push(token);
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
if (!param && (param = parseParam(token))) continue;
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
if (!flags.includes(`--${name}`)) flags.push(`--${name}`);
|
|
490
|
+
return { name, flags, param, description: tokens.slice(i).join(" "), fallback: config.fallback };
|
|
491
|
+
}
|
|
492
|
+
var formatParam = (param) => {
|
|
493
|
+
const inner = param.type === "string" ? param.name : `${param.name}:${param.type}`;
|
|
494
|
+
return param.required ? `<${inner}>` : `[${inner}]`;
|
|
495
|
+
};
|
|
496
|
+
var QUOTED = /"([^"]*)"|'([^']*)'|“([^”]*)”|「([^」]*)」|(\S+)/g;
|
|
497
|
+
var PLACEHOLDER = /(\d+)/g;
|
|
498
|
+
var ONLY_PLACEHOLDER = /^(\d+)$/;
|
|
499
|
+
function tokenize(markup) {
|
|
500
|
+
const elements = [];
|
|
501
|
+
let flat = "";
|
|
502
|
+
for (const element of h3.parse(markup)) {
|
|
503
|
+
if (element.type === "text") flat += h3.escape(String(element.attrs.content ?? ""));
|
|
504
|
+
else flat += `\uE000${elements.push(element) - 1}\uE001`;
|
|
505
|
+
}
|
|
506
|
+
const restore = (value) => value.replace(PLACEHOLDER, (_, index) => elements[+index].toString());
|
|
507
|
+
return [...flat.matchAll(QUOTED)].map((match) => {
|
|
508
|
+
const raw = match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5];
|
|
509
|
+
const only = ONLY_PLACEHOLDER.exec(raw);
|
|
510
|
+
return { value: restore(raw), element: only ? elements[+only[1]] : void 0, rest: restore(flat.slice(match.index)) };
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
function convert(param, token) {
|
|
514
|
+
const fail = (what) => {
|
|
515
|
+
throw new ArgvError(`\u53C2\u6570 ${param.name} \u5E94\u8BE5\u662F${what}\uFF0C\u6536\u5230\u7684\u662F ${h3.unescape(token.value)}`);
|
|
516
|
+
};
|
|
517
|
+
const number = Number(h3.unescape(token.value));
|
|
518
|
+
switch (param.type) {
|
|
519
|
+
case "number":
|
|
520
|
+
return Number.isFinite(number) ? number : fail("\u6570\u5B57");
|
|
521
|
+
case "integer":
|
|
522
|
+
return Number.isInteger(number) ? number : fail("\u6574\u6570");
|
|
523
|
+
case "posint":
|
|
524
|
+
return Number.isInteger(number) && number > 0 ? number : fail("\u6B63\u6574\u6570");
|
|
525
|
+
case "natural":
|
|
526
|
+
return Number.isInteger(number) && number >= 0 ? number : fail("\u975E\u8D1F\u6574\u6570");
|
|
527
|
+
case "user":
|
|
528
|
+
if (token.element) return token.element.type === "at" && token.element.attrs.id ? String(token.element.attrs.id) : fail("\u4E00\u4E2A @ \u6216\u7528\u6237 id");
|
|
529
|
+
return h3.unescape(token.value);
|
|
530
|
+
default:
|
|
531
|
+
return token.value;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
var Command = class {
|
|
535
|
+
constructor(ctx, def, description, config) {
|
|
536
|
+
this.ctx = ctx;
|
|
537
|
+
this.description = description;
|
|
538
|
+
this.config = config;
|
|
539
|
+
const { name, args } = parseDef(def);
|
|
540
|
+
this.name = name;
|
|
541
|
+
this.args = args;
|
|
542
|
+
}
|
|
543
|
+
ctx;
|
|
544
|
+
description;
|
|
545
|
+
config;
|
|
546
|
+
name;
|
|
547
|
+
args;
|
|
548
|
+
aliases = [];
|
|
549
|
+
options = [];
|
|
550
|
+
handler;
|
|
551
|
+
disposeCommand;
|
|
552
|
+
get names() {
|
|
553
|
+
return [this.name, ...this.aliases];
|
|
554
|
+
}
|
|
555
|
+
get syntax() {
|
|
556
|
+
return [this.name, ...this.args.map(formatParam)].join(" ");
|
|
557
|
+
}
|
|
558
|
+
alias(...names) {
|
|
559
|
+
for (const name of names) {
|
|
560
|
+
if (name && !this.names.includes(name)) this.aliases.push(name);
|
|
561
|
+
}
|
|
562
|
+
return this;
|
|
563
|
+
}
|
|
564
|
+
option(name, syntax, config) {
|
|
565
|
+
this.options.push(parseOption(name, syntax, config));
|
|
566
|
+
return this;
|
|
567
|
+
}
|
|
568
|
+
action(action) {
|
|
569
|
+
this.handler = action;
|
|
570
|
+
return this;
|
|
571
|
+
}
|
|
572
|
+
dispose() {
|
|
573
|
+
this.disposeCommand?.();
|
|
574
|
+
}
|
|
575
|
+
/** Reads what follows the name; words beyond the parameters are left out. */
|
|
576
|
+
parse(rest) {
|
|
577
|
+
const options = {};
|
|
578
|
+
for (const option of this.options) {
|
|
579
|
+
if (option.fallback !== void 0) options[option.name] = option.fallback;
|
|
580
|
+
}
|
|
581
|
+
const args = [];
|
|
582
|
+
const tokens = tokenize(rest);
|
|
583
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
584
|
+
const token = tokens[i];
|
|
585
|
+
const [flag, inline2] = token.element ? [] : h3.unescape(token.value).split(/=(.*)/s);
|
|
586
|
+
const option = flag ? this.options.find((option2) => option2.flags.includes(flag)) : void 0;
|
|
587
|
+
if (option) {
|
|
588
|
+
if (!option.param) {
|
|
589
|
+
options[option.name] = true;
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
const value = inline2 !== void 0 ? { ...token, value: h3.escape(inline2) } : tokens[++i];
|
|
593
|
+
if (!value) throw new ArgvError(`\u9009\u9879 ${flag} \u540E\u9762\u8981\u8DDF ${formatParam(option.param)}`);
|
|
594
|
+
options[option.name] = convert(option.param, value);
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
const param = this.args[args.length];
|
|
598
|
+
if (!param) continue;
|
|
599
|
+
if (param.type === "text") {
|
|
600
|
+
args.push(token.rest.trim());
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
args.push(convert(param, token));
|
|
604
|
+
}
|
|
605
|
+
const missing = this.args.slice(args.length).find((param) => param.required);
|
|
606
|
+
if (missing) throw new ArgvError(`\u7F3A\u5C11\u53C2\u6570 ${missing.name}`);
|
|
607
|
+
return { options, args };
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
var CommandService = class extends Service2 {
|
|
611
|
+
constructor(ctx, settings = { current: DEFAULT_SETTINGS }) {
|
|
612
|
+
super(ctx, "commands");
|
|
613
|
+
this.settings = settings;
|
|
614
|
+
this.home = ctx;
|
|
615
|
+
ctx.mixin("commands", ["command"]);
|
|
616
|
+
ctx.on("bot/message", (session, next) => this.handle(session, next), { prepend: true });
|
|
617
|
+
ctx.on("bot/status", (bot) => {
|
|
618
|
+
if (this.bots.get(bot.sid) !== bot) {
|
|
619
|
+
this.menus.delete(bot.sid);
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
if (bot.status === 1) this.syncMenu(bot);
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
settings;
|
|
626
|
+
static inject = ["bots", "timer"];
|
|
627
|
+
commands = [];
|
|
628
|
+
cooldowns = /* @__PURE__ */ new Map();
|
|
629
|
+
menus = /* @__PURE__ */ new Map();
|
|
630
|
+
pending = {};
|
|
631
|
+
home;
|
|
632
|
+
get bots() {
|
|
633
|
+
return this.home.get("bots");
|
|
634
|
+
}
|
|
635
|
+
command(def, description = "", config = {}) {
|
|
636
|
+
const command = new Command(this.ctx, def, description, config);
|
|
637
|
+
command.disposeCommand = this.ctx.effect(() => {
|
|
638
|
+
const names = this.names(command);
|
|
639
|
+
const clash = this.commands.find((other) => this.names(other).some((name) => names.some((mine) => same(name, mine))));
|
|
640
|
+
if (clash) this.home.logger("commands").warn(`\u6307\u4EE4 ${command.name} \u548C\u5DF2\u6709\u7684 ${clash.name} \u91CD\u540D\uFF0C\u4E24\u4E2A\u63D2\u4EF6\u90FD\u6536\u7684\u6D88\u606F\u7531\u5148\u6CE8\u518C\u7684\u5904\u7406`);
|
|
641
|
+
this.commands.push(command);
|
|
642
|
+
this.scheduleMenus();
|
|
643
|
+
return () => {
|
|
644
|
+
const index = this.commands.indexOf(command);
|
|
645
|
+
if (index >= 0) this.commands.splice(index, 1);
|
|
646
|
+
this.scheduleMenus();
|
|
647
|
+
};
|
|
648
|
+
}, `ctx.command(${JSON.stringify(command.name)})`);
|
|
649
|
+
return command;
|
|
650
|
+
}
|
|
651
|
+
/** Resolve settings at use time so changing aliases never replaces commands or their owning plugins. */
|
|
652
|
+
names(command) {
|
|
653
|
+
const owner = this.bots.ownerOf(command.ctx) ?? "";
|
|
654
|
+
const custom = (this.settings.current.aliases ?? []).filter((row) => row.owner === owner && row.command === command.name).flatMap((row) => row.aliases);
|
|
655
|
+
const names = /* @__PURE__ */ new Map();
|
|
656
|
+
for (const name of [...command.names, ...custom]) {
|
|
657
|
+
if (name && !names.has(name.toLowerCase())) names.set(name.toLowerCase(), name);
|
|
658
|
+
}
|
|
659
|
+
return [...names.values()];
|
|
660
|
+
}
|
|
661
|
+
list() {
|
|
662
|
+
const names = new Map(this.commands.map((command) => [command, this.names(command)]));
|
|
663
|
+
return this.commands.map((command) => {
|
|
664
|
+
const conflicts = [];
|
|
665
|
+
for (const other of this.commands) {
|
|
666
|
+
if (other === command) continue;
|
|
667
|
+
for (const name of names.get(command)) {
|
|
668
|
+
if (names.get(other).some((theirs) => same(theirs, name))) conflicts.push({ name, with: this.bots.ownerOf(other.ctx) });
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
return {
|
|
672
|
+
name: command.name,
|
|
673
|
+
aliases: names.get(command).slice(1),
|
|
674
|
+
description: command.description,
|
|
675
|
+
syntax: command.syntax,
|
|
676
|
+
hidden: !!command.config.hidden,
|
|
677
|
+
authority: this.authority(command),
|
|
678
|
+
defaultAuthority: command.config.authority ?? "everyone",
|
|
679
|
+
owner: this.bots.ownerOf(command.ctx),
|
|
680
|
+
conflicts
|
|
681
|
+
};
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
/** The commands a session can run: with an action, of a plugin that takes the session. */
|
|
685
|
+
reachable(session) {
|
|
686
|
+
return this.commands.filter((command) => command.handler && this.bots.allows(command.ctx, session));
|
|
687
|
+
}
|
|
688
|
+
async handle(session, next) {
|
|
689
|
+
const found = this.match(session);
|
|
690
|
+
if (!found) return next();
|
|
691
|
+
const { command, rest } = found;
|
|
692
|
+
if (!await this.permitted(command, session)) {
|
|
693
|
+
if (this.settings.current.denyNotice !== false) await session.send(h3.text("\u4F60\u6CA1\u6709\u6743\u9650\u4F7F\u7528\u8FD9\u4E2A\u6307\u4EE4\u3002"));
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
const cooldown = command.config.cooldown;
|
|
697
|
+
const key = `${command.name}
|
|
698
|
+
${session.platform}:${session.userId}`;
|
|
699
|
+
const last = this.cooldowns.get(key);
|
|
700
|
+
if (cooldown && last !== void 0 && Date.now() - last < cooldown) {
|
|
701
|
+
await session.send(h3.text(`\u8BF7\u5728 ${Math.ceil((cooldown - (Date.now() - last)) / 1e3)} \u79D2\u540E\u518D\u8BD5\u3002`));
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
let parsed;
|
|
705
|
+
try {
|
|
706
|
+
parsed = command.parse(rest);
|
|
707
|
+
} catch (error) {
|
|
708
|
+
if (!(error instanceof ArgvError)) throw error;
|
|
709
|
+
await session.send(h3.text(`${error.message}
|
|
710
|
+
\u7528\u6CD5\uFF1A${command.syntax}`));
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (cooldown) this.cooldowns.set(key, Date.now());
|
|
714
|
+
const argv = { session, command, next, ...parsed };
|
|
715
|
+
let result;
|
|
716
|
+
try {
|
|
717
|
+
result = await command.handler(argv, ...parsed.args);
|
|
718
|
+
} catch (error) {
|
|
719
|
+
command.ctx.logger("commands").warn(`\u6307\u4EE4 ${command.name} \u51FA\u9519:`, error);
|
|
720
|
+
this.bots.reportFailure(command.ctx, error);
|
|
721
|
+
await session.send(h3.text("\u6267\u884C\u6307\u4EE4\u65F6\u51FA\u9519\u4E86\u3002"));
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
if (result !== void 0 && result !== null && result !== "") await session.send(result);
|
|
725
|
+
}
|
|
726
|
+
/** The command the message starts with, past a prefix; the longest name wins, then the first registered. */
|
|
727
|
+
match(session) {
|
|
728
|
+
const content = session.stripped.content;
|
|
729
|
+
const first = h3.parse(content)[0];
|
|
730
|
+
if (first?.type !== "text") return;
|
|
731
|
+
const text = first.toString();
|
|
732
|
+
const { prefixes: given, bare } = this.settings.current;
|
|
733
|
+
const prefixes = [.../* @__PURE__ */ new Set([...given.filter(Boolean), ...bare ? [""] : []])].sort((a, b) => b.length - a.length);
|
|
734
|
+
const candidates = this.reachable(session);
|
|
735
|
+
for (const prefix of prefixes) {
|
|
736
|
+
if (!text.startsWith(prefix)) continue;
|
|
737
|
+
const body = text.slice(prefix.length);
|
|
738
|
+
let best;
|
|
739
|
+
for (const command of candidates) {
|
|
740
|
+
for (const name of this.names(command)) {
|
|
741
|
+
if (body.length < name.length || !same(body.slice(0, name.length), name)) continue;
|
|
742
|
+
if (body.length > name.length && !/\s/.test(body[name.length])) continue;
|
|
743
|
+
if (!best || name.length > best.name.length) best = { command, name };
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (best) return { command: best.command, rest: content.slice(prefix.length + best.name.length) };
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
isOwner(session) {
|
|
750
|
+
const id = session.userId;
|
|
751
|
+
const platform = normalizePlatform(session.platform);
|
|
752
|
+
return !!id && this.settings.current.owners.some((owner) => owner === id || normalizePlatformId(owner) === `${platform}:${id}`);
|
|
753
|
+
}
|
|
754
|
+
authority(command) {
|
|
755
|
+
const owner = this.bots.ownerOf(command.ctx) ?? "";
|
|
756
|
+
const override = this.settings.current.permissions?.find((row) => row.owner === owner && same(row.command, command.name));
|
|
757
|
+
return override?.authority ?? command.config.authority ?? "everyone";
|
|
758
|
+
}
|
|
759
|
+
async permitted(command, session) {
|
|
760
|
+
const authority = this.authority(command);
|
|
761
|
+
if (authority === "everyone" || this.isOwner(session)) return true;
|
|
762
|
+
if (authority === "owner" || !session.guildId || !session.userId) return false;
|
|
763
|
+
const known = session.event.member?.roles;
|
|
764
|
+
const roles = known?.length ? known : await session.bot.getGuildMember?.(session.guildId, session.userId).then((member) => member?.roles, () => void 0);
|
|
765
|
+
return !!roles?.some((role) => ["owner", "admin"].includes(role.name ?? role.id ?? ""));
|
|
766
|
+
}
|
|
767
|
+
menu() {
|
|
768
|
+
return this.commands.filter((command) => command.handler && !command.config.hidden).map((command) => ({
|
|
769
|
+
name: command.name,
|
|
770
|
+
description: { "": command.description },
|
|
771
|
+
arguments: command.args.map((arg) => ({ name: arg.name, description: {}, type: arg.type, required: arg.required })),
|
|
772
|
+
options: command.options.map((option) => ({
|
|
773
|
+
name: option.name,
|
|
774
|
+
description: { "": option.description },
|
|
775
|
+
type: option.param?.type ?? "boolean",
|
|
776
|
+
required: false
|
|
777
|
+
})),
|
|
778
|
+
children: []
|
|
779
|
+
}));
|
|
780
|
+
}
|
|
781
|
+
scheduleMenus() {
|
|
782
|
+
this.pending.menus?.();
|
|
783
|
+
this.pending.menus = this.home.timeout(() => {
|
|
784
|
+
for (const bot of this.bots) {
|
|
785
|
+
if (bot.status === 1) this.syncMenu(bot);
|
|
786
|
+
}
|
|
787
|
+
}, MENU_DELAY);
|
|
788
|
+
}
|
|
789
|
+
/** Puts the commands on a bot's menu, unless it has these already. */
|
|
790
|
+
syncMenu(bot) {
|
|
791
|
+
if (bot.platform === "qq" || !bot.updateCommands) return;
|
|
792
|
+
const menu = this.menu();
|
|
793
|
+
const key = JSON.stringify(menu);
|
|
794
|
+
if (this.menus.get(bot.sid) === key) return;
|
|
795
|
+
this.menus.set(bot.sid, key);
|
|
796
|
+
bot.updateCommands(menu).catch((e) => this.home.logger("commands").warn(`\u540C\u6B65 ${bot.sid} \u7684\u6307\u4EE4\u83DC\u5355\u5931\u8D25:`, e));
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
function same(a, b) {
|
|
800
|
+
return a.toLowerCase() === b.toLowerCase();
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// src/universal/http.ts
|
|
804
|
+
import { Service as Service3 } from "cordis";
|
|
805
|
+
var HttpError = class extends Error {
|
|
806
|
+
constructor(message, code, response, options) {
|
|
807
|
+
super(message, options);
|
|
808
|
+
this.code = code;
|
|
809
|
+
this.response = response;
|
|
810
|
+
this.proxy = options?.proxy;
|
|
811
|
+
}
|
|
812
|
+
code;
|
|
813
|
+
response;
|
|
814
|
+
name = "HttpError";
|
|
815
|
+
/** Sanitized proxy address (`protocol//host`) when the failed request went through a proxy */
|
|
816
|
+
proxy;
|
|
817
|
+
};
|
|
818
|
+
function mergeConfig(base, more = {}) {
|
|
819
|
+
const merged = { ...base };
|
|
820
|
+
for (const [key, value] of Object.entries(more)) {
|
|
821
|
+
if (value !== void 0) merged[key] = value;
|
|
822
|
+
}
|
|
823
|
+
if (base.headers || more.headers) merged.headers = { ...base.headers, ...more.headers };
|
|
824
|
+
return merged;
|
|
825
|
+
}
|
|
826
|
+
function resolve(url, baseURL) {
|
|
827
|
+
if (url instanceof URL) return url;
|
|
828
|
+
return baseURL ? new URL(url, baseURL.endsWith("/") ? baseURL : `${baseURL}/`) : new URL(url);
|
|
829
|
+
}
|
|
830
|
+
var where = (url) => `${url.origin}${url.pathname}`;
|
|
831
|
+
function encode(data, headers) {
|
|
832
|
+
if (data === void 0 || data === null) return;
|
|
833
|
+
if (typeof data === "string" || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || data instanceof Blob || data instanceof FormData || data instanceof URLSearchParams || data instanceof ReadableStream) {
|
|
834
|
+
return data;
|
|
835
|
+
}
|
|
836
|
+
headers.set("content-type", "application/json");
|
|
837
|
+
return JSON.stringify(data);
|
|
838
|
+
}
|
|
839
|
+
async function decode(response, type) {
|
|
840
|
+
if (type === "stream") return response.body;
|
|
841
|
+
if (type === "arraybuffer") return response.arrayBuffer();
|
|
842
|
+
if (type === "text") return response.text();
|
|
843
|
+
if (type === "json") return response.json();
|
|
844
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
845
|
+
if (contentType.includes("json")) {
|
|
846
|
+
const text = await response.text();
|
|
847
|
+
try {
|
|
848
|
+
return text ? JSON.parse(text) : void 0;
|
|
849
|
+
} catch {
|
|
850
|
+
return text;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
if (/^text\/|xml|javascript|urlencoded/.test(contentType)) return response.text();
|
|
854
|
+
return response.arrayBuffer();
|
|
855
|
+
}
|
|
856
|
+
function sniff(bytes) {
|
|
857
|
+
const starts = (...signature) => signature.every((byte, i) => bytes[i] === byte);
|
|
858
|
+
if (starts(137, 80, 78, 71)) return "image/png";
|
|
859
|
+
if (starts(255, 216, 255)) return "image/jpeg";
|
|
860
|
+
if (starts(71, 73, 70, 56)) return "image/gif";
|
|
861
|
+
if (starts(82, 73, 70, 70) && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) return "image/webp";
|
|
862
|
+
if (starts(66, 77)) return "image/bmp";
|
|
863
|
+
}
|
|
864
|
+
function safeProxyOrigin(raw) {
|
|
865
|
+
if (!raw) return "";
|
|
866
|
+
try {
|
|
867
|
+
const parsed = new URL(raw);
|
|
868
|
+
return `${parsed.protocol}//${parsed.host}`;
|
|
869
|
+
} catch {
|
|
870
|
+
return "";
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
function transportError(error, url, callerSignal, proxy = "") {
|
|
874
|
+
if (callerSignal?.aborted) return callerSignal.reason;
|
|
875
|
+
const hint = proxy ? `\uFF08\u7ECF\u4EE3\u7406 ${proxy}\uFF0C\u8BF7\u68C0\u67E5\u4EE3\u7406\u8BBE\u7F6E\uFF09` : "";
|
|
876
|
+
const options = proxy ? { cause: error, proxy } : { cause: error };
|
|
877
|
+
if (error?.name === "TimeoutError") return new HttpError(`${url.origin} did not answer in time${hint}`, "ETIMEDOUT", void 0, options);
|
|
878
|
+
let cause = error;
|
|
879
|
+
while (cause?.cause) cause = cause.cause;
|
|
880
|
+
const reason = cause?.code ?? cause?.message ?? String(error);
|
|
881
|
+
return new HttpError(`cannot reach ${url.origin}: ${reason}${hint}`, cause?.code, void 0, options);
|
|
882
|
+
}
|
|
883
|
+
function filenameOf(headers, url) {
|
|
884
|
+
const disposition = headers.get("content-disposition") ?? "";
|
|
885
|
+
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
|
886
|
+
if (encoded) return decodeURIComponent(encoded);
|
|
887
|
+
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
|
888
|
+
if (plain) return plain;
|
|
889
|
+
const last = url.pathname.split("/").pop();
|
|
890
|
+
return last ? decodeURIComponent(last) : void 0;
|
|
891
|
+
}
|
|
892
|
+
var HttpClient = class _HttpClient {
|
|
893
|
+
constructor(ctx, config = {}) {
|
|
894
|
+
this.ctx = ctx;
|
|
895
|
+
this.config = config;
|
|
896
|
+
}
|
|
897
|
+
ctx;
|
|
898
|
+
config;
|
|
899
|
+
extend(config) {
|
|
900
|
+
return new _HttpClient(this.ctx, mergeConfig(this.config, config));
|
|
901
|
+
}
|
|
902
|
+
proxy(input, more) {
|
|
903
|
+
const config = mergeConfig(this.config, more);
|
|
904
|
+
const url = resolve(input, config.baseURL);
|
|
905
|
+
const proxy = { url: "" };
|
|
906
|
+
this.ctx.emit("http/proxy", url, proxy, config);
|
|
907
|
+
return proxy.url;
|
|
908
|
+
}
|
|
909
|
+
usedProxy(url, request, config) {
|
|
910
|
+
if (!request.dispatcher) return "";
|
|
911
|
+
try {
|
|
912
|
+
const proxy = { url: "" };
|
|
913
|
+
this.ctx.emit("http/proxy", url, proxy, config);
|
|
914
|
+
return safeProxyOrigin(proxy.url);
|
|
915
|
+
} catch {
|
|
916
|
+
return "";
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
async fetch(input, init = {}, more) {
|
|
920
|
+
const config = mergeConfig(this.config, more);
|
|
921
|
+
const url = resolve(input, config.baseURL);
|
|
922
|
+
const headers = new Headers(config.headers);
|
|
923
|
+
new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
924
|
+
const signals = [init.signal, config.timeout ? AbortSignal.timeout(config.timeout) : void 0].filter((signal) => !!signal);
|
|
925
|
+
const request = { ...init, headers, signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0] };
|
|
926
|
+
this.ctx.emit("http/fetch-init", url, request, config);
|
|
927
|
+
try {
|
|
928
|
+
return await fetch(url, request);
|
|
929
|
+
} catch (error) {
|
|
930
|
+
throw transportError(error, url, init.signal, this.usedProxy(url, request, config));
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
async request(method, url, config = {}) {
|
|
934
|
+
const { params, data, responseType, signal, redirect, ...rest } = config;
|
|
935
|
+
const target = resolve(url, rest.baseURL ?? this.config.baseURL);
|
|
936
|
+
for (const [key, value] of Object.entries(params ?? {})) {
|
|
937
|
+
if (value !== void 0) target.searchParams.append(key, String(value));
|
|
938
|
+
}
|
|
939
|
+
const headers = new Headers();
|
|
940
|
+
const body = encode(data, headers);
|
|
941
|
+
const response = await this.fetch(target, { method, headers, body, signal, redirect }, rest);
|
|
942
|
+
let decoded;
|
|
943
|
+
try {
|
|
944
|
+
decoded = method === "HEAD" ? void 0 : await decode(response, responseType);
|
|
945
|
+
} catch (error) {
|
|
946
|
+
if (error?.name !== "SyntaxError") throw transportError(error, target, signal);
|
|
947
|
+
if (response.ok) throw new HttpError(`${method} ${where(target)} answered something that is not JSON`, void 0, void 0, { cause: error });
|
|
948
|
+
}
|
|
949
|
+
const result = { url: response.url, status: response.status, statusText: response.statusText, headers: response.headers, data: decoded };
|
|
950
|
+
if (!response.ok) throw new HttpError(`${method} ${where(target)} answered ${response.status}`, void 0, result);
|
|
951
|
+
return result;
|
|
952
|
+
}
|
|
953
|
+
async get(url, config) {
|
|
954
|
+
return (await this.request("GET", url, config)).data;
|
|
955
|
+
}
|
|
956
|
+
async delete(url, config) {
|
|
957
|
+
return (await this.request("DELETE", url, config)).data;
|
|
958
|
+
}
|
|
959
|
+
async head(url, config) {
|
|
960
|
+
return (await this.request("HEAD", url, config)).headers;
|
|
961
|
+
}
|
|
962
|
+
async post(url, data, config) {
|
|
963
|
+
return (await this.request("POST", url, { ...config, data })).data;
|
|
964
|
+
}
|
|
965
|
+
async put(url, data, config) {
|
|
966
|
+
return (await this.request("PUT", url, { ...config, data })).data;
|
|
967
|
+
}
|
|
968
|
+
async patch(url, data, config) {
|
|
969
|
+
return (await this.request("PATCH", url, { ...config, data })).data;
|
|
970
|
+
}
|
|
971
|
+
async file(url, config = {}) {
|
|
972
|
+
if (url.startsWith("data:")) {
|
|
973
|
+
const comma = url.indexOf(",");
|
|
974
|
+
const meta = url.slice(5, comma);
|
|
975
|
+
const bytes = Buffer.from(decodeURIComponent(url.slice(comma + 1)), meta.includes(";base64") ? "base64" : "utf8");
|
|
976
|
+
const data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
977
|
+
return { data, type: meta.split(";")[0] || sniff(bytes) || "application/octet-stream" };
|
|
978
|
+
}
|
|
979
|
+
const response = await this.request("GET", url, { ...config, responseType: "arraybuffer" });
|
|
980
|
+
const given = response.headers.get("content-type")?.split(";")[0].trim();
|
|
981
|
+
const type = given && given !== "application/octet-stream" ? given : sniff(new Uint8Array(response.data)) ?? given ?? "application/octet-stream";
|
|
982
|
+
return { data: response.data, type, filename: filenameOf(response.headers, new URL(response.url || url)) };
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
var HttpService = class extends Service3 {
|
|
986
|
+
client;
|
|
987
|
+
constructor(ctx, config = {}) {
|
|
988
|
+
super(ctx, "http");
|
|
989
|
+
this.client = new HttpClient(ctx, config);
|
|
990
|
+
}
|
|
991
|
+
get config() {
|
|
992
|
+
return this.client.config;
|
|
993
|
+
}
|
|
994
|
+
extend(config) {
|
|
995
|
+
return this.client.extend(config);
|
|
996
|
+
}
|
|
997
|
+
proxy(url, config) {
|
|
998
|
+
return this.client.proxy(url, config);
|
|
999
|
+
}
|
|
1000
|
+
fetch(url, init, config) {
|
|
1001
|
+
return this.client.fetch(url, init, config);
|
|
1002
|
+
}
|
|
1003
|
+
request(method, url, config) {
|
|
1004
|
+
return this.client.request(method, url, config);
|
|
1005
|
+
}
|
|
1006
|
+
get(url, config) {
|
|
1007
|
+
return this.client.get(url, config);
|
|
1008
|
+
}
|
|
1009
|
+
delete(url, config) {
|
|
1010
|
+
return this.client.delete(url, config);
|
|
1011
|
+
}
|
|
1012
|
+
head(url, config) {
|
|
1013
|
+
return this.client.head(url, config);
|
|
1014
|
+
}
|
|
1015
|
+
post(url, data, config) {
|
|
1016
|
+
return this.client.post(url, data, config);
|
|
1017
|
+
}
|
|
1018
|
+
put(url, data, config) {
|
|
1019
|
+
return this.client.put(url, data, config);
|
|
1020
|
+
}
|
|
1021
|
+
patch(url, data, config) {
|
|
1022
|
+
return this.client.patch(url, data, config);
|
|
1023
|
+
}
|
|
1024
|
+
file(url, config) {
|
|
1025
|
+
return this.client.file(url, config);
|
|
1026
|
+
}
|
|
1027
|
+
};
|
|
1028
|
+
var http_default = HttpService;
|
|
1029
|
+
|
|
1030
|
+
// src/universal/testing.ts
|
|
1031
|
+
var TestBot = class {
|
|
1032
|
+
constructor(ctx, options) {
|
|
1033
|
+
this.ctx = ctx;
|
|
1034
|
+
this.platform = options.platform ?? "test";
|
|
1035
|
+
this.selfId = options.selfId ?? "bot";
|
|
1036
|
+
this.sid = `${this.platform}:${this.selfId}`;
|
|
1037
|
+
this.features = options.features ?? [];
|
|
1038
|
+
this.user = { id: this.selfId, name: "Bot" };
|
|
1039
|
+
this.internal = options.internal;
|
|
1040
|
+
}
|
|
1041
|
+
ctx;
|
|
1042
|
+
platform;
|
|
1043
|
+
selfId;
|
|
1044
|
+
sid;
|
|
1045
|
+
status = 1;
|
|
1046
|
+
features;
|
|
1047
|
+
user;
|
|
1048
|
+
internal;
|
|
1049
|
+
sent = [];
|
|
1050
|
+
sn = 0;
|
|
1051
|
+
async sendMessage(channelId, content, options) {
|
|
1052
|
+
const elements = await this.ctx.bots.beforeSend(this, channelId, h4.normalize(content), options);
|
|
1053
|
+
if (!elements.length) return [];
|
|
1054
|
+
const markup = elements.join("");
|
|
1055
|
+
this.sent.push({ channelId, content: markup });
|
|
1056
|
+
return [{ id: `sent-${this.sent.length}`, content: markup, channel: { id: channelId } }];
|
|
1057
|
+
}
|
|
1058
|
+
async receive(content, options = {}) {
|
|
1059
|
+
const before = this.sent.length;
|
|
1060
|
+
const userId = options.userId ?? "user";
|
|
1061
|
+
const user = { id: userId, name: options.name };
|
|
1062
|
+
const guildId = options.guildId;
|
|
1063
|
+
await this.ctx.bots.dispatch(this, this.event("message-created", {
|
|
1064
|
+
user,
|
|
1065
|
+
channel: { id: options.channelId ?? guildId ?? `private:${userId}`, type: guildId ? Channel2.Type.TEXT : Channel2.Type.DIRECT },
|
|
1066
|
+
...guildId ? { guild: { id: guildId }, member: { user } } : {},
|
|
1067
|
+
message: { id: `message-${this.sn + 1}`, content },
|
|
1068
|
+
...options.event
|
|
1069
|
+
}));
|
|
1070
|
+
return this.sent.slice(before).map((message) => message.content);
|
|
1071
|
+
}
|
|
1072
|
+
async emit(type, data = {}) {
|
|
1073
|
+
await this.ctx.bots.dispatch(this, this.event(type, data));
|
|
1074
|
+
}
|
|
1075
|
+
event(type, data) {
|
|
1076
|
+
return { sn: ++this.sn, type, self_id: this.selfId, platform: this.platform, timestamp: Date.now(), ...data };
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
async function createTestApp() {
|
|
1080
|
+
const ctx = new Context4();
|
|
1081
|
+
const dataDir = mkdtempSync(path.join(os.tmpdir(), "luckylillia-test-"));
|
|
1082
|
+
ctx.accessor("storage", {
|
|
1083
|
+
get: () => ({
|
|
1084
|
+
dir: async (scope = "global", bot) => {
|
|
1085
|
+
const sid = typeof bot === "string" ? bot : bot?.sid;
|
|
1086
|
+
const dir = path.join(dataDir, scope === "bot" && sid ? path.join("bots", sid.replace(":", "+")) : scope);
|
|
1087
|
+
mkdirSync(dir, { recursive: true });
|
|
1088
|
+
return dir;
|
|
1089
|
+
}
|
|
1090
|
+
})
|
|
1091
|
+
});
|
|
1092
|
+
await ctx.plugin(TimerService);
|
|
1093
|
+
await ctx.plugin(http_default);
|
|
1094
|
+
await ctx.plugin(bots_default);
|
|
1095
|
+
const settings = { current: {
|
|
1096
|
+
...DEFAULT_SETTINGS,
|
|
1097
|
+
prefixes: [...DEFAULT_SETTINGS.prefixes],
|
|
1098
|
+
owners: [],
|
|
1099
|
+
aliases: [],
|
|
1100
|
+
permissions: []
|
|
1101
|
+
} };
|
|
1102
|
+
await ctx.plugin(CommandService, settings);
|
|
1103
|
+
return {
|
|
1104
|
+
ctx,
|
|
1105
|
+
commands: settings.current,
|
|
1106
|
+
dataDir,
|
|
1107
|
+
bot(options = {}) {
|
|
1108
|
+
const bot = new TestBot(ctx, options);
|
|
1109
|
+
ctx.bots.register(bot);
|
|
1110
|
+
return bot;
|
|
1111
|
+
},
|
|
1112
|
+
async dispose() {
|
|
1113
|
+
await ctx.registry.delete(CommandService);
|
|
1114
|
+
await ctx.registry.delete(bots_default);
|
|
1115
|
+
await ctx.registry.delete(http_default);
|
|
1116
|
+
await ctx.registry.delete(TimerService);
|
|
1117
|
+
rmSync(dataDir, { recursive: true, force: true });
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
export {
|
|
1122
|
+
createTestApp
|
|
1123
|
+
};
|