@im-more/dsh-kook 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/cordis.patch.yml +12 -0
  3. package/lib/index.js +2380 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/bot.d.ts +53 -0
  6. package/lib/types/bot.d.ts.map +1 -0
  7. package/lib/types/bot.js +138 -0
  8. package/lib/types/bot.js.map +1 -0
  9. package/lib/types/config.d.ts +46 -0
  10. package/lib/types/config.d.ts.map +1 -0
  11. package/lib/types/config.js +52 -0
  12. package/lib/types/config.js.map +1 -0
  13. package/lib/types/decode.d.ts +88 -0
  14. package/lib/types/decode.d.ts.map +1 -0
  15. package/lib/types/decode.js +564 -0
  16. package/lib/types/decode.js.map +1 -0
  17. package/lib/types/errors.d.ts +46 -0
  18. package/lib/types/errors.d.ts.map +1 -0
  19. package/lib/types/errors.js +159 -0
  20. package/lib/types/errors.js.map +1 -0
  21. package/lib/types/identity.d.ts +17 -0
  22. package/lib/types/identity.d.ts.map +1 -0
  23. package/lib/types/identity.js +24 -0
  24. package/lib/types/identity.js.map +1 -0
  25. package/lib/types/index.d.ts +15 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +15 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/kmarkdown.d.ts +76 -0
  30. package/lib/types/kmarkdown.d.ts.map +1 -0
  31. package/lib/types/kmarkdown.js +201 -0
  32. package/lib/types/kmarkdown.js.map +1 -0
  33. package/lib/types/modes/kmarkdown.d.ts +17 -0
  34. package/lib/types/modes/kmarkdown.d.ts.map +1 -0
  35. package/lib/types/modes/kmarkdown.js +166 -0
  36. package/lib/types/modes/kmarkdown.js.map +1 -0
  37. package/lib/types/modes/shared.d.ts +192 -0
  38. package/lib/types/modes/shared.d.ts.map +1 -0
  39. package/lib/types/modes/shared.js +371 -0
  40. package/lib/types/modes/shared.js.map +1 -0
  41. package/lib/types/request.d.ts +53 -0
  42. package/lib/types/request.d.ts.map +1 -0
  43. package/lib/types/request.js +147 -0
  44. package/lib/types/request.js.map +1 -0
  45. package/lib/types/send.d.ts +57 -0
  46. package/lib/types/send.d.ts.map +1 -0
  47. package/lib/types/send.js +141 -0
  48. package/lib/types/send.js.map +1 -0
  49. package/lib/types/types.d.ts +807 -0
  50. package/lib/types/types.d.ts.map +1 -0
  51. package/lib/types/types.js +168 -0
  52. package/lib/types/types.js.map +1 -0
  53. package/lib/types/webhook.d.ts +35 -0
  54. package/lib/types/webhook.d.ts.map +1 -0
  55. package/lib/types/webhook.js +132 -0
  56. package/lib/types/webhook.js.map +1 -0
  57. package/lib/types/ws.d.ts +54 -0
  58. package/lib/types/ws.d.ts.map +1 -0
  59. package/lib/types/ws.js +358 -0
  60. package/lib/types/ws.js.map +1 -0
  61. package/package.json +61 -3
  62. package/src/bot.ts +217 -0
  63. package/src/config.ts +84 -0
  64. package/src/decode.ts +660 -0
  65. package/src/errors.ts +188 -0
  66. package/src/identity.ts +32 -0
  67. package/src/index.ts +80 -0
  68. package/src/kmarkdown.ts +246 -0
  69. package/src/modes/kmarkdown.ts +204 -0
  70. package/src/modes/shared.ts +498 -0
  71. package/src/request.ts +196 -0
  72. package/src/send.ts +216 -0
  73. package/src/types.ts +764 -0
  74. package/src/webhook.ts +170 -0
  75. package/src/ws.ts +431 -0
  76. package/README.md +0 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["isAbortError","asRecord","asString","messageOf","messageOf","messageOf"],"sources":["types/errors.js","types/request.js","types/types.js","types/config.js","types/identity.js","types/kmarkdown.js","types/modes/shared.js","types/modes/kmarkdown.js","types/decode.js","types/send.js","types/webhook.js","types/ws.js","types/bot.js"],"sourcesContent":["import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\n/** One failed KOOK call: an HTTP answer, a non-zero business code, or a Gateway refusal code. */\nexport class KookApiError extends Error {\n status;\n code;\n retryAfterMs;\n constructor(message, init = {}) {\n super(message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = 'KookApiError';\n this.status = init.status;\n this.code = init.code;\n this.retryAfterMs = init.retryAfterMs;\n }\n}\n/** The configured `selfId` and the account the bot token belongs to disagree. */\nexport class KookIdentityError extends Error {\n constructor(message) {\n super(message);\n this.name = 'KookIdentityError';\n }\n}\n/** HELLO codes that only a corrected configuration can fix (missing parameter, invalid/failed/expired token). */\nconst PERMANENT_HELLO_CODES = new Set([40100, 40101, 40102, 40103]);\n/** RECONNECT codes that report a resume/session/sn refusal; v1 does not resume, so the connection is simply redialed. */\nconst RESUME_CODES = new Set([40106, 40107, 40108]);\n/**\n * Whether a HELLO answer means the configured token cannot work at all.\n * @param code - `d.code` of the HELLO frame.\n * @returns true for the four documented configuration refusals.\n */\nexport function isPermanentHelloCode(code) {\n return code !== undefined && PERMANENT_HELLO_CODES.has(code);\n}\n/**\n * Whether a RECONNECT notice names a resume/session refusal.\n * @param code - `d.code` of the RECONNECT frame.\n * @returns true for the three documented resume refusals.\n */\nexport function isResumeCode(code) {\n return code !== undefined && RESUME_CODES.has(code);\n}\n/** Whether a caught value is the abort error of a cancelled request. */\nfunction isAbortError(error) {\n return ((error instanceof Error || error instanceof DOMException) &&\n error.name === 'AbortError');\n}\n/**\n * Map any KOOK failure onto the core platform taxonomy.\n *\n * A non-2xx answer and a non-zero business code are the platform refusing the call, so nothing was published; a\n * transport failure or a 5xx answer leaves the outcome unknown. Business codes are not interpreted beyond the two\n * documented Gateway ranges, because KOOK publishes no error-code reference (the linked page is gone).\n *\n * @param error - the caught failure.\n * @returns the classified platform error.\n */\nexport function classifyKookError(error) {\n if (error instanceof PlatformError)\n return error;\n if (isAbortError(error)) {\n return new PlatformError('fatal', error instanceof Error ? error.message : 'kook request aborted', { published: 'unknown', cause: error });\n }\n if (error instanceof KookApiError) {\n const init = {\n ...(error.code === undefined ? {} : { code: error.code }),\n ...(error.retryAfterMs === undefined\n ? {}\n : { retryAfterMs: error.retryAfterMs }),\n cause: error,\n };\n if (error.code !== undefined && error.status === undefined) {\n // A Gateway refusal: the HELLO and RECONNECT code tables are the only documented ones.\n if (isPermanentHelloCode(error.code)) {\n return new PlatformError('permission', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (isResumeCode(error.code)) {\n return new PlatformError('fatal', error.message, {\n ...init,\n published: 'no',\n });\n }\n return new PlatformError('invalid', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.status === 429) {\n return new PlatformError('rate-limit', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.code !== undefined) {\n // An HTTP answer that also carries a business code: the status already says what happened.\n if (error.status === 401 || error.status === 403) {\n return new PlatformError('permission', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.status === 404) {\n return new PlatformError('not-found', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.status !== undefined && error.status >= 500) {\n return new PlatformError('retryable', error.message, {\n ...init,\n published: 'unknown',\n });\n }\n return new PlatformError('invalid', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.status === 401 || error.status === 403) {\n return new PlatformError('permission', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.status === 404) {\n return new PlatformError('not-found', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.status !== undefined &&\n error.status >= 400 &&\n error.status < 500) {\n return new PlatformError('invalid', error.message, {\n ...init,\n published: 'no',\n });\n }\n if (error.status !== undefined && error.status >= 500) {\n return new PlatformError('retryable', error.message, {\n ...init,\n published: 'unknown',\n });\n }\n // No status at all: the request never completed, so the platform may have acted.\n return new PlatformError('retryable', error.message, {\n ...init,\n published: 'unknown',\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new PlatformError('retryable', `kook request failed: ${message}`, {\n published: 'unknown',\n cause: error,\n });\n}\n//# sourceMappingURL=errors.js.map","/**\n * KOOK API transport: one request path for every v3 endpoint, the `{ code, message, data }` envelope and its error\n * classification input, and the rate-limit headers.\n *\n * The typed method surface lives on `Internal` (`types.ts`); this module owns the wire mechanics so the migrated\n * client and the adapter's own calls cannot diverge.\n */\nimport { KookApiError } from \"./errors.js\";\n/**\n * Build the request endpoints for one bot.\n * @param ctx - context whose `http` service performs requests.\n * @param apiBaseUrl - API root (`https://www.kookapp.cn/api/v3`).\n * @param token - bot token.\n * @returns the shared request endpoints.\n */\nexport function createKookRequest(ctx, apiBaseUrl, token) {\n return { ctx, baseUrl: apiBaseUrl.replace(/\\/+$/, ''), token };\n}\n/** Whether a caught value is the abort error of a cancelled request. */\nfunction isAbortError(error) {\n return ((error instanceof Error || error instanceof DOMException) &&\n error.name === 'AbortError');\n}\n/**\n * Deliver the cancellation of a request: the signal's reason when it aborted, else the error `ctx.http` produced.\n * @param cause - the value `ctx.http` rejected with.\n * @param signal - the cancellation signal handed to the request.\n * @returns the error to rethrow.\n */\nfunction cancellation(cause, signal) {\n return signal?.aborted === true ? signal.reason : cause;\n}\n/** Whether a failed request was cancelled, by its signal or by the error the transport produced. */\nfunction isCancellation(cause, signal) {\n if (signal?.aborted === true)\n return true;\n if (isAbortError(cause))\n return true;\n return signal?.reason !== undefined && cause === signal.reason;\n}\n/**\n * Delay a rate-limited answer asked for, in milliseconds.\n *\n * KOOK documents `X-Rate-Limit-Reset` (seconds) and says nothing about `Retry-After`; both are read, the standard\n * header first, because an undocumented one is only useful while it is present.\n *\n * @param response - the answer.\n * @returns the delay in milliseconds, or undefined when neither header is present or readable.\n */\nexport function retryAfterOf(response) {\n const standard = response.headers.get('retry-after');\n if (standard !== null) {\n const seconds = Number(standard);\n if (Number.isFinite(seconds) && seconds >= 0)\n return seconds * 1_000;\n }\n const reset = response.headers.get('x-rate-limit-reset');\n if (reset !== null) {\n const seconds = Number(reset);\n if (Number.isFinite(seconds) && seconds >= 0)\n return seconds * 1_000;\n }\n return undefined;\n}\n/** Read a JSON answer; an unreadable body is reported as absence rather than a parse error. */\nasync function jsonOf(response) {\n let body;\n try {\n body = await response.json();\n }\n catch (error) {\n // The answer carried no JSON (a proxy error page, a compressed body): the caller reports the status instead.\n error;\n return undefined;\n }\n if (typeof body !== 'object' || body === null)\n return undefined;\n return body;\n}\n/** The URL of one request. */\nfunction urlOf(request, path) {\n return `${request.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n}\n/**\n * Call one KOOK API endpoint and return its envelope's `data`.\n *\n * @param request - endpoints for this bot.\n * @param method - HTTP method (`GET`, `POST`, `DELETE`).\n * @param path - endpoint below the API root (`/message/create`).\n * @param payload - query parameters of `GET`/`DELETE`, else the request body (JSON or a multipart form).\n * @param signal - cancellation.\n * @returns the endpoint's `data` field.\n * @throws KookApiError for a transport failure, a non-2xx answer or a non-zero business code.\n */\nexport async function invoke(request, method, path, payload, signal) {\n const config = {\n method,\n headers: { authorization: `Bot ${request.token}` },\n };\n if (method === 'GET' || method === 'DELETE')\n config.params = payload ?? {};\n else\n config.data = payload ?? {};\n if (signal !== undefined)\n config.signal = signal;\n let response;\n try {\n response = await request.ctx.http(urlOf(request, path), config);\n }\n catch (cause) {\n if (isCancellation(cause, signal))\n throw cancellation(cause, signal);\n throw new KookApiError(`kook ${method} ${path} request failed`, { cause });\n }\n const status = response.status;\n const retryAfterMs = retryAfterOf(response);\n const body = await jsonOf(response);\n if (body === undefined) {\n // Reading the body fails when the answer is cut short by cancellation; that is still a cancellation.\n if (signal?.aborted === true)\n throw signal.reason;\n throw new KookApiError(`kook ${method} ${path} answered ${status} without a JSON envelope`, { status, ...(retryAfterMs === undefined ? {} : { retryAfterMs }) });\n }\n if (status === 429) {\n throw new KookApiError(`kook ${method} ${path} was rate limited`, {\n status,\n ...(typeof body.code === 'number' ? { code: body.code } : {}),\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n }\n if (body.code !== 0) {\n throw new KookApiError(`kook ${method} ${path} failed: ${body.message ?? 'the answer carries no success code'}`, {\n status,\n ...(typeof body.code === 'number' ? { code: body.code } : {}),\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n }\n if (status >= 400) {\n throw new KookApiError(`kook ${method} ${path} answered ${status} with a success envelope`, {\n status,\n code: body.code,\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n }\n return body.data;\n}\n//# sourceMappingURL=request.js.map","import { invoke } from \"./request.js\";\nexport var Signal;\n(function (Signal) {\n Signal[Signal[\"event\"] = 0] = \"event\";\n Signal[Signal[\"hello\"] = 1] = \"hello\";\n Signal[Signal[\"ping\"] = 2] = \"ping\";\n Signal[Signal[\"pong\"] = 3] = \"pong\";\n Signal[Signal[\"reconnect\"] = 4] = \"reconnect\";\n Signal[Signal[\"resume\"] = 5] = \"resume\";\n})(Signal || (Signal = {}));\nexport var Type;\n(function (Type) {\n Type[Type[\"text\"] = 1] = \"text\";\n Type[Type[\"image\"] = 2] = \"image\";\n Type[Type[\"video\"] = 3] = \"video\";\n Type[Type[\"file\"] = 4] = \"file\";\n Type[Type[\"unknown\"] = 7] = \"unknown\";\n Type[Type[\"audio\"] = 8] = \"audio\";\n Type[Type[\"kmarkdown\"] = 9] = \"kmarkdown\";\n Type[Type[\"card\"] = 10] = \"card\";\n Type[Type[\"system\"] = 255] = \"system\";\n})(Type || (Type = {}));\nexport var Card;\n(function (Card) {\n Card.Theme = ['primary', 'secondary', 'warning', 'danger', 'info', 'none', 'success'];\n Card.Size = ['lg', 'sm'];\n let Button;\n (function (Button) {\n Button.Theme = ['primary', 'secondary', 'warning', 'danger', 'info', 'none', 'success'];\n })(Button = Card.Button || (Card.Button = {}));\n})(Card || (Card = {}));\nexport var UserStatus;\n(function (UserStatus) {\n UserStatus[UserStatus[\"normal\"] = 0] = \"normal\";\n UserStatus[UserStatus[\"normal_1\"] = 1] = \"normal_1\";\n UserStatus[UserStatus[\"banned\"] = 10] = \"banned\";\n})(UserStatus || (UserStatus = {}));\nexport var Permissions;\n(function (Permissions) {\n Permissions[Permissions[\"GUILD_ADMIN\"] = 0] = \"GUILD_ADMIN\";\n Permissions[Permissions[\"GUILD_MANAGE\"] = 1] = \"GUILD_MANAGE\";\n Permissions[Permissions[\"GUILD_LOG\"] = 2] = \"GUILD_LOG\";\n Permissions[Permissions[\"GUILD_INVITE_CREATE\"] = 3] = \"GUILD_INVITE_CREATE\";\n Permissions[Permissions[\"GUILD_INVITE_MANAGE\"] = 4] = \"GUILD_INVITE_MANAGE\";\n Permissions[Permissions[\"CHANNEL_MANAGE\"] = 5] = \"CHANNEL_MANAGE\";\n Permissions[Permissions[\"GUILD_USER_KICK\"] = 6] = \"GUILD_USER_KICK\";\n Permissions[Permissions[\"GUILD_USER_BAN\"] = 7] = \"GUILD_USER_BAN\";\n Permissions[Permissions[\"GUILD_EMOJI_MANAGE\"] = 8] = \"GUILD_EMOJI_MANAGE\";\n Permissions[Permissions[\"GUILD_USER_NAME_CHANGE\"] = 9] = \"GUILD_USER_NAME_CHANGE\";\n Permissions[Permissions[\"GUILD_ROLE_MANAGE\"] = 10] = \"GUILD_ROLE_MANAGE\";\n Permissions[Permissions[\"CHANNEL_VIEW\"] = 11] = \"CHANNEL_VIEW\";\n Permissions[Permissions[\"CHANNEL_MESSAGE\"] = 12] = \"CHANNEL_MESSAGE\";\n Permissions[Permissions[\"CHANNEL_MANAGE_MESSAGE\"] = 13] = \"CHANNEL_MANAGE_MESSAGE\";\n Permissions[Permissions[\"CHANNEL_UPLOAD\"] = 14] = \"CHANNEL_UPLOAD\";\n Permissions[Permissions[\"CHANNEL_VOICE_CONNECT\"] = 15] = \"CHANNEL_VOICE_CONNECT\";\n Permissions[Permissions[\"CHANNEL_VOICE_MANAGE\"] = 16] = \"CHANNEL_VOICE_MANAGE\";\n Permissions[Permissions[\"CHANNEL_MESSAGE_AT_ALL\"] = 17] = \"CHANNEL_MESSAGE_AT_ALL\";\n Permissions[Permissions[\"CHANNEL_MESSAGE_REACTION_CREATE\"] = 18] = \"CHANNEL_MESSAGE_REACTION_CREATE\";\n Permissions[Permissions[\"CHANNEL_MESSAGE_REACTION_FOLLOW\"] = 19] = \"CHANNEL_MESSAGE_REACTION_FOLLOW\";\n Permissions[Permissions[\"CHANNEL_VOICE_CONNECT_PASSIVE\"] = 20] = \"CHANNEL_VOICE_CONNECT_PASSIVE\";\n Permissions[Permissions[\"CHANNEL_VOICE_SPEAK_KEY_ONLY\"] = 21] = \"CHANNEL_VOICE_SPEAK_KEY_ONLY\";\n Permissions[Permissions[\"CHANNEL_VOICR_SPEAK_FREE\"] = 22] = \"CHANNEL_VOICR_SPEAK_FREE\";\n Permissions[Permissions[\"CHANNEL_VOICE_SPEAK\"] = 23] = \"CHANNEL_VOICE_SPEAK\";\n Permissions[Permissions[\"GUILD_USER_DEAFEN\"] = 24] = \"GUILD_USER_DEAFEN\";\n Permissions[Permissions[\"GUILD_USER_MUTEGUILD_USER_NAME_CHANGE_OTHER\"] = 25] = \"GUILD_USER_MUTEGUILD_USER_NAME_CHANGE_OTHER\";\n Permissions[Permissions[\"GUILD_USER_NAME_CHANGE_OTHER\"] = 26] = \"GUILD_USER_NAME_CHANGE_OTHER\";\n Permissions[Permissions[\"CHANNEL_VOICE_BGM\"] = 27] = \"CHANNEL_VOICE_BGM\";\n})(Permissions || (Permissions = {}));\nexport function hasPermission(permissions, permission) {\n return (permissions & (1 << permission)) === (1 << permission);\n}\nexport var GuildMute;\n(function (GuildMute) {\n let Type;\n (function (Type) {\n Type[Type[\"mic\"] = 1] = \"mic\";\n Type[Type[\"headset\"] = 2] = \"headset\";\n })(Type = GuildMute.Type || (GuildMute.Type = {}));\n})(GuildMute || (GuildMute = {}));\nexport class Internal {\n request;\n constructor(request) {\n this.request = request;\n }\n static define(name, method, path) {\n Object.defineProperty(Internal.prototype, name, {\n configurable: true,\n writable: true,\n value: async function (payload) {\n return await invoke(this.request, method, path, payload);\n },\n });\n }\n}\nInternal.define('getGuildList', 'GET', '/guild/list');\nInternal.define('getGuildView', 'GET', '/guild/view');\nInternal.define('getGuildUserList', 'GET', '/guild/user-list');\nInternal.define('setGuildUserNickname', 'POST', '/guild/nickname');\nInternal.define('leaveGuild', 'POST', '/guild/leave');\nInternal.define('kickoutGuildUser', 'POST', '/guild/kickout');\nInternal.define('getGuildMuteList', 'GET', '/guild-mute/list');\nInternal.define('createGuildMute', 'POST', '/guild-mute/create');\nInternal.define('deleteGuildMute', 'POST', '/guild-mute/delete');\nInternal.define('getGuildBoostHistory', 'GET', '/guild-boost/history');\nInternal.define('getChannelList', 'GET', '/channel/list');\nInternal.define('getChannelView', 'GET', '/channel/view');\nInternal.define('createChannel', 'POST', '/channel/create');\nInternal.define('updateChannel', 'POST', '/channel/update');\nInternal.define('deleteChannel', 'POST', '/channel/delete');\nInternal.define('getChannelUserList', 'GET', '/channel/user-list');\nInternal.define('kickChannelUser', 'POST', '/channel/kickout');\nInternal.define('moveChannelUser', 'POST', '/channel/move-user');\nInternal.define('getChannelRoleIndex', 'GET', '/channel-role/index');\nInternal.define('createChannelRole', 'POST', '/channel-role/create');\nInternal.define('updateChannelRole', 'POST', '/channel-role/update');\nInternal.define('deleteChannelRole', 'POST', '/channel-role/delete');\nInternal.define('getMessageList', 'GET', '/message/list');\nInternal.define('getMessageView', 'GET', '/message/view');\nInternal.define('createMessage', 'POST', '/message/create');\nInternal.define('updateMessage', 'POST', '/message/update');\nInternal.define('deleteMessage', 'POST', '/message/delete');\nInternal.define('getMessageReactionList', 'GET', '/message/reaction-list');\nInternal.define('addMessageReaction', 'POST', '/message/add-reaction');\nInternal.define('deleteMessageReaction', 'POST', '/message/delete-reaction');\nInternal.define('getChannelJoinedUserList', 'GET', '/channel-user/get-joined-channel');\nInternal.define('getPrivateChatList', 'GET', '/user-chat/list');\nInternal.define('getPrivateChatView', 'GET', '/user-chat/view');\nInternal.define('createPrivateChat', 'POST', '/user-chat/create');\nInternal.define('deletePrivateChat', 'POST', '/user-chat/delete');\nInternal.define('getDirectMessageList', 'GET', '/direct-message/list');\nInternal.define('createDirectMessage', 'POST', '/direct-message/create');\nInternal.define('updateDirectMessage', 'POST', '/direct-message/update');\nInternal.define('deleteDirectMessage', 'POST', '/direct-message/delete');\nInternal.define('getDirectMessageReactionList', 'GET', '/direct-message/reaction-list');\nInternal.define('addDirectMessageReaction', 'POST', '/direct-message/add-reaction');\nInternal.define('deleteDirectMessageReaction', 'POST', '/direct-message/delete-reaction');\nInternal.define('getGateway', 'GET', '/gateway/index');\nInternal.define('getToken', 'POST', '/oauth2/token');\nInternal.define('createAsset', 'POST', '/asset/create');\nInternal.define('getUserMe', 'GET', '/user/me');\nInternal.define('getUserView', 'GET', '/user/view');\nInternal.define('offline', 'POST', '/user/offline');\nInternal.define('getGuildRoleList', 'GET', '/guild-role/list');\nInternal.define('createGuildRole', 'POST', '/guild-role/create');\nInternal.define('updateGuildRole', 'POST', '/guild-role/update');\nInternal.define('deleteGuildRole', 'POST', '/guild-role/delete');\nInternal.define('grantGuildRole', 'POST', '/guild-role/grant');\nInternal.define('revokeGuildRole', 'POST', '/guild-role/revoke');\nInternal.define('getIntimacy', 'GET', '/intimacy/index');\nInternal.define('updateIntimacy', 'POST', '/intimacy/update');\nInternal.define('getGuildEmojiList', 'GET', '/guild-emoji/list');\nInternal.define('createGuildEmoji', 'POST', '/guild-emoji/create');\nInternal.define('updateGuildEmoji', 'POST', '/guild-emoji/update');\nInternal.define('deleteGuildEmoji', 'POST', '/guild-emoji/delete');\nInternal.define('getInviteList', 'GET', '/invite/list');\nInternal.define('createInvite', 'POST', '/invite/create');\nInternal.define('deleteInvite', 'POST', '/invite/delete');\nInternal.define('getBlacklist', 'GET', '/blacklist/list');\nInternal.define('createBlacklist', 'POST', '/blacklist/create');\nInternal.define('deleteBlacklist', 'POST', '/blacklist/delete');\nInternal.define('getGuildBadge', 'GET', '/badge/guild');\nInternal.define('getGameList', 'GET', '/game');\nInternal.define('createGame', 'POST', '/game/create');\nInternal.define('updateGame', 'POST', '/game/update');\nInternal.define('deleteGame', 'POST', '/game/delete');\nInternal.define('createGameActivity', 'POST', '/game/activity');\nInternal.define('deleteGameActivity', 'POST', '/game/delete-activity');\n//# sourceMappingURL=types.js.map","import z from '@deepseek-ai/schemastery';\n/** Validated KOOK adapter configuration. */\nexport const Config = z.object({\n token: z.string().role('secret').required(),\n selfId: z.string().pattern(/^\\d+$/).required(),\n protocol: z.union(['ws', 'http']).required(),\n path: z.string().default('/kook'),\n verifyToken: z.string().role('secret').default(''),\n apiBaseUrl: z.string().role('url').default('https://www.kookapp.cn/api/v3'),\n ws: z\n .object({\n retryTimes: z.natural().default(6),\n retryInterval: z.natural().role('ms').default(5_000),\n retryLazy: z.natural().role('ms').default(60_000),\n })\n .default({}),\n});\n/**\n * The configuration the selected protocol cannot work from.\n *\n * The schema already refuses a missing token or a non-numeric `selfId`; what it cannot express is which credential a\n * protocol needs, so that check runs when the plugin loads and names the corrective action.\n *\n * @param config - the validated configuration.\n * @returns the configuration error, or undefined when the selection is complete.\n */\nexport function configError(config) {\n let url;\n try {\n url = new URL(config.apiBaseUrl);\n }\n catch {\n return new Error('kook: apiBaseUrl must be an absolute http(s) URL');\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return new Error('kook: apiBaseUrl must be an absolute http(s) URL');\n }\n if (config.protocol === 'http' && config.verifyToken === '') {\n return new Error('kook: protocol \"http\" needs verifyToken (the verify_token KOOK issues for the webhook)');\n }\n return undefined;\n}\n/**\n * Normalize an inbound route path: absolute, no trailing slash.\n * @param path - the configured `path`.\n * @returns the pathname to register.\n */\nexport function routePath(path) {\n const withSlash = path.startsWith('/') ? path : `/${path}`;\n return withSlash.length > 1 ? withSlash.replace(/\\/+$/, '') : withSlash;\n}\n//# sourceMappingURL=config.js.map","import { KookIdentityError } from \"./errors.js\";\nimport { invoke } from \"./request.js\";\n/**\n * Verify that the bot token belongs to the configured bot.\n *\n * The token is an opaque platform-issued string, so the bot id cannot be derived from it; `selfId` is configured and\n * checked here. The host keys `ctx.bots`, `sources.bot` and the intake dedupe key on `bot.id`, so a mismatch is a\n * configuration error that reconnecting cannot fix.\n *\n * @param request - endpoints for this bot.\n * @param selfId - the configured bot user id.\n * @param signal - cancellation of the transport that asked.\n * @returns the bot's own user record.\n * @throws KookIdentityError when `/user/me` reports another account.\n */\nexport async function verifyIdentity(request, selfId, signal) {\n const user = await invoke(request, 'GET', '/user/me', undefined, signal);\n const actual = user === undefined || user === null ? '' : String(user.id);\n if (actual !== selfId) {\n throw new KookIdentityError(`kook: selfId is configured as ${selfId} but the bot token belongs to ${actual === '' ? 'an unknown account' : actual}; fix selfId and restart`);\n }\n return user;\n}\n//# sourceMappingURL=identity.js.map","/**\n * KMarkdown text handling: the escaping the platform requires, the inbound `(met|chn|rol)` tokens, and the\n * visible-length splitter the message budgets use.\n *\n * Escaping follows the upstream adapter exactly: a backslash goes in front of `\\`, `*`, `` ` ``, `~`, `(` and `)`, so\n * user text cannot open a control sequence or a formatting run. `[` and `]` stay unescaped because a lone one is\n * harmless.\n */\nimport { h } from '@deepseek-ai/cordis-plugin-im-core';\n/**\n * Escape user text for KMarkdown.\n * @param text - plain text.\n * @returns the text with the six metacharacters escaped.\n */\nexport function escapeKMarkdown(text) {\n return text.replace(/[\\\\*`~()]/g, '\\\\$&');\n}\n/**\n * Undo KMarkdown escaping.\n * @param text - escaped text.\n * @returns the text with `\\x` collapsed to `x`.\n */\nexport function unescapeKMarkdown(text) {\n return text.replace(/\\\\(.)/g, '$1');\n}\n/** Token of one kmarkdown control sequence, including the emoji form. */\nconst CONTROL = /^\\((met|chn|rol)\\)([\\w-]+)\\(\\1\\)/;\nconst EMOJI = /^\\(emj\\)([^()]*)\\(emj\\)\\[([^\\]]*)\\]/;\n/**\n * Parse the kmarkdown body of one message into content elements.\n *\n * Only the control sequences KOOK defines are interpreted; markdown syntax (`**bold**`, `> quote`, fences) stays in\n * the text as the platform sent it, because rewriting the source would show the model something the user did not\n * write.\n *\n * @param content - `d.content` of a kind-9 message.\n * @param names - mention and role names of `extra.kmarkdown`.\n * @returns the decoded content nodes, in source order.\n */\nexport function parseKMarkdown(content, names = {}) {\n const users = names.users ?? [];\n const roles = names.roles ?? [];\n const elements = [];\n let buffer = '';\n let rest = content;\n const flush = () => {\n if (buffer === '')\n return;\n elements.push(h.text(buffer));\n buffer = '';\n };\n while (rest !== '') {\n if (rest.startsWith('\\\\') && rest.length > 1) {\n buffer += rest[1];\n rest = rest.slice(2);\n continue;\n }\n const control = CONTROL.exec(rest);\n if (control !== null) {\n const whole = control.at(0) ?? '';\n const kind = control.at(1) ?? '';\n const id = control.at(2) ?? '';\n rest = rest.slice(whole.length);\n flush();\n if (kind === 'met') {\n if (id === 'all' || id === 'here') {\n elements.push(h('at', { type: id }));\n }\n else {\n const name = users.find((user) => user.id === id)?.username;\n elements.push(h('at', {\n type: 'user',\n id,\n ...(name === undefined ? {} : { name }),\n }));\n }\n }\n else if (kind === 'chn') {\n elements.push(h('channel', { id }));\n }\n else {\n const name = roles.find((role) => String(role.role_id) === id)?.name;\n elements.push(h('at', {\n type: 'role',\n id,\n ...(name === undefined ? {} : { name }),\n }));\n }\n continue;\n }\n buffer += rest.charAt(0);\n rest = rest.slice(1);\n }\n flush();\n return elements;\n}\n/** Split a kmarkdown body into the pieces a cut may not break. */\nfunction tokenize(content) {\n const tokens = [];\n let rest = content;\n while (rest !== '') {\n if (rest.startsWith('\\\\') && rest.length > 1) {\n tokens.push({\n raw: rest.slice(0, 2),\n visible: 1,\n newline: false,\n space: false,\n });\n rest = rest.slice(2);\n continue;\n }\n const control = CONTROL.exec(rest) ?? EMOJI.exec(rest);\n if (control !== null) {\n const whole = control.at(0) ?? '';\n tokens.push({ raw: whole, visible: 1, newline: false, space: false });\n rest = rest.slice(whole.length);\n continue;\n }\n const codePoint = rest.codePointAt(0);\n const raw = String.fromCodePoint(codePoint);\n tokens.push({ raw, visible: 1, newline: raw === '\\n', space: raw === ' ' });\n rest = rest.slice(raw.length);\n }\n return tokens;\n}\n/**\n * Visible characters of a kmarkdown body: control sequences and escape pairs count once, like a rendered mention.\n * @param content - kmarkdown text.\n * @returns the number of visible characters.\n */\nexport function visibleLength(content) {\n let length = 0;\n for (const token of tokenize(content))\n length += token.visible;\n return length;\n}\n/**\n * Split a kmarkdown body into chunks of at most `limit` visible characters.\n *\n * The cut prefers the last line break of the window, then the last space, then a hard cut, and it never lands inside\n * an escape pair or a control sequence. Concatenating the chunks returns the input exactly: splitting moves no\n * character and adds no marker.\n *\n * @param content - kmarkdown text.\n * @param limit - visible characters per chunk.\n * @returns the chunks, in order.\n */\nexport function splitKMarkdown(content, limit) {\n const tokens = tokenize(content);\n if (tokens.reduce((sum, token) => sum + token.visible, 0) <= limit)\n return [content];\n const chunks = [];\n let start = 0;\n while (start < tokens.length) {\n let end = start;\n let visible = 0;\n while (end < tokens.length && visible + tokens[end].visible <= limit) {\n visible += tokens[end].visible;\n end += 1;\n }\n if (end === tokens.length) {\n chunks.push(tokens\n .slice(start)\n .map((token) => token.raw)\n .join(''));\n break;\n }\n let cut = end;\n for (let index = end - 1; index >= start; index--) {\n if (tokens[index].newline) {\n cut = index + 1;\n break;\n }\n }\n if (cut === end) {\n for (let index = end - 1; index >= start; index--) {\n if (tokens[index].space) {\n cut = index + 1;\n break;\n }\n }\n }\n if (cut <= start)\n cut = start + 1;\n chunks.push(tokens\n .slice(start, cut)\n .map((token) => token.raw)\n .join(''));\n start = cut;\n }\n return chunks;\n}\n/**\n * Encode the inline kmarkdown of a subtree, for a control that only carries text (a card button).\n * @param nodes - rendered text fragments.\n * @returns the concatenated kmarkdown.\n */\nexport function inlineKMarkdown(nodes) {\n return nodes.map((node) => node.text).join('');\n}\n//# sourceMappingURL=kmarkdown.js.map","/**\n * Draft model of the single `kmarkdown` mode: the node stream, the text/card buffers, the documented card budgets, and\n * the exact request body of one platform message.\n *\n * One logical message is either kmarkdown (`type: 9`) or card JSON (`type: 10`), exactly as the upstream encoder\n * flushes: text alone stays a `type: 9` message, and the first element that needs a card module (media, a button, a\n * divider) turns the whole message into a card.\n */\nimport { isPhrasingContainer } from '@deepseek-ai/satori-element';\nimport { inlineKMarkdown, splitKMarkdown } from \"../kmarkdown.js\";\n/** KOOK's documented bounds; nothing else is a limit. */\nexport const KOOK_LIMITS = {\n /** `content` of one message (\"请不要超过 8000 字符\"). */\n textChars: 8_000,\n /** kmarkdown text of one section/context module. */\n sectionChars: 5_000,\n /** Modules of one card. */\n cardModules: 50,\n /** Buttons of one `action-group`. */\n buttonsPerRow: 4,\n /** Images of one `image-group`. */\n imagesPerGroup: 9,\n /** `page_size` of `/guild/user-list`. */\n membersPageSize: 50,\n};\n/** A paragraph break node. */\nexport const BREAK = { type: 'break' };\n/**\n * One text node holding already encoded kmarkdown.\n * @param text - kmarkdown text.\n * @returns the node.\n */\nexport function textNode(text) {\n return { type: 'text', text };\n}\n/**\n * Group items into runs of at most `size`.\n * @param items - the items, in order.\n * @param size - maximum run length.\n * @returns the runs, in order.\n */\nexport function chunk(items, size) {\n const runs = [];\n for (let start = 0; start < items.length; start += size) {\n runs.push(items.slice(start, start + size));\n }\n return runs;\n}\n/**\n * The card `image-group` runs of an image list (1–9 images each; DSH has no album element yet, so only a future\n * caller uses this).\n * @param images - the images, in order.\n * @returns the groups, in order.\n */\nexport function groupImages(images) {\n return chunk(images, KOOK_LIMITS.imagesPerGroup);\n}\n/**\n * The platform colour of a button theme.\n * @param theme - the element's theme, when it declared one.\n * @returns the KOOK button colour.\n */\nexport function themeOf(theme) {\n switch (theme) {\n case 'info':\n case 'success':\n case 'warning':\n case 'danger':\n return theme;\n default:\n return 'primary';\n }\n}\n/** The name of an outbound attachment: the declared name, else the last path segment of the source. */\nexport function fileName(name, src) {\n if (name !== undefined && name !== '')\n return name;\n try {\n const segment = new URL(src).pathname.split('/').pop();\n if (segment !== undefined && segment !== '')\n return decodeURIComponent(segment);\n }\n catch (error) {\n // Not a URL: the source itself is the best name available.\n error;\n if (src !== '' && !src.includes('/'))\n return src;\n }\n return 'file';\n}\n/** The kmarkdown text of a node list (a button label, a link label). */\nexport function textOf(nodes) {\n return inlineKMarkdown(nodes.filter((node) => node.type === 'text'));\n}\n/**\n * Wrap every text run of a node list with one kmarkdown construct.\n *\n * Each contiguous text run is wrapped on its own, so a media node between two runs never leaves a marker open across\n * the card module boundary. Nested marks compose (`<b><i>x</i></b>` → `***x***`), as the upstream encoder emits.\n *\n * @param nodes - rendered children.\n * @param open - opening marker.\n * @param close - closing marker, `open` when symmetric.\n * @returns the children with their text runs wrapped.\n */\nexport function withMark(nodes, open, close = open) {\n const out = [];\n let run = [];\n const flush = () => {\n if (run.length === 0)\n return;\n out.push(textNode(open + run.join('') + close));\n run = [];\n };\n for (const node of nodes) {\n if (node.type === 'text') {\n run.push(node.text);\n continue;\n }\n flush();\n out.push(node);\n }\n flush();\n return out;\n}\n/**\n * Prefix every line of a node list with the quote marker.\n * @param nodes - rendered children.\n * @returns the children with `> ` at the start of every line.\n */\nexport function quoteLines(nodes) {\n const out = [];\n let atLineStart = true;\n for (const node of nodes) {\n if (node.type === 'break') {\n // A paragraph boundary starts a line; the next text node of a nested quote gets its own marker.\n atLineStart = true;\n out.push(node);\n continue;\n }\n if (node.type !== 'text') {\n out.push(node);\n continue;\n }\n let text = '';\n for (const char of node.text) {\n if (atLineStart && char !== '\\n')\n text += '> ';\n text += char;\n atLineStart = char === '\\n';\n }\n out.push(textNode(text));\n }\n return out;\n}\n/**\n * The media node of one attachment element, reporting a phrasing-position attachment as `moved`.\n * @param el - one of `img`/`audio`/`video`/`file`.\n * @param ctx - render context of the mode.\n * @returns the node.\n */\nexport function mediaNode(el, ctx) {\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n if (parent !== undefined && isPhrasingContainer(parent.type)) {\n ctx.report.moved.push({\n tag: el.type,\n reason: 'kook-media-split',\n path: ctx.stableId(el),\n });\n }\n switch (el.type) {\n case 'img':\n return { type: 'image', ref: ctx.resource('image', el.attrs.src, {}) };\n case 'audio':\n return {\n type: 'media',\n kind: 'audio',\n ref: ctx.resource('audio', el.attrs.src, el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n title: fileName(el.attrs.name, el.attrs.src),\n };\n case 'video':\n return {\n type: 'media',\n kind: 'video',\n ref: ctx.resource('video', el.attrs.src, el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n title: fileName(el.attrs.name, el.attrs.src),\n };\n case 'file':\n return {\n type: 'media',\n kind: 'file',\n ref: ctx.resource('file', el.attrs.src, el.attrs.name === undefined ? {} : { name: el.attrs.name }),\n title: fileName(el.attrs.name, el.attrs.src),\n };\n }\n}\n/**\n * Fold the rendered node stream into platform messages.\n *\n * Text accumulates in one buffer; the first media, button or divider element turns the message into a card and every\n * text run becomes a `section`. A card holds at most 50 modules, a section at most 5,000 visible characters, and a\n * kmarkdown message at most 8,000: the buffer is cut at those bounds and each extra platform message is reported as a\n * split. The result is never empty.\n *\n * @param nodes - rendered nodes in document order.\n * @param ctx - render context, for the split and moved report.\n * @returns one draft per platform message.\n */\nexport function assembleDraft(nodes, ctx) {\n const drafts = [];\n let text = '';\n let modules = [];\n let card = false;\n const flushCard = () => {\n if (modules.length === 0)\n return;\n drafts.push({ kind: 'card', modules });\n modules = [];\n };\n const pushModule = (module) => {\n card = true;\n modules.push(module);\n // A card accepts at most 50 modules; the next one starts another message, so a card never exceeds its budget.\n if (modules.length >= KOOK_LIMITS.cardModules)\n flushCard();\n };\n const flushText = () => {\n const content = text.trim();\n text = '';\n if (content === '')\n return;\n for (const section of splitKMarkdown(content, KOOK_LIMITS.sectionChars)) {\n pushModule({ type: 'section', content: section });\n }\n };\n const lineBreak = () => {\n if (text === '')\n return;\n if (text.endsWith('\\n'))\n return;\n text += '\\n';\n };\n for (const node of nodes) {\n switch (node.type) {\n case 'text':\n text += node.text;\n break;\n case 'break':\n lineBreak();\n break;\n case 'divider':\n flushText();\n pushModule({ type: 'divider' });\n break;\n case 'image':\n flushText();\n pushModule({ type: 'container', image: { ref: node.ref } });\n break;\n case 'media':\n flushText();\n pushModule({\n type: 'media',\n kind: node.kind,\n ref: node.ref,\n title: node.title,\n });\n break;\n case 'buttons':\n flushText();\n pushModule({ type: 'buttons', buttons: node.buttons });\n break;\n }\n }\n if (card) {\n flushText();\n flushCard();\n }\n else {\n const content = text.trim();\n if (content !== '') {\n for (const part of splitKMarkdown(content, KOOK_LIMITS.textChars)) {\n drafts.push({ kind: 'text', content: part });\n }\n }\n }\n if (drafts.length === 0)\n drafts.push({ kind: 'text', content: '\\u2060' });\n ctx.report.split += drafts.length - 1;\n return drafts;\n}\n/** The resource key `prepare` resolved for one media source. */\nfunction resolvedKey(prepared, ref) {\n const resolved = prepared.resolved.get(ref);\n if (resolved === undefined) {\n throw new Error('kook: the media was not prepared before serialize');\n }\n return resolved.key;\n}\n/** One image as a card element. */\nfunction imageOf(prepared, image) {\n return { type: 'image', src: resolvedKey(prepared, image.ref) };\n}\n/** One button as a card element. */\nfunction buttonOf(button) {\n return {\n type: 'button',\n theme: button.theme,\n value: button.value,\n click: button.click,\n text: { type: 'kmarkdown', content: button.text },\n };\n}\n/** One draft module as the wire module(s) it produces. */\nfunction modulesOf(prepared, module) {\n switch (module.type) {\n case 'section':\n return [\n {\n type: 'section',\n text: { type: 'kmarkdown', content: module.content },\n },\n ];\n case 'container':\n return [\n { type: 'container', elements: [imageOf(prepared, module.image)] },\n ];\n case 'image-group':\n return groupImages(module.images).map((images) => ({\n type: 'image-group',\n elements: images.map((image) => imageOf(prepared, image)),\n }));\n case 'buttons':\n return chunk(module.buttons, KOOK_LIMITS.buttonsPerRow).map((buttons) => ({\n type: 'action-group',\n elements: buttons.map(buttonOf),\n }));\n case 'divider':\n return [{ type: 'divider' }];\n case 'media':\n return [\n {\n type: module.kind,\n src: resolvedKey(prepared, module.ref),\n title: module.title,\n },\n ];\n }\n}\n/**\n * Build the exact request body of one draft.\n *\n * Only the first platform message answers the quoted one; `SerializeContext.quote` reaches every part, so the adapter\n * picks the one that carries it.\n *\n * @param prepared - the draft with every resource resolved.\n * @param ctx - serialize context (part index and quote).\n * @returns the request body.\n */\nexport function serializeDraft(prepared, ctx) {\n const quote = ctx.index === 0 ? ctx.quote : undefined;\n const common = quote === undefined ? {} : { quote };\n if (prepared.draft.kind === 'text') {\n return { kind: 'text', type: 9, content: prepared.draft.content, ...common };\n }\n const card = {\n type: 'card',\n modules: prepared.draft.modules.flatMap((module) => modulesOf(prepared, module)),\n };\n return { kind: 'card', type: 10, content: JSON.stringify([card]), ...common };\n}\n//# sourceMappingURL=shared.js.map","/**\n * The single `kmarkdown` mode: KOOK message text with its KMarkdown markup, and a card when the content needs one.\n *\n * Native tags are the ones the upstream encoder renders (`text`, `p`, `br`, `b`, `i`, `u`, `s`, `spoiler`, `code`,\n * `a`, `at`, `channel`, `emoji`) plus the block structure KMarkdown shows as text (headings, lists, quotes, fences, a\n * divider) and the media and buttons that only a card module can carry. A `<button type=\"input\">` is not declared: a\n * click that sends a text as the reader has no card component, so the core fallback renders its label and command.\n * Everything else takes the core fallback, which keeps its text — the platform has no second way to render it.\n */\nimport { defineMode, ElementRegistry } from '@deepseek-ai/cordis-plugin-im-core';\nimport { isPhrasingContainer } from '@deepseek-ai/satori-element';\nimport { escapeKMarkdown } from \"../kmarkdown.js\";\nimport { assembleDraft, BREAK, chunk, KOOK_LIMITS, mediaNode, quoteLines, serializeDraft, textNode, textOf, themeOf, withMark, } from \"./shared.js\";\n/** Drop the paragraph breaks a container put in front of its content, so a list marker is not followed by a newline. */\nfunction withoutLeadingBreaks(nodes) {\n let start = 0;\n while (start < nodes.length && nodes[start].type === 'break')\n start += 1;\n return nodes.slice(start);\n}\n/** The nodes of a render without its text runs, for a construct that carries the text in its own markup. */\nfunction nonText(nodes) {\n return nodes.filter((node) => node.type !== 'text');\n}\n/** A heading: KMarkdown has no heading syntax, so a bold line stands in. */\nfunction heading(nodes) {\n return [BREAK, ...withMark(nodes, '**'), BREAK];\n}\n/** The action button of one `<button>` element. */\nfunction actionButton(el, ctx) {\n const label = textOf(ctx.render(el.children)).trim();\n if (el.attrs.type === 'link') {\n return {\n click: 'link',\n value: el.attrs.href,\n text: label === '' ? escapeKMarkdown(el.attrs.href) : label,\n theme: themeOf(el.attrs.theme),\n };\n }\n // `action` and `submit` both report their id back; the input variant never reaches a handler (not declared).\n const id = el.attrs.type === 'input' ? '' : el.attrs.id;\n return {\n click: 'return-val',\n value: id,\n text: label === '' ? escapeKMarkdown(id) : label,\n theme: themeOf(el.attrs.theme),\n };\n}\n/**\n * Build the `kmarkdown` mode.\n * @returns the only mode of this adapter.\n */\nexport function createKmarkdownMode() {\n const elements = new ElementRegistry()\n .register('text', (el) => textNode(escapeKMarkdown(el.attrs.content)))\n .register('p', (el, ctx) => [BREAK, ...ctx.render(el.children), BREAK])\n .register('br', () => textNode('\\n'))\n .register('b', (el, ctx) => withMark(ctx.render(el.children), '**'))\n .register('i', (el, ctx) => withMark(ctx.render(el.children), '*'))\n .register('u', (el, ctx) => withMark(ctx.render(el.children), '(ins)'))\n .register('s', (el, ctx) => withMark(ctx.render(el.children), '~~'))\n .register('spoiler', (el, ctx) => withMark(ctx.render(el.children), '(spl)'))\n .register('code', (el, ctx) => textNode(`\\`${ctx.text(el.children)}\\``))\n .register('pre', (el, ctx) => {\n const language = el.attrs.lang ?? '';\n return textNode(`\\`\\`\\`${language}\\n${ctx.text(el.children)}\\n\\`\\`\\``);\n }, { variants: ['lang'] })\n .register('a', (el, ctx) => {\n const children = ctx.render(el.children);\n const label = textOf(children).trim();\n return [\n textNode(`[${label === '' ? escapeKMarkdown(el.attrs.href) : label}](${el.attrs.href})`),\n ...nonText(children),\n ];\n })\n .register('at', (el) => {\n switch (el.attrs.type) {\n case 'user':\n return el.attrs.id === undefined\n ? textNode(escapeKMarkdown(`@${el.attrs.name ?? ''}`))\n : textNode(`(met)${el.attrs.id}(met)`);\n case 'all':\n return textNode('(met)all(met)');\n case 'here':\n return textNode('(met)here(met)');\n case 'role':\n return el.attrs.id === undefined\n ? textNode(escapeKMarkdown(`@${el.attrs.name ?? ''}`))\n : textNode(`(rol)${el.attrs.id}(rol)`);\n }\n }, { variants: ['user', 'all', 'here', 'role'] })\n .register('channel', (el) => textNode(`(chn)${el.attrs.id}(chn)`))\n .register('emoji', (el) => {\n const name = el.attrs.name ?? '';\n // `(emj)name(emj)[id]` names the guild emoji and falls back to its short code when the id is unknown.\n return el.attrs.id === '' || name === ''\n ? textNode(`:${name}:`)\n : textNode(`(emj)${name}(emj)[${el.attrs.id}]`);\n })\n .register('h1', (el, ctx) => heading(ctx.render(el.children)))\n .register('h2', (el, ctx) => heading(ctx.render(el.children)))\n .register('h3', (el, ctx) => heading(ctx.render(el.children)))\n .register('h4', (el, ctx) => heading(ctx.render(el.children)))\n .register('h5', (el, ctx) => heading(ctx.render(el.children)))\n .register('h6', (el, ctx) => heading(ctx.render(el.children)))\n .register('ul', (el, ctx) => [BREAK, ...ctx.render(el.children), BREAK])\n .register('ol', (el, ctx) => [BREAK, ...ctx.render(el.children), BREAK])\n .register('li', (el, ctx) => {\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n if (parent?.type !== 'ol') {\n return [\n textNode('• '),\n ...withoutLeadingBreaks(ctx.render(el.children)),\n BREAK,\n ];\n }\n const index = Math.max(parent.children.indexOf(el), 0);\n const start = parent.attrs.start ?? 1;\n return [\n textNode(`${start + index}. `),\n ...withoutLeadingBreaks(ctx.render(el.children)),\n BREAK,\n ];\n })\n .register('blockquote', (el, ctx) => quoteLines(ctx.render(el.children)))\n .register('hr', () => ({ type: 'divider' }))\n .register('img', (el, ctx) => mediaNode(el, ctx), { variants: ['inline'] })\n .register('audio', (el, ctx) => mediaNode(el, ctx))\n .register('video', (el, ctx) => mediaNode(el, ctx))\n .register('file', (el, ctx) => mediaNode(el, ctx))\n // `input` is deliberately not declared: the core fallback keeps the label and command text and reports the\n // dropped interaction.\n .register('button', (el, ctx) => {\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n if (parent !== undefined && isPhrasingContainer(parent.type)) {\n ctx.report.moved.push({\n tag: 'button',\n reason: 'kook-button-lifted',\n path: ctx.stableId(el),\n });\n }\n return { type: 'buttons', buttons: [actionButton(el, ctx)] };\n }, { variants: ['action', 'link', 'submit', 'theme', 'inline'] })\n .register('button-group', (el, ctx) => {\n const buttons = [];\n for (const node of ctx.render(el.children)) {\n if (node.type === 'buttons')\n buttons.push(...node.buttons);\n }\n return chunk(buttons, KOOK_LIMITS.buttonsPerRow).map((group) => ({\n type: 'buttons',\n buttons: group,\n }));\n });\n return defineMode()({\n id: 'kmarkdown',\n elements,\n limits: {\n 'limit.text.chars': KOOK_LIMITS.textChars,\n 'limit.buttons.row': KOOK_LIMITS.buttonsPerRow,\n },\n assemble: (nodes, _envelope, ctx) => assembleDraft(nodes, ctx),\n serialize: (prepared, ctx) => serializeDraft(prepared, ctx),\n });\n}\n//# sourceMappingURL=kmarkdown.js.map","/**\n * Inbound decoding: one received KOOK payload becomes an intake `Session`, and one message object becomes an\n * `InboundMessage`.\n *\n * The event kinds the vocabulary can carry are chat messages (types 1/2/3/4/8/9/10), button clicks, deletions and\n * reactions; everything else is dropped with a debug line. A card is decoded module by module because KOOK now sends\n * file messages as cards, so skipping a card would lose the file; an unknown module keeps a text placeholder instead\n * of the whole card.\n */\nimport { h, normalize } from '@deepseek-ai/cordis-plugin-im-core';\nimport { parseKMarkdown } from \"./kmarkdown.js\";\nimport { Type } from \"./types.js\";\nfunction asRecord(value) {\n return typeof value === 'object' && value !== null\n ? value\n : undefined;\n}\nfunction asString(value) {\n return typeof value === 'string' ? value : undefined;\n}\nfunction asNumber(value) {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\nfunction asArray(value) {\n return Array.isArray(value) ? value : [];\n}\n/** A timestamp in milliseconds, from the event or the clock. */\nfunction timeOf(data) {\n return data.msg_timestamp || Date.now();\n}\n/**\n * The chat one message event belongs to.\n *\n * A group message names its channel in `target_id`; a private one names the conversation (`chat_code`) in\n * `extra.code`, which is the id `/user-chat/create-msg` addresses. That field is the adapter's riskiest assumption on\n * the wire, so it is decoded exactly as the upstream adapter does.\n */\nexport function chatOfMessage(data, extra, bot) {\n // The migrated type narrows `channel_type` to the two documented values; a broadcast is a third one on the wire.\n const channelType = data.channel_type;\n if (channelType === 'GROUP') {\n return {\n id: data.target_id,\n type: 'group',\n ...(extra.channel_name === undefined || extra.channel_name === ''\n ? {}\n : { name: extra.channel_name }),\n };\n }\n if (channelType === 'BROADCAST') {\n // DSH has no broadcast semantics; a broadcast is a group message to every channel it reached.\n bot.ctx.logger.debug('kook: a BROADCAST message arrives as a group message');\n return { id: data.target_id, type: 'group' };\n }\n return { id: extra.code ?? '', type: 'direct' };\n}\n/** The first non-empty name: an empty guild nickname falls back to the account name. */\nfunction nameOf(...names) {\n for (const name of names) {\n if (name !== undefined && name !== '')\n return name;\n }\n return undefined;\n}\n/** A user reference: the id a mention addresses, the name people see, and whether the account is a bot. */\nexport function userRefOf(user) {\n if (user === undefined)\n return { id: '' };\n const name = nameOf(user.nickname, user.username);\n return {\n id: String(user.id ?? ''),\n ...(name === undefined ? {} : { name }),\n ...(user.bot === true ? { isBot: true } : {}),\n };\n}\n/** A user reference from one untyped wire record (`user_info`, `target_info`). */\nfunction userRefFromRecord(record) {\n const id = asString(record.id) ?? '';\n const name = nameOf(asString(record.nickname), asString(record.username));\n return {\n id,\n ...(name === undefined ? {} : { name }),\n ...(record.bot === true ? { isBot: true } : {}),\n };\n}\n/** The referrer of one message, handed back as `Target.referrer` so a reply can name the message it answers. */\nexport function referrerOf(chat, messageId, guildId) {\n return {\n chatId: chat.id,\n channelType: chat.type === 'group' ? 'GROUP' : 'PERSON',\n messageId,\n ...(guildId === undefined || guildId === '' ? {} : { guildId }),\n };\n}\n/** The mention names KOOK reported alongside a kmarkdown message. */\nfunction mentionNames(meta) {\n const kmarkdown = meta?.kmarkdown;\n if (kmarkdown === undefined)\n return {};\n return {\n ...(kmarkdown.mention_part === undefined\n ? {}\n : { users: kmarkdown.mention_part }),\n ...(kmarkdown.mention_role_part === undefined\n ? {}\n : { roles: kmarkdown.mention_role_part }),\n };\n}\n/**\n * Decode the body of one message by its platform type.\n * @param base - the `type`/`content` pair of the message (an event or a read row).\n * @param meta - the metadata carrying attachments, mention names and the quote.\n * @returns the content nodes, in platform order.\n */\nexport function decodeContent(base, meta) {\n const attachment = meta?.attachments;\n const name = attachment?.name;\n switch (base.type) {\n case Type.text:\n return parseTextMentions(base.content);\n case Type.image: {\n const width = asNumber(attachment?.width);\n const height = asNumber(attachment?.height);\n return [\n h('img', {\n src: base.content,\n ...(name === undefined ? {} : { alt: name }),\n ...(width === undefined ? {} : { width }),\n ...(height === undefined ? {} : { height }),\n }),\n ];\n }\n case Type.video: {\n const duration = asNumber(attachment?.duration);\n return [\n h('video', {\n src: base.content,\n ...(name === undefined ? {} : { name }),\n ...(duration === undefined ? {} : { duration }),\n }),\n ];\n }\n case Type.file: {\n const size = asNumber(attachment?.size);\n return [\n h('file', {\n src: base.content,\n ...(name === undefined ? {} : { name }),\n ...(size === undefined ? {} : { size }),\n }),\n ];\n }\n case Type.audio: {\n const duration = asNumber(attachment?.duration);\n return [\n h('audio', {\n src: base.content,\n ...(name === undefined ? {} : { name }),\n ...(duration === undefined ? {} : { duration }),\n }),\n ];\n }\n case Type.kmarkdown:\n return parseKMarkdown(base.content, mentionNames(meta));\n case Type.card:\n return decodeCard(base.content);\n default:\n return base.content === '' ? [] : [h.text(base.content)];\n }\n}\n/**\n * Parse the mentions of a plain-text message: `@name#id`, `@全体成员`, `@在线成员`, `@role:<id>;` and\n * `#channel:<id>;`.\n *\n * The upstream pattern had no `g` flag, so only the first mention of a message was decoded; every occurrence is\n * decoded here so the model sees the whole mention list.\n *\n * @param content - `d.content` of a type-1 message.\n * @returns the decoded content nodes.\n */\nexport function parseTextMentions(content) {\n const pattern = /@role:(\\d+);|#channel:(\\d+);|@全体成员|@在线成员|@(.+?)#(\\d+)/g;\n const elements = [];\n let last = 0;\n for (let match = pattern.exec(content); match !== null; match = pattern.exec(content)) {\n if (match.index > last)\n elements.push(h.text(content.slice(last, match.index)));\n const whole = match[0] ?? '';\n const role = match[1];\n const channel = match[2];\n const name = match[3];\n const id = match[4];\n if (whole === '@全体成员')\n elements.push(h('at', { type: 'all' }));\n else if (whole === '@在线成员')\n elements.push(h('at', { type: 'here' }));\n else if (role !== undefined)\n elements.push(h('at', { type: 'role', id: role }));\n else if (channel !== undefined)\n elements.push(h('channel', { id: channel }));\n else\n elements.push(h('at', {\n type: 'user',\n id: id ?? '',\n ...(name === undefined ? {} : { name }),\n }));\n last = match.index + whole.length;\n }\n if (last < content.length)\n elements.push(h.text(content.slice(last)));\n return elements;\n}\n/**\n * Decode a card message body (`type: 10`).\n *\n * @param content - the card JSON array, serialized as a string.\n * @returns the decoded content nodes; the raw text when the body is not JSON.\n */\nexport function decodeCard(content) {\n let parsed;\n try {\n parsed = JSON.parse(content);\n }\n catch (error) {\n // A body that is not JSON is still content the user sent; show its text instead of dropping the message.\n error;\n return content === '' ? [] : [h.text(content)];\n }\n const cards = Array.isArray(parsed) ? parsed : [parsed];\n const nodes = [];\n for (const card of cards) {\n const record = asRecord(card);\n if (record === undefined)\n continue;\n for (const module of asArray(record.modules))\n nodes.push(...decodeModule(module));\n }\n return nodes;\n}\n/** The content nodes of one card module. */\nfunction decodeModule(raw) {\n const module = asRecord(raw);\n if (module === undefined)\n return [];\n const type = asString(module.type);\n switch (type) {\n case 'section': {\n const nodes = decodeCardText(module.text);\n const accessory = asRecord(module.accessory);\n if (accessory !== undefined)\n nodes.push(...decodeAccessory(accessory));\n return nodes;\n }\n case 'header': {\n const text = cardPlainText(module.text);\n return text === '' ? [] : [h('p', h('b', text))];\n }\n case 'container':\n case 'image-group':\n case 'context':\n case 'action-group':\n return asArray(module.elements).flatMap((element) => decodeAccessory(element));\n case 'divider':\n return [h('hr')];\n case 'file':\n case 'audio':\n case 'video': {\n const src = asString(module.src) ?? '';\n if (src === '')\n return [];\n const title = asString(module.title) ?? '';\n return [h(type, { src, ...(title === '' ? {} : { name: title }) })];\n }\n case 'countdown':\n return [h.text('[倒计时]')];\n case 'invite':\n return [h.text('[邀请]')];\n default:\n // A module the adapter does not know keeps a placeholder so the card's other content is not lost.\n return type === undefined ? [] : [h.text(`[${type}]`)];\n }\n}\n/** The content nodes of a card `section.text` (a text object or a `paragraph` of fields). */\nfunction decodeCardText(raw) {\n const text = asRecord(raw);\n if (text === undefined)\n return [];\n if (text.type === 'paragraph') {\n const nodes = [];\n for (const field of asArray(text.fields)) {\n if (nodes.length > 0)\n nodes.push(h.text('\\n'));\n nodes.push(...decodeCardText(field));\n }\n return nodes;\n }\n const content = asString(text.content) ?? '';\n if (content === '')\n return [];\n return text.type === 'plain-text'\n ? [h.text(content)]\n : parseKMarkdown(content);\n}\n/** The plain text of a card text object. */\nfunction cardPlainText(raw) {\n const text = asRecord(raw);\n return text === undefined ? '' : (asString(text.content) ?? '');\n}\n/** The content nodes of one card accessory (image or button). */\nfunction decodeAccessory(raw) {\n const accessory = asRecord(raw);\n if (accessory === undefined)\n return [];\n if (accessory.type === 'plain-text' || accessory.type === 'kmarkdown') {\n // A `context` element may be a text object; the same text types a section uses.\n return decodeCardText(accessory);\n }\n if (accessory.type === 'image') {\n const src = asString(accessory.src) ?? '';\n return src === '' ? [] : [h('img', { src })];\n }\n if (accessory.type === 'button') {\n const label = asString(asRecord(accessory.text)?.content) ?? '';\n const value = asString(accessory.value) ?? '';\n return [\n accessory.click === 'link'\n ? h('button', { type: 'link', href: value }, label === '' ? value : label)\n : h('button', { type: 'action', id: value }, label === '' ? value : label),\n ];\n }\n const type = asString(accessory.type);\n return type === undefined ? [] : [h.text(`[${type}]`)];\n}\n/** Collect what one decoded message mentions, from the decoded content and the platform's own mention lists. */\nfunction collectMentions(bot, content, meta) {\n const users = [];\n const seen = new Set();\n const mentions = {\n self: false,\n all: meta?.mention_all === true,\n users,\n };\n const add = (user) => {\n if (user.id === '')\n return;\n if (user.id === bot.selfId)\n mentions.self = true;\n if (seen.has(user.id))\n return;\n seen.add(user.id);\n users.push(user);\n };\n const walk = (element) => {\n if (element.type === 'at') {\n if (element.attrs.type === 'all')\n mentions.all = true;\n else if (element.attrs.type === 'user' &&\n element.attrs.id !== undefined) {\n add({\n id: element.attrs.id,\n ...(element.attrs.name === undefined\n ? {}\n : { name: element.attrs.name }),\n });\n }\n }\n for (const child of element.children)\n walk(child);\n };\n walk(content);\n // The platform's list also covers mentions its content projection left out (a card carries none of its own).\n const names = mentionNames(meta).users ?? [];\n for (const id of meta?.mention ?? []) {\n const name = names.find((user) => user.id === id)?.username;\n add({ id, ...(name === undefined ? {} : { name }) });\n }\n if (meta?.mention_here === true)\n bot.ctx.logger.debug('kook: mention_here is not represented in DSH mentions');\n return mentions;\n}\n/** A bounded description of a body that decoded to no content, so `<raw>` stays small. */\nfunction rawPreview(content) {\n return content.length > 500 ? `${content.slice(0, 500)}…` : content;\n}\n/** Decode one message row into an `InboundMessage` for the given chat. */\nfunction messageOf(bot, base, meta, chat, id, time) {\n const nodes = decodeContent(base, meta);\n const content = normalize(nodes.length > 0\n ? nodes\n : [\n h('raw', {\n platform: 'kook',\n type: String(base.type),\n data: rawPreview(base.content),\n }, ''),\n ]);\n const quote = meta?.quote;\n const quoteNodes = quote === undefined ? [] : decodeContent(quote, quote);\n const quoteAuthor = quote?.author;\n return {\n id,\n chat,\n sender: userRefOf(meta?.author),\n content,\n ...(quote === undefined\n ? {}\n : {\n quote: {\n id: quote.id || quote.rong_id || '',\n ...(quoteAuthor === undefined\n ? {}\n : { sender: userRefOf(quoteAuthor) }),\n ...(quoteNodes.length === 0\n ? {}\n : { content: normalize(quoteNodes) }),\n },\n }),\n mentions: collectMentions(bot, content, meta),\n time,\n referrer: referrerOf(chat, id, meta?.guild_id),\n raw: base,\n };\n}\n/**\n * Decode one event message (`d.type !== 255`).\n * @param bot - the receiving adapter.\n * @param data - the event payload.\n * @returns the decoded inbound message.\n */\nexport function decodeInboundMessage(bot, data) {\n const extra = (data.extra ?? {});\n const chat = chatOfMessage(data, extra, bot);\n return messageOf(bot, data, extra, chat, data.msg_id, timeOf(data));\n}\n/**\n * Decode one message read by id (`/message/view`, `/user-chat/view`).\n *\n * @param bot - the adapter that read the message.\n * @param message - the message row.\n * @param chat - the chat the caller asked about; the read answer does not name its type, so the request stands.\n * @returns the decoded inbound message.\n */\nexport function decodeMessage(bot, message, chat) {\n return messageOf(bot, message, message, chat, message.id ?? '', Date.now());\n}\n/** The chat of a deletion or reaction notice. */\nfunction chatOfNotice(body) {\n const channelId = asString(body.channel_id) ?? '';\n if (channelId !== '')\n return { id: channelId, type: 'group' };\n return { id: asString(body.chat_code) ?? '', type: 'direct' };\n}\n/**\n * The chat of a button click.\n *\n * `data.channel_type` is always `PERSON` on a click, even in a guild, so the notice body decides: an explicit\n * `GROUP`, or a missing type with a `target_id`, is a group; otherwise the click came from a direct chat, whose id is\n * the chat code.\n */\nfunction chatOfButton(body) {\n const channelType = asString(body.channel_type);\n const targetId = asString(body.target_id) ?? '';\n if (channelType === 'GROUP' ||\n (channelType === undefined && targetId !== '')) {\n const channelId = asString(body.channel_id) ?? '';\n return { id: channelId !== '' ? channelId : targetId, type: 'group' };\n }\n return { id: asString(body.chat_code) ?? '', type: 'direct' };\n}\n/** Decode one system event: a button click, a deletion or a reaction. */\nfunction decodeNotice(bot, data) {\n const notice = asRecord(data.extra);\n const type = asString(notice?.type);\n const body = asRecord(notice?.body);\n if (notice === undefined || type === undefined || body === undefined)\n return undefined;\n const time = data.msg_timestamp || asNumber(body.event_time) || Date.now();\n switch (type) {\n case 'message_btn_click': {\n const value = asString(body.value) ?? '';\n const messageId = asString(body.msg_id) ?? '';\n const userId = asString(body.user_id) ?? asString(body.author_id) ?? '';\n const chat = chatOfButton(body);\n const info = asRecord(body.user_info);\n const user = info === undefined ? { id: userId } : userRefFromRecord(info);\n return bot.session({\n type: 'interaction/button',\n id: `button:${messageId}:${userId}:${value}`,\n timestamp: time,\n button: {\n bot,\n id: value,\n user,\n chat,\n message: { id: messageId, chat },\n referrer: referrerOf(chat, messageId, asString(body.guild_id)),\n time,\n },\n raw: data,\n });\n }\n case 'deleted_message':\n case 'deleted_private_message': {\n const messageId = asString(body.msg_id) ?? '';\n const chat = chatOfNotice(body);\n return bot.session({\n type: 'message-deleted',\n id: `delete:${messageId}`,\n timestamp: time,\n deleted: { id: messageId, chat },\n raw: data,\n });\n }\n case 'added_reaction':\n case 'private_added_reaction':\n case 'deleted_reaction':\n case 'private_deleted_reaction': {\n const messageId = asString(body.msg_id) ?? '';\n const userId = asString(body.user_id) ?? '';\n const emoji = asString(asRecord(body.emoji)?.id) ?? '';\n const chat = chatOfNotice(body);\n const added = type.includes('added');\n return bot.session({\n type: added ? 'reaction-added' : 'reaction-removed',\n id: `reaction:${added ? 'add' : 'remove'}:${messageId}:${userId}:${emoji}`,\n timestamp: time,\n reaction: {\n message: { id: messageId, chat },\n emoji,\n ...(userId === '' ? {} : { user: { id: userId } }),\n },\n raw: data,\n });\n }\n case 'updated_message':\n case 'updated_private_message':\n // DSH has no consumer for an edited message; saying so beats misreporting it as a new one.\n bot.ctx.logger.debug('kook: ignored an edited-message event');\n return undefined;\n default:\n bot.ctx.logger.debug('kook: ignored the %s system event', type);\n return undefined;\n }\n}\n/**\n * Decode one received payload.\n *\n * @param bot - the receiving adapter, whose `selfId` marks the bot's own mentions.\n * @param data - the payload's `d` field.\n * @returns the session to publish, or undefined for an event this adapter does not carry.\n */\nexport function decodeEvent(bot, data) {\n if (data.type === Type.system)\n return decodeNotice(bot, data);\n const message = decodeInboundMessage(bot, data);\n return bot.session({\n type: 'message',\n id: message.id,\n timestamp: message.time,\n message,\n raw: data,\n });\n}\n//# sourceMappingURL=decode.js.map","/**\n * Outbound hooks: the send pipeline's payload, deletion, member reads and message reads.\n *\n * A channel message goes to `/message/create` (or `/message/view`, `/message/delete`); a direct one goes to the\n * upstream adapter's `/user-chat/*` routes. The two are told apart exactly as upstream tells them apart: a channel id\n * is 16–19 digits and a direct chat code is 32 hexadecimal characters, so the longer id is the direct chat.\n */\nimport { PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\nimport { decodeMessage, userRefOf } from \"./decode.js\";\nimport { KOOK_LIMITS } from \"./modes/shared.js\";\nimport { invoke } from \"./request.js\";\n/** Whether a chat id names a direct chat: a `chat_code` (32 hex characters) is longer than a channel id. */\nexport function isDirectChannel(chatId) {\n return chatId.length > 30;\n}\n/** The platform path of one message operation, by chat kind. */\nfunction pathOf(chatId, channel, direct) {\n return isDirectChannel(chatId) ? direct : channel;\n}\n/** The published part of one sent message. */\nfunction partOf(receipt, kind, target) {\n if (receipt?.msg_id === undefined || receipt.msg_id === '') {\n // The request reached the platform, so an answer without a receipt is a published outcome, not a refusal.\n throw new PlatformError('invalid', 'kook: the platform answered without a msg_id', { published: 'unknown' });\n }\n const referrer = {\n chatId: target.chat.id,\n channelType: target.chat.type === 'group' ? 'GROUP' : 'PERSON',\n messageId: receipt.msg_id,\n };\n return {\n id: receipt.msg_id,\n kind,\n time: receipt.msg_timestamp === undefined ? Date.now() : receipt.msg_timestamp,\n referrer,\n };\n}\n/**\n * Send one serialized payload.\n *\n * @param request - endpoints for this bot.\n * @param payload - the serialized draft (`type: 9` text or `type: 10` card).\n * @param target - the chat the payload goes to.\n * @param _ctx - part index and quote, already applied by `serialize`.\n * @returns the published part.\n */\nexport async function sendPayload(request, payload, target, _ctx) {\n // KOOK chat messages have no threads: `thread: true` has nothing to follow (ignored), an explicit id is refused.\n if (typeof target.thread === 'string') {\n throw new PlatformError('invalid', 'kook has no message threads', {\n published: 'no',\n });\n }\n const direct = isDirectChannel(target.chat.id);\n const body = {\n type: payload.type,\n content: payload.content,\n };\n if (direct)\n body.chat_code = target.chat.id;\n else\n body.target_id = target.chat.id;\n // `serialize` only puts the quote on the first part of a split message.\n if (payload.quote !== undefined)\n body.quote = payload.quote;\n const receipt = await invoke(request, 'POST', direct ? '/user-chat/create-msg' : '/message/create', body);\n return partOf(receipt, payload.kind, target);\n}\n/**\n * Recall one published part.\n * @param request - endpoints for this bot.\n * @param part - the part to recall.\n * @param handle - the message the part belongs to, which names the chat.\n */\nexport async function deletePart(request, part, handle) {\n await invoke(request, 'POST', pathOf(handle.target.chat.id, '/message/delete', '/user-chat/delete-msg'), { msg_id: part.id });\n}\n/** The page number a cursor names; anything unreadable starts at the first page. */\nfunction pageOf(cursor) {\n const page = Number(cursor ?? '');\n return Number.isFinite(page) && page >= 1 ? Math.floor(page) : 1;\n}\n/**\n * List the members of a chat.\n *\n * A group chat pages `/guild/user-list`; the guild id comes from `/channel/view` because the chat only knows its\n * channel. A direct chat has exactly one member, which `/user-chat/view` reports.\n *\n * @param request - endpoints for this bot.\n * @param chat - the chat the caller asked about.\n * @param cursor - page number of the previous page's `next`.\n * @param limit - page size the platform should use (at most 50).\n * @returns one page of members.\n */\nexport async function members(request, chat, cursor, limit) {\n if (isDirectChannel(chat.id)) {\n const view = await invoke(request, 'GET', '/user-chat/view', {\n chat_code: chat.id,\n });\n const target = view?.target_info;\n return { data: target === undefined ? [] : [userRefOf(target)] };\n }\n const page = pageOf(cursor);\n const pageSize = Math.max(1, Math.min(limit ?? KOOK_LIMITS.membersPageSize, KOOK_LIMITS.membersPageSize));\n const channel = await invoke(request, 'GET', '/channel/view', {\n target_id: chat.id,\n });\n if (channel?.guild_id === undefined || channel.guild_id === '') {\n throw new PlatformError('not-found', `kook: channel ${chat.id} names no guild`, { published: 'no' });\n }\n const list = await invoke(request, 'GET', '/guild/user-list', {\n guild_id: channel.guild_id,\n page,\n page_size: pageSize,\n });\n const data = list.items.map((member) => userRefOf(member));\n const total = list.meta?.page_total ?? page;\n return { data, ...(page < total ? { next: String(page + 1) } : {}) };\n}\n/**\n * Read one message by id.\n *\n * The read answer names the channel but not its type, so the requested chat is what the decoded message reports; the\n * host verifies that its id matches the chat it asked about.\n *\n * @param request - endpoints for this bot.\n * @param bot - the adapter, needed to decode the answer.\n * @param chat - the chat the caller asked about.\n * @param id - platform message id.\n * @returns the decoded message.\n */\nexport async function getMessage(request, bot, chat, id) {\n const path = isDirectChannel(chat.id) ? '/user-chat/view' : '/message/view';\n // Both routes take `msg_id` for a message read; `chat_code`/`target_id` are the conversation reads.\n const raw = await invoke(request, 'GET', path, { msg_id: id });\n if (raw === undefined || raw === null || typeof raw !== 'object') {\n throw new PlatformError('not-found', `kook: message ${id} is not in ${chat.id}`, { published: 'no' });\n }\n return decodeMessage(bot, raw, chat);\n}\n//# sourceMappingURL=send.js.map","/**\n * Webhook transport (`protocol: 'http'`).\n *\n * The profile's `webServer` owns the listener, so this transport only registers one anonymous route at `path` and\n * checks every request itself: `verify_token` must match the platform-issued token, and the challenge handshake is\n * answered within the one second KOOK allows.\n *\n * The platform is confirmed only after `bot.receive` accepted the frame; a failure answers `500`, which makes KOOK\n * redeliver (2/4/8/16/32/64 s, at most five times). The cost is that a slow intake occasionally exceeds the one-second\n * challenge budget and triggers a redelivery, which the host de-duplicates on `msg_id`.\n *\n * KOOK only configures callbacks in the developer console, so there is nothing to register with the platform here and\n * no `publicUrl` option; the operator must append `?compress=0` to the callback URL because v1 does not decompress\n * bodies.\n */\nimport { routePath } from \"./config.js\";\nimport { decodeEvent } from \"./decode.js\";\nfunction asRecord(value) {\n return typeof value === 'object' && value !== null\n ? value\n : undefined;\n}\nfunction asString(value) {\n return typeof value === 'string' ? value : undefined;\n}\n/** Read a request body to its end. The adapter imposes no size limit, as the upstream plugin does not. */\nasync function readBody(request) {\n const chunks = [];\n for await (const chunk of request) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n/** Answer one request without a body. */\nfunction writeStatus(response, status, headers = {}) {\n response.writeHead(status, headers);\n response.end();\n}\n/** Message of any caught value, for a log line. */\nfunction messageOf(error) {\n return error instanceof Error ? error.message : String(error);\n}\n/** The Webhook transport of one bot. */\nexport class KookWebhook {\n bot;\n dispose;\n constructor(bot) {\n this.bot = bot;\n }\n /** Register the route; a profile without a web server fails with an actionable message. */\n async start() {\n const webServer = this.bot.ctx.get('webServer');\n if (webServer === undefined) {\n throw this.failStart('kook: protocol \"http\" needs a profile-provided webServer; use protocol \"ws\" instead');\n }\n this.dispose = webServer.register({\n kind: 'exact',\n path: routePath(this.bot.config.path),\n auth: 'anonymous',\n handler: (request, response) => this.handle(request, response),\n });\n // A webhook bot is online as soon as its callback URL is configured on the platform; there is no HELLO.\n this.bot.online();\n }\n /** Release the route. The platform keeps posting to it until the console's callback URL changes. */\n async stop() {\n this.dispose?.();\n this.dispose = undefined;\n }\n /**\n * Log a fatal start failure before the caller throws it, because `Bot.start` only stores a connect failure on\n * `bot.error`.\n * @param message - error text that also names the corrective action.\n * @returns the error for the caller to throw.\n */\n failStart(message) {\n this.bot.ctx.logger.error(message);\n return new Error(message);\n }\n async handle(request, response) {\n try {\n if (request.method !== 'POST') {\n writeStatus(response, 405, { allow: 'POST' });\n return;\n }\n const body = await readBody(request);\n // The platform's JSON is untyped wire data; the fields this handler reads are narrowed one by one below.\n let parsed;\n try {\n parsed = JSON.parse(body);\n }\n catch (error) {\n // A compressed body (the callback URL without `?compress=0`) lands here; the status is the diagnosis.\n this.bot.ctx.logger.warn('kook: cannot parse a webhook body: %s', messageOf(error));\n writeStatus(response, 400);\n return;\n }\n const frame = asRecord(parsed);\n const data = asRecord(frame?.d);\n if (frame === undefined || data === undefined) {\n writeStatus(response, 400);\n return;\n }\n const verifyToken = asString(data.verify_token);\n if (verifyToken !== this.bot.config.verifyToken) {\n writeStatus(response, 403);\n return;\n }\n const challenge = asString(data.challenge);\n if (challenge !== undefined && challenge !== '') {\n // The platform's one-time handshake: answer in under a second with the same string.\n response.writeHead(200, { 'content-type': 'application/json' });\n response.end(JSON.stringify({ challenge }));\n return;\n }\n // `data` is the same object narrowed field by field; the decoder takes the untyped payload whole.\n const rawData = frame.d;\n const session = decodeEvent(this.bot, rawData);\n if (session !== undefined)\n await this.bot.receive(session);\n writeStatus(response, 200);\n }\n catch (error) {\n this.bot.ctx.logger.warn('kook: webhook delivery failed: %s', messageOf(error));\n if (!response.headersSent)\n writeStatus(response, 500);\n else\n response.end();\n }\n }\n}\n//# sourceMappingURL=webhook.js.map","/**\n * Gateway WebSocket transport (`protocol: 'ws'`).\n *\n * The adapter fetches `/gateway/index?compress=0` before **every** dial (KOOK hands out a fresh gateway URL), dials it\n * with the `http` service and keeps dialing forever: `ws.retryTimes` is a fast-retry budget, not a give-up count.\n * Resume is not implemented — the platform would replay the offline window only for a client that keeps its session,\n * and the upstream adapter never did — so a dropped connection loses the events it missed and the bot says so in its\n * logs.\n *\n * The `sn` heartbeat confirmation is the platform's ACK: the `sn` a PING carries is the last message `bot.receive`\n * accepted, so a receive that fails leaves the event unconfirmed and the platform retransmits it on the next heartbeat.\n */\nimport { Status } from '@deepseek-ai/cordis-plugin-im-core';\nimport { decodeEvent } from \"./decode.js\";\nimport { isPermanentHelloCode, isResumeCode } from \"./errors.js\";\nimport { invoke } from \"./request.js\";\nimport { Signal } from \"./types.js\";\n/** The platform requires HELLO within 6 s of the connection opening. */\nconst HELLO_TIMEOUT = 6_000;\n/** The platform requires PONG within 6 s of a PING. */\nconst PONG_TIMEOUT = 6_000;\n/** Heartbeat interval, 30 s plus a random ±5 s as the platform asks. */\nconst HEARTBEAT_BASE = 30_000;\nconst HEARTBEAT_JITTER = 5_000;\n/** Waitable sleep that resolves early on abort. */\nfunction sleep(ms, signal) {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n/** Text of one WebSocket frame. */\nfunction frameText(data) {\n return typeof data === 'string' ? data : String(data);\n}\n/** One JSON field of one frame, when it is an object. */\nfunction recordOf(value) {\n return typeof value === 'object' && value !== null\n ? value\n : undefined;\n}\n/** One number field of one frame. */\nfunction numberOf(value) {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n/** The platform refused the connection for a reason only a corrected configuration can fix. */\nclass KookGatewayFatalError extends Error {\n constructor(message) {\n super(message);\n this.name = 'KookGatewayFatalError';\n }\n}\n/**\n * The Gateway client of one bot.\n *\n * `start()` returns after starting the reconnect loop, never after the first HELLO: `Bot.start` awaits `connect()`,\n * and holding plugin initialization open until KOOK is reachable would block the whole profile.\n */\nexport class KookWsTransport {\n bot;\n controller;\n running;\n socket;\n heartbeatTimer;\n pongTimer;\n constructor(bot) {\n this.bot = bot;\n }\n /** Start the reconnect loop. */\n async start() {\n this.controller = new AbortController();\n this.running = this.loop(this.controller.signal);\n }\n /** Stop the loop and wait for it to unwind. */\n async stop() {\n this.controller?.abort();\n this.controller = undefined;\n this.closeSocket();\n await this.running?.catch(() => undefined);\n this.running = undefined;\n }\n /** Delay before the next dial: the fast interval while the failure budget lasts, the lazy one after it. */\n intervalOf(failures) {\n const { ws } = this.bot.config;\n return failures < ws.retryTimes ? ws.retryInterval : ws.retryLazy;\n }\n async loop(signal) {\n let failures = 0;\n while (!signal.aborted) {\n try {\n const socket = await this.open(signal);\n const greeted = await this.accept(socket, signal);\n if (signal.aborted)\n return;\n // A connection that greeted once proves the token works, so the next dial goes out at the fast interval.\n failures = greeted ? 0 : failures + 1;\n this.bot.ctx.logger.warn('kook: the gateway connection closed; reconnecting');\n this.bot.status = Status.RECONNECT;\n await sleep(this.intervalOf(failures), signal);\n }\n catch (error) {\n if (signal.aborted)\n return;\n if (error instanceof KookGatewayFatalError) {\n // A rejected token cannot be fixed by reconnecting: report it and stop until the profile is edited.\n this.bot.ctx.logger.error(error.message);\n this.bot.offline(error);\n return;\n }\n failures += 1;\n this.bot.ctx.logger.warn('kook: %s; reconnecting', messageOf(error));\n this.bot.status = Status.RECONNECT;\n await sleep(this.intervalOf(failures), signal);\n }\n }\n }\n /** Fetch a fresh gateway URL and dial it, resolving once the socket opens. */\n async open(signal) {\n const gateway = await invoke(this.bot.request, 'GET', '/gateway/index', { compress: 0 }, signal);\n const url = gateway?.url;\n if (url === undefined || url === '') {\n throw new Error('kook: /gateway/index answered without a url');\n }\n return await this.dial(url, signal);\n }\n /** Dial one gateway URL and resolve once the socket is open. */\n dial(url, signal) {\n const socket = this.bot.ctx.http.ws(url, {\n headers: { authorization: `Bot ${this.bot.config.token}` },\n });\n return new Promise((resolve, reject) => {\n const cleanup = () => {\n socket.removeEventListener('open', onOpen);\n socket.removeEventListener('error', onError);\n socket.removeEventListener('close', onClose);\n signal.removeEventListener('abort', onAbort);\n };\n const onOpen = () => {\n cleanup();\n resolve(socket);\n };\n const onError = (event) => {\n cleanup();\n reject(new Error(`kook: WebSocket error${event.message === undefined ? '' : `: ${event.message}`}`));\n };\n const onClose = (event) => {\n cleanup();\n reject(new Error(`kook: WebSocket closed before opening (code ${event.code})`));\n };\n const onAbort = () => {\n cleanup();\n reject(signal.reason ?? new Error('kook: adapter stopped'));\n };\n if (signal.aborted) {\n onAbort();\n return;\n }\n socket.addEventListener('open', onOpen);\n socket.addEventListener('error', onError);\n socket.addEventListener('close', onClose);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n /**\n * Serve one open connection until it closes.\n * @param socket - the open socket.\n * @param signal - cancellation of the loop.\n * @returns whether HELLO arrived, i.e. whether the connection ever worked.\n */\n async accept(socket, signal) {\n this.socket = socket;\n let greeted = false;\n let sn = 0;\n // Events are received one at a time so `sn` only advances past a message whose `bot.receive` resolved.\n let queue = Promise.resolve();\n // HELLO settles through one of: the frame, the connection closing, the deadline, or the loop stopping.\n let helloCode;\n let helloDone = false;\n let settleHello;\n const hello = new Promise((resolve) => {\n settleHello = resolve;\n });\n const settle = (code) => {\n if (helloDone)\n return;\n helloDone = true;\n helloCode = code;\n settleHello?.();\n };\n const closed = new Promise((resolve) => {\n socket.addEventListener('close', () => {\n settle(undefined);\n resolve();\n });\n });\n socket.addEventListener('message', (event) => {\n let parsed;\n try {\n parsed = JSON.parse(frameText(event.data));\n }\n catch (error) {\n this.bot.ctx.logger.warn('kook: cannot parse a gateway frame: %s', messageOf(error));\n return;\n }\n switch (parsed.s) {\n case Signal.event: {\n queue = queue.then(async () => {\n try {\n const session = decodeEvent(this.bot, parsed.d);\n if (session !== undefined)\n await this.bot.receive(session);\n const frameSn = numberOf(parsed.sn);\n if (frameSn !== undefined)\n sn = Math.max(sn, frameSn);\n }\n catch (error) {\n // The heartbeat's `sn` still points at the previous message, so the platform retransmits this one.\n this.bot.ctx.logger.error('kook: intake failed: %s', messageOf(error));\n }\n });\n break;\n }\n case Signal.hello: {\n settle(numberOf(recordOf(parsed.d)?.code) ?? 0);\n break;\n }\n case Signal.pong: {\n this.clearPong();\n break;\n }\n case Signal.resume: {\n // The migrated enum names s=5 `resume`; the platform sends s=5 to demand a reconnect (and s=4 is only ever\n // sent by a client that resumes, which this adapter does not).\n const code = numberOf(recordOf(parsed.d)?.code);\n this.bot.ctx.logger.info('kook: the platform asked for a reconnect%s', code === undefined ? '' : ` (code ${code})`);\n if (isResumeCode(code)) {\n this.bot.ctx.logger.warn('kook: the platform refused the session (%s); resume is not implemented, so the offline window is lost', code);\n }\n this.closeSocket();\n break;\n }\n default:\n this.bot.ctx.logger.debug('kook: ignored a gateway frame with s=%s', String(parsed.s));\n }\n });\n const deadline = setTimeout(() => {\n settle(Number.NaN);\n }, HELLO_TIMEOUT);\n const onAbort = () => {\n settle(Number.NaN);\n this.closeSocket();\n };\n signal.addEventListener('abort', onAbort, { once: true });\n try {\n await hello;\n clearTimeout(deadline);\n if (signal.aborted)\n return false;\n if (helloCode === undefined) {\n // The connection closed before HELLO: a transport failure, not a configuration one.\n throw new Error('kook: the gateway connection closed before HELLO');\n }\n if (Number.isNaN(helloCode)) {\n this.closeSocket();\n throw new Error(`kook: HELLO did not arrive within ${HELLO_TIMEOUT / 1_000} s`);\n }\n if (helloCode !== 0) {\n this.closeSocket();\n // Only 40100–40103 are configuration refusals; an undocumented code is retried like any other transport failure.\n if (isPermanentHelloCode(helloCode)) {\n throw new KookGatewayFatalError(`kook: the gateway refused the connection (code ${helloCode}); fix token/selfId and restart`);\n }\n throw new Error(`kook: the gateway HELLO failed with code ${helloCode}`);\n }\n greeted = true;\n this.bot.online();\n this.scheduleHeartbeat(socket, () => sn, signal);\n await closed;\n // Let the receives already queued finish before a new connection starts dispatching.\n await queue;\n return greeted;\n }\n finally {\n clearTimeout(deadline);\n signal.removeEventListener('abort', onAbort);\n this.stopHeartbeat();\n if (this.socket === socket)\n this.socket = undefined;\n }\n }\n /** One heartbeat at 30 s ± 5 s, then another; a missing PONG within 6 s closes the socket for the reconnect loop. */\n scheduleHeartbeat(socket, sn, signal) {\n this.stopHeartbeat();\n this.queueHeartbeat(socket, sn, signal);\n }\n /** Arm the next heartbeat without dropping the PONG deadline of the one already sent. */\n queueHeartbeat(socket, sn, signal) {\n const delay = HEARTBEAT_BASE + Math.round((Math.random() * 2 - 1) * HEARTBEAT_JITTER);\n this.heartbeatTimer = setTimeout(() => {\n if (signal.aborted || this.socket !== socket)\n return;\n try {\n socket.send(JSON.stringify({ s: Signal.ping, sn: sn() }));\n }\n catch (error) {\n this.bot.ctx.logger.warn('kook: could not send a heartbeat: %s', messageOf(error));\n this.closeSocket();\n return;\n }\n this.pongTimer = setTimeout(() => {\n if (this.socket !== socket)\n return;\n this.bot.ctx.logger.warn('kook: the gateway did not answer the heartbeat within %s s; reconnecting', PONG_TIMEOUT / 1_000);\n this.closeSocket();\n }, PONG_TIMEOUT);\n this.queueHeartbeat(socket, sn, signal);\n }, delay);\n }\n clearPong() {\n if (this.pongTimer !== undefined)\n clearTimeout(this.pongTimer);\n this.pongTimer = undefined;\n }\n stopHeartbeat() {\n if (this.heartbeatTimer !== undefined)\n clearTimeout(this.heartbeatTimer);\n this.heartbeatTimer = undefined;\n this.clearPong();\n }\n closeSocket() {\n const socket = this.socket;\n this.socket = undefined;\n this.stopHeartbeat();\n try {\n socket?.close(1000, 'adapter stopped');\n }\n catch (error) {\n // The socket is already closed or closing; nothing left to release.\n error;\n }\n }\n}\n/** Message of any caught value, for a log line. */\nfunction messageOf(error) {\n return error instanceof Error ? error.message : String(error);\n}\n//# sourceMappingURL=ws.js.map","import { Adapter, PlatformError } from '@deepseek-ai/cordis-plugin-im-core';\nimport { Config, configError } from \"./config.js\";\nimport { classifyKookError } from \"./errors.js\";\nimport { verifyIdentity } from \"./identity.js\";\nimport { createKmarkdownMode } from \"./modes/kmarkdown.js\";\nimport { createKookRequest, invoke } from \"./request.js\";\nimport { deletePart, getMessage, members, sendPayload } from \"./send.js\";\nimport { Internal } from \"./types.js\";\nimport { KookWebhook } from \"./webhook.js\";\nimport { KookWsTransport } from \"./ws.js\";\n/** MIME type by file extension for the multipart part name of an upload. */\nconst EXTENSIONS = {\n 'image/png': '.png',\n 'image/jpeg': '.jpg',\n 'image/gif': '.gif',\n 'image/webp': '.webp',\n 'video/mp4': '.mp4',\n 'video/quicktime': '.mov',\n 'audio/mpeg': '.mp3',\n 'audio/ogg': '.ogg',\n 'audio/wav': '.wav',\n 'application/pdf': '.pdf',\n 'text/plain': '.txt',\n};\n/** Message of any caught value, for a log line. */\nfunction messageOf(error) {\n return error instanceof Error ? error.message : String(error);\n}\n/** The file extension a MIME type names, when it has one worth adding to the upload name. */\nfunction extensionOf(mime) {\n return mime === undefined ? '' : (EXTENSIONS[mime] ?? '');\n}\n/**\n * KOOK adapter.\n *\n * Identity is the configured `selfId`, checked against `/user/me` on connect; the Gateway WebSocket and the Webhook are\n * the two transports; `kmarkdown` is the only mode, because a KOOK message is either KMarkdown text or a card and the\n * mode chooses between them per message. Outbound media goes through `/asset/create` because card images must be\n * uploaded by this bot.\n */\nexport class KookBot extends Adapter {\n /** The adapter needs the Satori service and the isolated `http` service. */\n static inject = ['satori', 'http'];\n /** The Loader applies this schema to a profile row's `config` before the constructor runs. */\n static Config = Config;\n modes = { kmarkdown: createKmarkdownMode() };\n modeOrder = ['kmarkdown'];\n /** Endpoints shared by every API call of this bot. */\n request;\n /** Full typed KOOK API surface registered by the migrated declarations. */\n internal;\n transport;\n constructor(ctx, config) {\n // A profile the selected protocol cannot work from fails at load, not at the first dial or callback.\n const invalid = configError(config);\n if (invalid !== undefined)\n throw invalid;\n super(ctx, config, {\n id: `kook:${config.selfId}`,\n platform: 'kook',\n adapter: 'kook',\n });\n this.selfId = config.selfId;\n this.request = createKookRequest(ctx, config.apiBaseUrl, config.token);\n this.internal = new Internal(this.request);\n }\n async connect() {\n try {\n const user = await verifyIdentity(this.request, this.config.selfId);\n this.user = {\n id: this.selfId,\n name: user.username === undefined || user.username === ''\n ? this.selfId\n : user.username,\n ...(user.avatar === undefined || user.avatar === ''\n ? {}\n : { avatar: user.avatar }),\n isBot: true,\n };\n }\n catch (error) {\n // `Bot.start` only stores a connect failure on `bot.error`, so log it here.\n this.ctx.logger.error('kook: connect failed: %s', messageOf(error));\n throw error;\n }\n this.transport =\n this.config.protocol === 'http'\n ? new KookWebhook(this)\n : new KookWsTransport(this);\n await this.transport.start();\n }\n async disconnect() {\n const transport = this.transport;\n this.transport = undefined;\n await transport?.stop();\n }\n /**\n * Upload one outbound attachment to `/asset/create`.\n *\n * The platform requires card images to be uploaded by the bot itself (\"图片必须由你的机器人上传\"), so every media\n * element is uploaded and the returned URL is what the card carries; an external link is never used.\n */\n async upload(ref, _scope, ctx) {\n const fetched = await ctx.fetch(ref.src, ctx.signal);\n const mime = ref.meta.mime ?? fetched.mime ?? 'application/octet-stream';\n const name = ref.meta.name ?? fetched.name ?? `kook-${ref.kind}${extensionOf(mime)}`;\n const form = new FormData();\n form.append('file', new Blob([fetched.data], { type: mime }), name);\n const asset = await invoke(this.request, 'POST', '/asset/create', form);\n const url = asset?.url;\n if (url === undefined || url === '') {\n throw new PlatformError('invalid', 'kook: /asset/create answered without a url', { published: 'no' });\n }\n return { key: url };\n }\n resourceScope(_target, _kind) {\n // An uploaded asset belongs to the bot; the same URL is valid in every channel it posts to.\n return this.id;\n }\n async sendPayload(payload, target, ctx) {\n return await sendPayload(this.request, payload, target, ctx);\n }\n async deletePart(part, handle) {\n await deletePart(this.request, part, handle);\n }\n async members(chat, cursor, limit) {\n return await members(this.request, chat, cursor, limit);\n }\n async getMessage(chat, id) {\n return await getMessage(this.request, this, chat, id);\n }\n classify(error) {\n return classifyKookError(error);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QAAQ,QAAQ,QAAQ,IAAI,OAAO,YAAY,IAAI;EACjF,MAAM,OAAO,IAAI,SAAS;EAC1B,KAAK,OAAO,QAAQ,IAAI,KAAK,CAAC,QAAQ,IAAI,GAAG,EAAE,MAAM,KAAK,CAAC,GAAG,IAAI;EAElE,MAAM,OAAM,MADQ,OAAO,KAAK,SAAS,QAAQ,iBAAiB,IAAI,EAAA,EACnD;EACnB,IAAI,QAAQ,KAAA,KAAa,QAAQ,IAC7B,MAAM,IAAI,cAAc,WAAW,8CAA8C,EAAE,WAAW,KAAK,CAAC;EAExG,OAAO,EAAE,KAAK,IAAI;CACtB;CACA,cAAc,SAAS,OAAO;EAE1B,OAAO,KAAK;CAChB;CACA,MAAM,YAAY,SAAS,QAAQ,KAAK;EACpC,OAAO,MAAM,YAAY,KAAK,SAAS,SAAS,QAAQ,GAAG;CAC/D;CACA,MAAM,WAAW,MAAM,QAAQ;EAC3B,MAAM,WAAW,KAAK,SAAS,MAAM,MAAM;CAC/C;CACA,MAAM,QAAQ,MAAM,QAAQ,OAAO;EAC/B,OAAO,MAAM,QAAQ,KAAK,SAAS,MAAM,QAAQ,KAAK;CAC1D;CACA,MAAM,WAAW,MAAM,IAAI;EACvB,OAAO,MAAM,WAAW,KAAK,SAAS,MAAM,MAAM,EAAE;CACxD;CACA,SAAS,OAAO;EACZ,OAAO,kBAAkB,KAAK;CAClC;AACJ"}
@@ -0,0 +1,53 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { Adapter, PlatformError } from '@deepseek-ai/cordis-plugin-im-core';
3
+ import type { ChatRef, InboundMessage, MembersPage, Mode, PrepareContext, ResolvedResource, ResourceKind, ResourceRef, SendContext, SentPart, Target } from '@deepseek-ai/cordis-plugin-im-core';
4
+ import { Config } from './config.ts';
5
+ import type { KookModeTypes } from './modes/shared.ts';
6
+ import type { KookRequest } from './request.ts';
7
+ import { deletePart } from './send.ts';
8
+ import { Internal } from './types.ts';
9
+ /** The single mode this adapter always registers. */
10
+ export interface KookModes {
11
+ [mode: string]: Mode<KookModeTypes>;
12
+ kmarkdown: Mode<KookModeTypes>;
13
+ }
14
+ /**
15
+ * KOOK adapter.
16
+ *
17
+ * Identity is the configured `selfId`, checked against `/user/me` on connect; the Gateway WebSocket and the Webhook are
18
+ * the two transports; `kmarkdown` is the only mode, because a KOOK message is either KMarkdown text or a card and the
19
+ * mode chooses between them per message. Outbound media goes through `/asset/create` because card images must be
20
+ * uploaded by this bot.
21
+ */
22
+ export declare class KookBot extends Adapter<Config, KookModes> {
23
+ /** The adapter needs the Satori service and the isolated `http` service. */
24
+ static inject: string[];
25
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
26
+ static readonly Config: import("@deepseek-ai/schemastery").default<Config>;
27
+ readonly modes: KookModes;
28
+ readonly modeOrder: readonly ["kmarkdown"];
29
+ /** Endpoints shared by every API call of this bot. */
30
+ readonly request: KookRequest;
31
+ /** Full typed KOOK API surface registered by the migrated declarations. */
32
+ readonly internal: Internal;
33
+ private transport;
34
+ constructor(ctx: Context, config: Config);
35
+ connect(): Promise<void>;
36
+ disconnect(): Promise<void>;
37
+ /**
38
+ * Upload one outbound attachment to `/asset/create`.
39
+ *
40
+ * The platform requires card images to be uploaded by the bot itself ("图片必须由你的机器人上传"), so every media
41
+ * element is uploaded and the returned URL is what the card carries; an external link is never used.
42
+ */
43
+ upload(ref: ResourceRef, _scope: string, ctx: PrepareContext): Promise<ResolvedResource>;
44
+ resourceScope(_target: Target, _kind: ResourceKind): string;
45
+ sendPayload(payload: unknown, target: Target, ctx: SendContext): Promise<SentPart>;
46
+ deletePart(part: SentPart, handle: Parameters<typeof deletePart>[2]): Promise<void>;
47
+ members(chat: ChatRef, cursor?: string, limit?: number): Promise<MembersPage>;
48
+ getMessage(chat: ChatRef, id: string): Promise<InboundMessage>;
49
+ classify(error: unknown): PlatformError;
50
+ }
51
+ export { Config };
52
+ export default KookBot;
53
+ //# sourceMappingURL=bot.d.ts.map
@@ -0,0 +1 @@
1
+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AAE,MAAM;IAczB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA0BxB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAM1C;;;;;OAKG;IACY,MAAM,CACnB,GAAG,EAAE,WAAW,EAChB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,cAAc,GAClB,OAAO,CAAC,gBAAgB,CAAC;IAwBnB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,MAAM;IAKrD,WAAW,CACxB,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,WAAW,GACf,OAAO,CAAC,QAAQ,CAAC;IASL,UAAU,CACvB,IAAI,EAAE,QAAQ,EACd,MAAM,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,GACvC,OAAO,CAAC,IAAI,CAAC;IAID,OAAO,CACpB,IAAI,EAAE,OAAO,EACb,MAAM,CAAC,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,WAAW,CAAC;IAIR,UAAU,CACvB,IAAI,EAAE,OAAO,EACb,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,CAAC;IAIjB,QAAQ,CAAC,KAAK,EAAE,OAAO;CAGjC;AAED,OAAO,EAAE,MAAM,EAAE,CAAA;AAEjB,eAAe,OAAO,CAAA"}
@@ -0,0 +1,138 @@
1
+ import { Adapter, PlatformError } from '@deepseek-ai/cordis-plugin-im-core';
2
+ import { Config, configError } from "./config.js";
3
+ import { classifyKookError } from "./errors.js";
4
+ import { verifyIdentity } from "./identity.js";
5
+ import { createKmarkdownMode } from "./modes/kmarkdown.js";
6
+ import { createKookRequest, invoke } from "./request.js";
7
+ import { deletePart, getMessage, members, sendPayload } from "./send.js";
8
+ import { Internal } from "./types.js";
9
+ import { KookWebhook } from "./webhook.js";
10
+ import { KookWsTransport } from "./ws.js";
11
+ /** MIME type by file extension for the multipart part name of an upload. */
12
+ const EXTENSIONS = {
13
+ 'image/png': '.png',
14
+ 'image/jpeg': '.jpg',
15
+ 'image/gif': '.gif',
16
+ 'image/webp': '.webp',
17
+ 'video/mp4': '.mp4',
18
+ 'video/quicktime': '.mov',
19
+ 'audio/mpeg': '.mp3',
20
+ 'audio/ogg': '.ogg',
21
+ 'audio/wav': '.wav',
22
+ 'application/pdf': '.pdf',
23
+ 'text/plain': '.txt',
24
+ };
25
+ /** Message of any caught value, for a log line. */
26
+ function messageOf(error) {
27
+ return error instanceof Error ? error.message : String(error);
28
+ }
29
+ /** The file extension a MIME type names, when it has one worth adding to the upload name. */
30
+ function extensionOf(mime) {
31
+ return mime === undefined ? '' : (EXTENSIONS[mime] ?? '');
32
+ }
33
+ /**
34
+ * KOOK adapter.
35
+ *
36
+ * Identity is the configured `selfId`, checked against `/user/me` on connect; the Gateway WebSocket and the Webhook are
37
+ * the two transports; `kmarkdown` is the only mode, because a KOOK message is either KMarkdown text or a card and the
38
+ * mode chooses between them per message. Outbound media goes through `/asset/create` because card images must be
39
+ * uploaded by this bot.
40
+ */
41
+ export class KookBot extends Adapter {
42
+ /** The adapter needs the Satori service and the isolated `http` service. */
43
+ static inject = ['satori', 'http'];
44
+ /** The Loader applies this schema to a profile row's `config` before the constructor runs. */
45
+ static Config = Config;
46
+ modes = { kmarkdown: createKmarkdownMode() };
47
+ modeOrder = ['kmarkdown'];
48
+ /** Endpoints shared by every API call of this bot. */
49
+ request;
50
+ /** Full typed KOOK API surface registered by the migrated declarations. */
51
+ internal;
52
+ transport;
53
+ constructor(ctx, config) {
54
+ // A profile the selected protocol cannot work from fails at load, not at the first dial or callback.
55
+ const invalid = configError(config);
56
+ if (invalid !== undefined)
57
+ throw invalid;
58
+ super(ctx, config, {
59
+ id: `kook:${config.selfId}`,
60
+ platform: 'kook',
61
+ adapter: 'kook',
62
+ });
63
+ this.selfId = config.selfId;
64
+ this.request = createKookRequest(ctx, config.apiBaseUrl, config.token);
65
+ this.internal = new Internal(this.request);
66
+ }
67
+ async connect() {
68
+ try {
69
+ const user = await verifyIdentity(this.request, this.config.selfId);
70
+ this.user = {
71
+ id: this.selfId,
72
+ name: user.username === undefined || user.username === ''
73
+ ? this.selfId
74
+ : user.username,
75
+ ...(user.avatar === undefined || user.avatar === ''
76
+ ? {}
77
+ : { avatar: user.avatar }),
78
+ isBot: true,
79
+ };
80
+ }
81
+ catch (error) {
82
+ // `Bot.start` only stores a connect failure on `bot.error`, so log it here.
83
+ this.ctx.logger.error('kook: connect failed: %s', messageOf(error));
84
+ throw error;
85
+ }
86
+ this.transport =
87
+ this.config.protocol === 'http'
88
+ ? new KookWebhook(this)
89
+ : new KookWsTransport(this);
90
+ await this.transport.start();
91
+ }
92
+ async disconnect() {
93
+ const transport = this.transport;
94
+ this.transport = undefined;
95
+ await transport?.stop();
96
+ }
97
+ /**
98
+ * Upload one outbound attachment to `/asset/create`.
99
+ *
100
+ * The platform requires card images to be uploaded by the bot itself ("图片必须由你的机器人上传"), so every media
101
+ * element is uploaded and the returned URL is what the card carries; an external link is never used.
102
+ */
103
+ async upload(ref, _scope, ctx) {
104
+ const fetched = await ctx.fetch(ref.src, ctx.signal);
105
+ const mime = ref.meta.mime ?? fetched.mime ?? 'application/octet-stream';
106
+ const name = ref.meta.name ?? fetched.name ?? `kook-${ref.kind}${extensionOf(mime)}`;
107
+ const form = new FormData();
108
+ form.append('file', new Blob([fetched.data], { type: mime }), name);
109
+ const asset = await invoke(this.request, 'POST', '/asset/create', form);
110
+ const url = asset?.url;
111
+ if (url === undefined || url === '') {
112
+ throw new PlatformError('invalid', 'kook: /asset/create answered without a url', { published: 'no' });
113
+ }
114
+ return { key: url };
115
+ }
116
+ resourceScope(_target, _kind) {
117
+ // An uploaded asset belongs to the bot; the same URL is valid in every channel it posts to.
118
+ return this.id;
119
+ }
120
+ async sendPayload(payload, target, ctx) {
121
+ return await sendPayload(this.request, payload, target, ctx);
122
+ }
123
+ async deletePart(part, handle) {
124
+ await deletePart(this.request, part, handle);
125
+ }
126
+ async members(chat, cursor, limit) {
127
+ return await members(this.request, chat, cursor, limit);
128
+ }
129
+ async getMessage(chat, id) {
130
+ return await getMessage(this.request, this, chat, id);
131
+ }
132
+ classify(error) {
133
+ return classifyKookError(error);
134
+ }
135
+ }
136
+ export { Config };
137
+ export default KookBot;
138
+ //# sourceMappingURL=bot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../src/bot.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAA;AAc3E,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAA;AAE1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAExD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAErC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAczC,4EAA4E;AAC5E,MAAM,UAAU,GAA2B;IACzC,WAAW,EAAE,MAAM;IACnB,YAAY,EAAE,MAAM;IACpB,WAAW,EAAE,MAAM;IACnB,YAAY,EAAE,OAAO;IACrB,WAAW,EAAE,MAAM;IACnB,iBAAiB,EAAE,MAAM;IACzB,YAAY,EAAE,MAAM;IACpB,WAAW,EAAE,MAAM;IACnB,WAAW,EAAE,MAAM;IACnB,iBAAiB,EAAE,MAAM;IACzB,YAAY,EAAE,MAAM;CACrB,CAAA;AAED,mDAAmD;AACnD,SAAS,SAAS,CAAC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