@effect-ak/tg-bot-api 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,6 +3,10 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
6
10
  var __copyProps = (to, from, except, desc) => {
7
11
  if (from && typeof from === "object" || typeof from === "function") {
8
12
  for (let key of __getOwnPropNames(from))
@@ -15,4 +19,28 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
15
19
 
16
20
  // src/index.ts
17
21
  var index_exports = {};
22
+ __export(index_exports, {
23
+ verifyLoginData: () => verifyLoginData
24
+ });
18
25
  module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/login-widget.ts
28
+ var toHex = (buffer) => Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
29
+ var verifyLoginData = async (input) => {
30
+ const dataCheckString = Object.entries(input.data).filter(([key]) => key !== "hash").sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("\n");
31
+ const encoder = new TextEncoder();
32
+ const secretKey = await crypto.subtle.digest("SHA-256", encoder.encode(input.botToken));
33
+ const signingKey = await crypto.subtle.importKey(
34
+ "raw",
35
+ secretKey,
36
+ { name: "HMAC", hash: "SHA-256" },
37
+ false,
38
+ ["sign"]
39
+ );
40
+ const signature = await crypto.subtle.sign("HMAC", signingKey, encoder.encode(dataCheckString));
41
+ return toHex(signature) === input.data.hash;
42
+ };
43
+ // Annotate the CommonJS export names for ESM import in node:
44
+ 0 && (module.exports = {
45
+ verifyLoginData
46
+ });
package/dist/index.d.ts CHANGED
@@ -389,6 +389,109 @@ interface EventHandlers {
389
389
  }) => void;
390
390
  }
391
391
 
392
+ /**
393
+ * User data returned by Telegram Login Widget after successful authentication.
394
+ *
395
+ * @see https://core.telegram.org/widgets/login#receiving-authorization-data
396
+ */
397
+ interface TelegramLoginData {
398
+ /** Unique Telegram user identifier */
399
+ id: number;
400
+ /** User's first name */
401
+ first_name: string;
402
+ /** User's last name (optional) */
403
+ last_name?: string;
404
+ /** Telegram username (optional) */
405
+ username?: string;
406
+ /** URL of the user's profile photo (optional) */
407
+ photo_url?: string;
408
+ /** Unix timestamp of the authentication */
409
+ auth_date: number;
410
+ /** HMAC-SHA-256 signature for data verification */
411
+ hash: string;
412
+ }
413
+ /**
414
+ * Options for `Telegram.Login.auth` and `Telegram.Login.init`.
415
+ */
416
+ interface TelegramLoginOptions {
417
+ /** Numeric bot ID (not the username) */
418
+ bot_id: number;
419
+ /** Request permission to send messages to the user from your bot */
420
+ request_access?: boolean;
421
+ /** Language code for the login popup (e.g. "en", "ru") */
422
+ lang?: string;
423
+ }
424
+ /**
425
+ * Programmatic API exposed by `telegram-widget.js` at `window.Telegram.Login`.
426
+ *
427
+ * Load the script to make this available:
428
+ * ```html
429
+ * <script src="https://telegram.org/js/telegram-widget.js?22"></script>
430
+ * ```
431
+ *
432
+ * @see https://core.telegram.org/widgets/login
433
+ */
434
+ interface TelegramLoginService {
435
+ /** OAuth origin URL (`https://oauth.telegram.org`) */
436
+ widgetsOrigin: string;
437
+ /**
438
+ * Store options and register the auth callback.
439
+ * If auth data is already present in the URL hash, the callback fires immediately.
440
+ */
441
+ init: (options: TelegramLoginOptions, callback: (data: TelegramLoginData | false) => void) => void;
442
+ /**
443
+ * Open the login popup using options previously set by {@link init}.
444
+ */
445
+ open: (callback?: (data: TelegramLoginData | false) => void) => void;
446
+ /**
447
+ * Full auth flow — opens a popup for Telegram OAuth.
448
+ * Self-contained, does not require a prior {@link init} call.
449
+ */
450
+ auth: (options: TelegramLoginOptions, callback: (data: TelegramLoginData | false) => void) => void;
451
+ /**
452
+ * Retrieve previously stored auth data from the server via POST request.
453
+ *
454
+ * @param options - `bot_id` is passed as a string here (server-side lookup key)
455
+ * @param callback - receives the widget origin and auth data (or `false`)
456
+ */
457
+ getAuthData: (options: {
458
+ bot_id: string;
459
+ lang?: string;
460
+ }, callback: (origin: string, data: TelegramLoginData | false) => void) => void;
461
+ }
462
+ declare global {
463
+ interface Window {
464
+ Telegram: {
465
+ /** Telegram Login Widget API */
466
+ Login: TelegramLoginService;
467
+ /** Query an embedded iframe widget for its metadata */
468
+ getWidgetInfo: (el: string | HTMLElement, callback: (info: Record<string, unknown>) => void) => void;
469
+ /** Send runtime configuration to widget iframe(s) */
470
+ setWidgetOptions: (options: Record<string, unknown>, el?: string | HTMLElement) => void;
471
+ };
472
+ }
473
+ }
474
+ /**
475
+ * Verify the authenticity of data received from Telegram Login Widget.
476
+ *
477
+ * Uses the algorithm described in the
478
+ * {@link https://core.telegram.org/widgets/login#checking-authorization | official docs}:
479
+ * 1. Build `data_check_string` from all fields except `hash`, sorted alphabetically
480
+ * 2. `secret_key = SHA-256(bot_token)`
481
+ * 3. Compare `HMAC-SHA-256(secret_key, data_check_string)` with `hash`
482
+ *
483
+ * Uses Web Crypto API — works in Node.js, Deno, Bun, and edge runtimes.
484
+ *
485
+ * @param input - Auth data and bot token
486
+ * @param input.data - Auth data received from the widget callback
487
+ * @param input.botToken - Your bot's token from \@BotFather
488
+ * @returns `true` if the data is authentic
489
+ */
490
+ declare const verifyLoginData: (input: {
491
+ data: TelegramLoginData;
492
+ botToken: string;
493
+ }) => Promise<boolean>;
494
+
392
495
  type AllowedUpdateName = Exclude<keyof Update, "update_id">;
393
496
  interface AcceptedGiftTypes {
394
497
  unlimited_gifts: boolean;
@@ -3730,4 +3833,4 @@ interface VerifyUserInput {
3730
3833
  custom_description?: string;
3731
3834
  }
3732
3835
 
3733
- export type { Accelerometer, AccelerometerStartParams, AcceptedGiftTypes, AddStickerToSetInput, AffiliateInfo, AllowedUpdateName, Animation, AnswerCallbackQueryInput, AnswerInlineQueryInput, AnswerPreCheckoutQueryInput, AnswerShippingQueryInput, AnswerWebAppQueryInput, Api, ApproveChatJoinRequestInput, ApproveSuggestedPostInput, Audio, BackButton, BackgroundFill, BackgroundFillFreeformGradient, BackgroundFillGradient, BackgroundFillSolid, BackgroundType, BackgroundTypeChatTheme, BackgroundTypeFill, BackgroundTypePattern, BackgroundTypeWallpaper, BanChatMemberInput, BanChatSenderChatInput, BindOrUnbindEventHandler, BiometricAuthenticateParams, BiometricManager, BiometricRequestAccessParams, Birthdate, BotCommand, BotCommandScope, BotCommandScopeAllChatAdministrators, BotCommandScopeAllGroupChats, BotCommandScopeAllPrivateChats, BotCommandScopeChat, BotCommandScopeChatAdministrators, BotCommandScopeChatMember, BotCommandScopeDefault, BotDescription, BotName, BotShortDescription, BottomButton, BusinessBotRights, BusinessConnection, BusinessIntro, BusinessLocation, BusinessMessagesDeleted, BusinessOpeningHours, BusinessOpeningHoursInterval, CallbackGame, CallbackQuery, Chat, ChatAdministratorRights, ChatBackground, ChatBoost, ChatBoostAdded, ChatBoostRemoved, ChatBoostSource, ChatBoostSourceGiftCode, ChatBoostSourceGiveaway, ChatBoostSourcePremium, ChatBoostUpdated, ChatFullInfo, ChatInviteLink, ChatJoinRequest, ChatLocation, ChatMember, ChatMemberAdministrator, ChatMemberBanned, ChatMemberLeft, ChatMemberMember, ChatMemberOwner, ChatMemberRestricted, ChatMemberUpdated, ChatOwnerChanged, ChatOwnerLeft, ChatPermissions, ChatPhoto, ChatShared, Checklist, ChecklistTask, ChecklistTasksAdded, ChecklistTasksDone, ChosenInlineResult, CloseForumTopicInput, CloseGeneralForumTopicInput, CloseInput, CloudStorage, Contact, ContentSafeAreaInset, ConvertGiftToStarsInput, CopyMessageInput, CopyMessagesInput, CopyTextButton, CreateChatInviteLinkInput, CreateChatSubscriptionInviteLinkInput, CreateForumTopicInput, CreateInvoiceLinkInput, CreateNewStickerSetInput, DeclineChatJoinRequestInput, DeclineSuggestedPostInput, DeleteBusinessMessagesInput, DeleteChatPhotoInput, DeleteChatStickerSetInput, DeleteForumTopicInput, DeleteMessageInput, DeleteMessagesInput, DeleteMyCommandsInput, DeleteStickerFromSetInput, DeleteStickerSetInput, DeleteStoryInput, DeleteWebhookInput, DeviceOrientation, DeviceOrientationStartParams, DeviceStorage, Dice, DirectMessagePriceChanged, DirectMessagesTopic, Document, DownloadFileParams, EditChatInviteLinkInput, EditChatSubscriptionInviteLinkInput, EditForumTopicInput, EditGeneralForumTopicInput, EditMessageCaptionInput, EditMessageChecklistInput, EditMessageLiveLocationInput, EditMessageMediaInput, EditMessageReplyMarkupInput, EditMessageTextInput, EditStoryInput, EditUserStarSubscriptionInput, EmojiStatusParams, EncryptedCredentials, EncryptedPassportElement, EventHandlers, ExportChatInviteLinkInput, ExternalReplyInfo, File, ForceReply, ForumTopic, ForumTopicClosed, ForumTopicCreated, ForumTopicEdited, ForumTopicReopened, ForwardMessageInput, ForwardMessagesInput, Game, GameHighScore, GeneralForumTopicHidden, GeneralForumTopicUnhidden, GetAvailableGiftsInput, GetBusinessAccountGiftsInput, GetBusinessAccountStarBalanceInput, GetBusinessConnectionInput, GetChatAdministratorsInput, GetChatGiftsInput, GetChatInput, GetChatMemberCountInput, GetChatMemberInput, GetChatMenuButtonInput, GetCustomEmojiStickersInput, GetFileInput, GetForumTopicIconStickersInput, GetGameHighScoresInput, GetMeInput, GetMyCommandsInput, GetMyDefaultAdministratorRightsInput, GetMyDescriptionInput, GetMyNameInput, GetMyShortDescriptionInput, GetMyStarBalanceInput, GetStarTransactionsInput, GetStickerSetInput, GetUpdatesInput, GetUserChatBoostsInput, GetUserGiftsInput, GetUserProfileAudiosInput, GetUserProfilePhotosInput, GetWebhookInfoInput, Gift, GiftBackground, GiftInfo, GiftPremiumSubscriptionInput, Gifts, Giveaway, GiveawayCompleted, GiveawayCreated, GiveawayWinners, Gyroscope, GyroscopeStartParams, HapticFeedback, HideGeneralForumTopicInput, InaccessibleMessage, InlineKeyboardButton, InlineKeyboardMarkup, InlineQuery, InlineQueryResult, InlineQueryResultArticle, InlineQueryResultAudio, InlineQueryResultCachedAudio, InlineQueryResultCachedDocument, InlineQueryResultCachedGif, InlineQueryResultCachedMpeg4Gif, InlineQueryResultCachedPhoto, InlineQueryResultCachedSticker, InlineQueryResultCachedVideo, InlineQueryResultCachedVoice, InlineQueryResultContact, InlineQueryResultDocument, InlineQueryResultGame, InlineQueryResultGif, InlineQueryResultLocation, InlineQueryResultMpeg4Gif, InlineQueryResultPhoto, InlineQueryResultVenue, InlineQueryResultVideo, InlineQueryResultVoice, InlineQueryResultsButton, InputChecklist, InputChecklistTask, InputContactMessageContent, InputFile, InputInvoiceMessageContent, InputLocationMessageContent, InputMedia, InputMediaAnimation, InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo, InputMessageContent, InputPaidMedia, InputPaidMediaPhoto, InputPaidMediaVideo, InputPollOption, InputProfilePhoto, InputProfilePhotoAnimated, InputProfilePhotoStatic, InputSticker, InputStoryContent, InputStoryContentPhoto, InputStoryContentVideo, InputTextMessageContent, InputVenueMessageContent, Invoice, KeyboardButton, KeyboardButtonPollType, KeyboardButtonRequestChat, KeyboardButtonRequestUsers, LabeledPrice, LeaveChatInput, LinkPreviewOptions, Location, LocationAddress, LocationData, LocationManager, LogOutInput, LoginUrl, MaskPosition, MaybeInaccessibleMessage, MenuButton, MenuButtonCommands, MenuButtonDefault, MenuButtonWebApp, Message, MessageAutoDeleteTimerChanged, MessageEntity, MessageId, MessageOrigin, MessageOriginChannel, MessageOriginChat, MessageOriginHiddenUser, MessageOriginUser, MessageReactionCountUpdated, MessageReactionUpdated, OrderInfo, OwnedGift, OwnedGiftRegular, OwnedGiftUnique, OwnedGifts, PaidMedia, PaidMediaInfo, PaidMediaPhoto, PaidMediaPreview, PaidMediaPurchased, PaidMediaVideo, PaidMessagePriceChanged, PassportData, PassportElementError, PassportElementErrorDataField, PassportElementErrorFile, PassportElementErrorFiles, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorTranslationFile, PassportElementErrorTranslationFiles, PassportElementErrorUnspecified, PassportFile, PhotoSize, PinChatMessageInput, Poll, PollAnswer, PollOption, PopupButton, PopupParams, PostStoryInput, PreCheckoutQuery, PreparedInlineMessage, PromoteChatMemberInput, ProximityAlertTriggered, ReactionCount, ReactionType, ReactionTypeCustomEmoji, ReactionTypeEmoji, ReactionTypePaid, ReadBusinessMessageInput, RefundStarPaymentInput, RefundedPayment, RemoveBusinessAccountProfilePhotoInput, RemoveChatVerificationInput, RemoveMyProfilePhotoInput, RemoveUserVerificationInput, ReopenForumTopicInput, ReopenGeneralForumTopicInput, ReplaceStickerInSetInput, ReplyKeyboardMarkup, ReplyKeyboardRemove, ReplyParameters, RepostStoryInput, ResponseParameters, RestrictChatMemberInput, RevenueWithdrawalState, RevenueWithdrawalStateFailed, RevenueWithdrawalStatePending, RevenueWithdrawalStateSucceeded, RevokeChatInviteLinkInput, SafeAreaInset, SavePreparedInlineMessageInput, ScanQrPopupParams, SecureStorage, SendAnimationInput, SendAudioInput, SendChatActionInput, SendChecklistInput, SendContactInput, SendDiceInput, SendDocumentInput, SendGameInput, SendGiftInput, SendInvoiceInput, SendLocationInput, SendMediaGroupInput, SendMessageDraftInput, SendMessageInput, SendPaidMediaInput, SendPhotoInput, SendPollInput, SendStickerInput, SendVenueInput, SendVideoInput, SendVideoNoteInput, SendVoiceInput, SentWebAppMessage, SetBusinessAccountBioInput, SetBusinessAccountGiftSettingsInput, SetBusinessAccountNameInput, SetBusinessAccountProfilePhotoInput, SetBusinessAccountUsernameInput, SetChatAdministratorCustomTitleInput, SetChatDescriptionInput, SetChatMenuButtonInput, SetChatPermissionsInput, SetChatPhotoInput, SetChatStickerSetInput, SetChatTitleInput, SetCustomEmojiStickerSetThumbnailInput, SetGameScoreInput, SetMessageReactionInput, SetMyCommandsInput, SetMyDefaultAdministratorRightsInput, SetMyDescriptionInput, SetMyNameInput, SetMyProfilePhotoInput, SetMyShortDescriptionInput, SetPassportDataErrorsInput, SetStickerEmojiListInput, SetStickerKeywordsInput, SetStickerMaskPositionInput, SetStickerPositionInSetInput, SetStickerSetThumbnailInput, SetStickerSetTitleInput, SetUserEmojiStatusInput, SetWebhookInput, SettingsButton, SharedUser, ShippingAddress, ShippingOption, ShippingQuery, StarAmount, StarTransaction, StarTransactions, Sticker, StickerSet, StopMessageLiveLocationInput, StopPollInput, Story, StoryArea, StoryAreaPosition, StoryAreaType, StoryAreaTypeLink, StoryAreaTypeLocation, StoryAreaTypeSuggestedReaction, StoryAreaTypeUniqueGift, StoryAreaTypeWeather, StoryShareParams, StoryWidgetLink, SuccessfulPayment, SuggestedPostApprovalFailed, SuggestedPostApproved, SuggestedPostDeclined, SuggestedPostInfo, SuggestedPostPaid, SuggestedPostParameters, SuggestedPostPrice, SuggestedPostRefunded, SwitchInlineQueryChosenChat, TextQuote, ThemeParams, TransactionPartner, TransactionPartnerAffiliateProgram, TransactionPartnerChat, TransactionPartnerFragment, TransactionPartnerOther, TransactionPartnerTelegramAds, TransactionPartnerTelegramApi, TransactionPartnerUser, TransferBusinessAccountStarsInput, TransferGiftInput, UnbanChatMemberInput, UnbanChatSenderChatInput, UnhideGeneralForumTopicInput, UniqueGift, UniqueGiftBackdrop, UniqueGiftBackdropColors, UniqueGiftColors, UniqueGiftInfo, UniqueGiftModel, UniqueGiftSymbol, UnpinAllChatMessagesInput, UnpinAllForumTopicMessagesInput, UnpinAllGeneralForumTopicMessagesInput, UnpinChatMessageInput, Update, UpgradeGiftInput, UploadStickerFileInput, User, UserChatBoosts, UserProfileAudios, UserProfilePhotos, UserRating, UsersShared, Venue, VerifyChatInput, VerifyUserInput, Video, VideoChatEnded, VideoChatParticipantsInvited, VideoChatScheduled, VideoChatStarted, VideoNote, VideoQuality, Voice, WebApp, WebAppChat, WebAppData, WebAppInfo, WebAppInitData, WebAppUser, WebhookInfo, WriteAccessAllowed };
3836
+ export { type Accelerometer, type AccelerometerStartParams, type AcceptedGiftTypes, type AddStickerToSetInput, type AffiliateInfo, type AllowedUpdateName, type Animation, type AnswerCallbackQueryInput, type AnswerInlineQueryInput, type AnswerPreCheckoutQueryInput, type AnswerShippingQueryInput, type AnswerWebAppQueryInput, type Api, type ApproveChatJoinRequestInput, type ApproveSuggestedPostInput, type Audio, type BackButton, type BackgroundFill, type BackgroundFillFreeformGradient, type BackgroundFillGradient, type BackgroundFillSolid, type BackgroundType, type BackgroundTypeChatTheme, type BackgroundTypeFill, type BackgroundTypePattern, type BackgroundTypeWallpaper, type BanChatMemberInput, type BanChatSenderChatInput, type BindOrUnbindEventHandler, type BiometricAuthenticateParams, type BiometricManager, type BiometricRequestAccessParams, type Birthdate, type BotCommand, type BotCommandScope, type BotCommandScopeAllChatAdministrators, type BotCommandScopeAllGroupChats, type BotCommandScopeAllPrivateChats, type BotCommandScopeChat, type BotCommandScopeChatAdministrators, type BotCommandScopeChatMember, type BotCommandScopeDefault, type BotDescription, type BotName, type BotShortDescription, type BottomButton, type BusinessBotRights, type BusinessConnection, type BusinessIntro, type BusinessLocation, type BusinessMessagesDeleted, type BusinessOpeningHours, type BusinessOpeningHoursInterval, type CallbackGame, type CallbackQuery, type Chat, type ChatAdministratorRights, type ChatBackground, type ChatBoost, type ChatBoostAdded, type ChatBoostRemoved, type ChatBoostSource, type ChatBoostSourceGiftCode, type ChatBoostSourceGiveaway, type ChatBoostSourcePremium, type ChatBoostUpdated, type ChatFullInfo, type ChatInviteLink, type ChatJoinRequest, type ChatLocation, type ChatMember, type ChatMemberAdministrator, type ChatMemberBanned, type ChatMemberLeft, type ChatMemberMember, type ChatMemberOwner, type ChatMemberRestricted, type ChatMemberUpdated, type ChatOwnerChanged, type ChatOwnerLeft, type ChatPermissions, type ChatPhoto, type ChatShared, type Checklist, type ChecklistTask, type ChecklistTasksAdded, type ChecklistTasksDone, type ChosenInlineResult, type CloseForumTopicInput, type CloseGeneralForumTopicInput, type CloseInput, type CloudStorage, type Contact, type ContentSafeAreaInset, type ConvertGiftToStarsInput, type CopyMessageInput, type CopyMessagesInput, type CopyTextButton, type CreateChatInviteLinkInput, type CreateChatSubscriptionInviteLinkInput, type CreateForumTopicInput, type CreateInvoiceLinkInput, type CreateNewStickerSetInput, type DeclineChatJoinRequestInput, type DeclineSuggestedPostInput, type DeleteBusinessMessagesInput, type DeleteChatPhotoInput, type DeleteChatStickerSetInput, type DeleteForumTopicInput, type DeleteMessageInput, type DeleteMessagesInput, type DeleteMyCommandsInput, type DeleteStickerFromSetInput, type DeleteStickerSetInput, type DeleteStoryInput, type DeleteWebhookInput, type DeviceOrientation, type DeviceOrientationStartParams, type DeviceStorage, type Dice, type DirectMessagePriceChanged, type DirectMessagesTopic, type Document, type DownloadFileParams, type EditChatInviteLinkInput, type EditChatSubscriptionInviteLinkInput, type EditForumTopicInput, type EditGeneralForumTopicInput, type EditMessageCaptionInput, type EditMessageChecklistInput, type EditMessageLiveLocationInput, type EditMessageMediaInput, type EditMessageReplyMarkupInput, type EditMessageTextInput, type EditStoryInput, type EditUserStarSubscriptionInput, type EmojiStatusParams, type EncryptedCredentials, type EncryptedPassportElement, type EventHandlers, type ExportChatInviteLinkInput, type ExternalReplyInfo, type File, type ForceReply, type ForumTopic, type ForumTopicClosed, type ForumTopicCreated, type ForumTopicEdited, type ForumTopicReopened, type ForwardMessageInput, type ForwardMessagesInput, type Game, type GameHighScore, type GeneralForumTopicHidden, type GeneralForumTopicUnhidden, type GetAvailableGiftsInput, type GetBusinessAccountGiftsInput, type GetBusinessAccountStarBalanceInput, type GetBusinessConnectionInput, type GetChatAdministratorsInput, type GetChatGiftsInput, type GetChatInput, type GetChatMemberCountInput, type GetChatMemberInput, type GetChatMenuButtonInput, type GetCustomEmojiStickersInput, type GetFileInput, type GetForumTopicIconStickersInput, type GetGameHighScoresInput, type GetMeInput, type GetMyCommandsInput, type GetMyDefaultAdministratorRightsInput, type GetMyDescriptionInput, type GetMyNameInput, type GetMyShortDescriptionInput, type GetMyStarBalanceInput, type GetStarTransactionsInput, type GetStickerSetInput, type GetUpdatesInput, type GetUserChatBoostsInput, type GetUserGiftsInput, type GetUserProfileAudiosInput, type GetUserProfilePhotosInput, type GetWebhookInfoInput, type Gift, type GiftBackground, type GiftInfo, type GiftPremiumSubscriptionInput, type Gifts, type Giveaway, type GiveawayCompleted, type GiveawayCreated, type GiveawayWinners, type Gyroscope, type GyroscopeStartParams, type HapticFeedback, type HideGeneralForumTopicInput, type InaccessibleMessage, type InlineKeyboardButton, type InlineKeyboardMarkup, type InlineQuery, type InlineQueryResult, type InlineQueryResultArticle, type InlineQueryResultAudio, type InlineQueryResultCachedAudio, type InlineQueryResultCachedDocument, type InlineQueryResultCachedGif, type InlineQueryResultCachedMpeg4Gif, type InlineQueryResultCachedPhoto, type InlineQueryResultCachedSticker, type InlineQueryResultCachedVideo, type InlineQueryResultCachedVoice, type InlineQueryResultContact, type InlineQueryResultDocument, type InlineQueryResultGame, type InlineQueryResultGif, type InlineQueryResultLocation, type InlineQueryResultMpeg4Gif, type InlineQueryResultPhoto, type InlineQueryResultVenue, type InlineQueryResultVideo, type InlineQueryResultVoice, type InlineQueryResultsButton, type InputChecklist, type InputChecklistTask, type InputContactMessageContent, type InputFile, type InputInvoiceMessageContent, type InputLocationMessageContent, type InputMedia, type InputMediaAnimation, type InputMediaAudio, type InputMediaDocument, type InputMediaPhoto, type InputMediaVideo, type InputMessageContent, type InputPaidMedia, type InputPaidMediaPhoto, type InputPaidMediaVideo, type InputPollOption, type InputProfilePhoto, type InputProfilePhotoAnimated, type InputProfilePhotoStatic, type InputSticker, type InputStoryContent, type InputStoryContentPhoto, type InputStoryContentVideo, type InputTextMessageContent, type InputVenueMessageContent, type Invoice, type KeyboardButton, type KeyboardButtonPollType, type KeyboardButtonRequestChat, type KeyboardButtonRequestUsers, type LabeledPrice, type LeaveChatInput, type LinkPreviewOptions, type Location, type LocationAddress, type LocationData, type LocationManager, type LogOutInput, type LoginUrl, type MaskPosition, type MaybeInaccessibleMessage, type MenuButton, type MenuButtonCommands, type MenuButtonDefault, type MenuButtonWebApp, type Message, type MessageAutoDeleteTimerChanged, type MessageEntity, type MessageId, type MessageOrigin, type MessageOriginChannel, type MessageOriginChat, type MessageOriginHiddenUser, type MessageOriginUser, type MessageReactionCountUpdated, type MessageReactionUpdated, type OrderInfo, type OwnedGift, type OwnedGiftRegular, type OwnedGiftUnique, type OwnedGifts, type PaidMedia, type PaidMediaInfo, type PaidMediaPhoto, type PaidMediaPreview, type PaidMediaPurchased, type PaidMediaVideo, type PaidMessagePriceChanged, type PassportData, type PassportElementError, type PassportElementErrorDataField, type PassportElementErrorFile, type PassportElementErrorFiles, type PassportElementErrorFrontSide, type PassportElementErrorReverseSide, type PassportElementErrorSelfie, type PassportElementErrorTranslationFile, type PassportElementErrorTranslationFiles, type PassportElementErrorUnspecified, type PassportFile, type PhotoSize, type PinChatMessageInput, type Poll, type PollAnswer, type PollOption, type PopupButton, type PopupParams, type PostStoryInput, type PreCheckoutQuery, type PreparedInlineMessage, type PromoteChatMemberInput, type ProximityAlertTriggered, type ReactionCount, type ReactionType, type ReactionTypeCustomEmoji, type ReactionTypeEmoji, type ReactionTypePaid, type ReadBusinessMessageInput, type RefundStarPaymentInput, type RefundedPayment, type RemoveBusinessAccountProfilePhotoInput, type RemoveChatVerificationInput, type RemoveMyProfilePhotoInput, type RemoveUserVerificationInput, type ReopenForumTopicInput, type ReopenGeneralForumTopicInput, type ReplaceStickerInSetInput, type ReplyKeyboardMarkup, type ReplyKeyboardRemove, type ReplyParameters, type RepostStoryInput, type ResponseParameters, type RestrictChatMemberInput, type RevenueWithdrawalState, type RevenueWithdrawalStateFailed, type RevenueWithdrawalStatePending, type RevenueWithdrawalStateSucceeded, type RevokeChatInviteLinkInput, type SafeAreaInset, type SavePreparedInlineMessageInput, type ScanQrPopupParams, type SecureStorage, type SendAnimationInput, type SendAudioInput, type SendChatActionInput, type SendChecklistInput, type SendContactInput, type SendDiceInput, type SendDocumentInput, type SendGameInput, type SendGiftInput, type SendInvoiceInput, type SendLocationInput, type SendMediaGroupInput, type SendMessageDraftInput, type SendMessageInput, type SendPaidMediaInput, type SendPhotoInput, type SendPollInput, type SendStickerInput, type SendVenueInput, type SendVideoInput, type SendVideoNoteInput, type SendVoiceInput, type SentWebAppMessage, type SetBusinessAccountBioInput, type SetBusinessAccountGiftSettingsInput, type SetBusinessAccountNameInput, type SetBusinessAccountProfilePhotoInput, type SetBusinessAccountUsernameInput, type SetChatAdministratorCustomTitleInput, type SetChatDescriptionInput, type SetChatMenuButtonInput, type SetChatPermissionsInput, type SetChatPhotoInput, type SetChatStickerSetInput, type SetChatTitleInput, type SetCustomEmojiStickerSetThumbnailInput, type SetGameScoreInput, type SetMessageReactionInput, type SetMyCommandsInput, type SetMyDefaultAdministratorRightsInput, type SetMyDescriptionInput, type SetMyNameInput, type SetMyProfilePhotoInput, type SetMyShortDescriptionInput, type SetPassportDataErrorsInput, type SetStickerEmojiListInput, type SetStickerKeywordsInput, type SetStickerMaskPositionInput, type SetStickerPositionInSetInput, type SetStickerSetThumbnailInput, type SetStickerSetTitleInput, type SetUserEmojiStatusInput, type SetWebhookInput, type SettingsButton, type SharedUser, type ShippingAddress, type ShippingOption, type ShippingQuery, type StarAmount, type StarTransaction, type StarTransactions, type Sticker, type StickerSet, type StopMessageLiveLocationInput, type StopPollInput, type Story, type StoryArea, type StoryAreaPosition, type StoryAreaType, type StoryAreaTypeLink, type StoryAreaTypeLocation, type StoryAreaTypeSuggestedReaction, type StoryAreaTypeUniqueGift, type StoryAreaTypeWeather, type StoryShareParams, type StoryWidgetLink, type SuccessfulPayment, type SuggestedPostApprovalFailed, type SuggestedPostApproved, type SuggestedPostDeclined, type SuggestedPostInfo, type SuggestedPostPaid, type SuggestedPostParameters, type SuggestedPostPrice, type SuggestedPostRefunded, type SwitchInlineQueryChosenChat, type TelegramLoginData, type TelegramLoginOptions, type TelegramLoginService, type TextQuote, type ThemeParams, type TransactionPartner, type TransactionPartnerAffiliateProgram, type TransactionPartnerChat, type TransactionPartnerFragment, type TransactionPartnerOther, type TransactionPartnerTelegramAds, type TransactionPartnerTelegramApi, type TransactionPartnerUser, type TransferBusinessAccountStarsInput, type TransferGiftInput, type UnbanChatMemberInput, type UnbanChatSenderChatInput, type UnhideGeneralForumTopicInput, type UniqueGift, type UniqueGiftBackdrop, type UniqueGiftBackdropColors, type UniqueGiftColors, type UniqueGiftInfo, type UniqueGiftModel, type UniqueGiftSymbol, type UnpinAllChatMessagesInput, type UnpinAllForumTopicMessagesInput, type UnpinAllGeneralForumTopicMessagesInput, type UnpinChatMessageInput, type Update, type UpgradeGiftInput, type UploadStickerFileInput, type User, type UserChatBoosts, type UserProfileAudios, type UserProfilePhotos, type UserRating, type UsersShared, type Venue, type VerifyChatInput, type VerifyUserInput, type Video, type VideoChatEnded, type VideoChatParticipantsInvited, type VideoChatScheduled, type VideoChatStarted, type VideoNote, type VideoQuality, type Voice, type WebApp, type WebAppChat, type WebAppData, type WebAppInfo, type WebAppInitData, type WebAppUser, type WebhookInfo, type WriteAccessAllowed, verifyLoginData };
package/dist/index.js CHANGED
@@ -0,0 +1,19 @@
1
+ // src/login-widget.ts
2
+ var toHex = (buffer) => Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
3
+ var verifyLoginData = async (input) => {
4
+ const dataCheckString = Object.entries(input.data).filter(([key]) => key !== "hash").sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join("\n");
5
+ const encoder = new TextEncoder();
6
+ const secretKey = await crypto.subtle.digest("SHA-256", encoder.encode(input.botToken));
7
+ const signingKey = await crypto.subtle.importKey(
8
+ "raw",
9
+ secretKey,
10
+ { name: "HMAC", hash: "SHA-256" },
11
+ false,
12
+ ["sign"]
13
+ );
14
+ const signature = await crypto.subtle.sign("HMAC", signingKey, encoder.encode(dataCheckString));
15
+ return toHex(signature) === input.data.hash;
16
+ };
17
+ export {
18
+ verifyLoginData
19
+ };
package/package.json CHANGED
@@ -1,26 +1,27 @@
1
1
  {
2
2
  "name": "@effect-ak/tg-bot-api",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "type": "module",
5
5
  "description": "TypeScript types for Telegram Bot Api and Telegram Mini Apps",
6
6
  "license": "MIT",
7
7
  "keywords": [
8
8
  "telegram",
9
+ "telegram-bot",
10
+ "telegram-bot-api",
9
11
  "mini-app",
10
- "typescript"
12
+ "typescript",
13
+ "types"
11
14
  ],
12
15
  "author": {
13
16
  "name": "Aleksandr Kondaurov",
14
17
  "email": "kondaurov.dev@gmail.com"
15
18
  },
19
+ "homepage": "https://tg-bot-sdk.website",
16
20
  "repository": {
17
21
  "type": "git",
18
- "url": "https://github.com/kondaurovDev/tg-bot-client",
22
+ "url": "https://github.com/kondaurovDev/tg-bot-sdk",
19
23
  "directory": "packages/api"
20
24
  },
21
- "bugs": {
22
- "url": "https://github.com/effect-ak/tg-bot-client/issues"
23
- },
24
25
  "publishConfig": {
25
26
  "access": "public"
26
27
  },
@@ -31,7 +32,8 @@
31
32
  "types": "./dist/index.d.ts",
32
33
  "import": "./dist/index.js",
33
34
  "require": "./dist/index.cjs"
34
- }
35
+ },
36
+ "./dist/*": "./dist/*"
35
37
  },
36
38
  "files": [
37
39
  "dist/*.js",
package/readme.md CHANGED
@@ -1,293 +1,27 @@
1
- [![NPM Version](https://img.shields.io/npm/v/%40effect-ak%2Ftg-bot-api)](https://www.npmjs.com/package/@effect-ak/tg-bot-api)
2
- ![Telegram Bot API](https://img.shields.io/badge/BotApi-9.4-blue?link=)
3
- ![Telegram WebApp](https://img.shields.io/badge/Telegram.WebApp-9.1-blue?link=)
4
-
5
- ## Highlights:
6
-
7
- - **Complete and Up-to-Date Telegram Bot API**: The entire API is generated from [the official documentation](https://core.telegram.org/bots/api) using a [code generator](./codegen/main.ts), ensuring this client remains in sync and supports every method and type provided by the **Telegram Bot API**.
8
- - **[Types for Webapps](#webapps-typings)** Types that describe `Telegram.WebApp`. Created by [code generator](./codegen/main.ts) as well.
9
- - **Type Mapping**: Types from the documentation are converted to TypeScript types:
10
- - `Integer` → `number`
11
- - `True` → `boolean`
12
- - `String or Number` → `string | number`
13
- - Enumerated types, such as `"Type of the chat can be either "private", "group", "supergroup" or "channel""`, are converted to a standard union of literal types `"private" | "group" | "supergroup" | "channel"`
14
- - And more...
15
-
16
- ## Webapps typings
17
-
18
- Telegram provides a big [html](https://core.telegram.org/bots/webapps) page that describes `Telegram.WebApp`
19
-
20
- ```typescript
21
- import type { WebApp } from "@effect-ak/tg-bot-client/webapp"
22
-
23
- interface Telegram {
24
- WebApp: TgWebApp
25
- }
26
-
27
- declare const Telegram: Telegram
28
-
29
- const saveData = () => {
30
- Telegram.WebApp.CloudStorage.setItem("key1", "some data", (error) => {
31
- if (error == null) {
32
- console.log("Saved!")
33
- }
34
- })
35
- }
36
- ```
37
-
38
- ## Code generation
39
-
40
- Scrapes the official Telegram documentation HTML and generates:
41
-
42
- - **TypeScript types** for Bot API and Mini Apps (`src/specification/`)
43
- - **Markdown docs** with method/type reference pages (`docs/`)
44
-
45
- ### Pipeline
46
-
47
- ```
48
- core.telegram.org/bots/api core.telegram.org/bots/webapps
49
- | |
50
- fetch & cache fetch & cache
51
- (input/api.html) (input/webapp.html)
52
- | |
53
- v v
54
- DocPage WebAppPage
55
- | |
56
- ┌──────┴──────┐ |
57
- v v v
58
- ExtractedType ExtractedMethod ExtractedWebApp
59
- | | | |
60
- v v v v
61
- types.ts api.ts webapp.ts (types)
62
- | |
63
- └──────┬──────┘
64
- v
65
- docs/ (markdown)
66
- ```
67
-
68
- 1. **Fetch** — `PageProviderService` downloads HTML from `core.telegram.org` and caches it locally in `input/`.
69
-
70
- 2. **Parse** — `DocPage` / `WebAppPage` parse the HTML into a DOM tree (`node-html-parser`). Each entity is located by its `<a class="anchor">` tag.
71
-
72
- 3. **Extract entities** — for every `<h4>` heading on the page the extraction pipeline deterministically converts HTML into typed structures. See [Extraction semantics](#extraction-semantics) below for the full details.
73
-
74
- 4. **Generate TypeScript** — `BotApiCodeWriterService` and `WebAppCodeWriterService` use `ts-morph` to emit `.ts` files with interfaces, type aliases, and method signatures.
75
-
76
- 5. **Generate Markdown** — `MarkdownWriterService` converts the same extracted data into browsable `.md` files with cross-linked types.
77
-
78
- ### Usage
1
+ # @effect-ak/tg-bot-api
79
2
 
80
- ```bash
81
- # generate everything (Bot API types + docs + Mini Apps types)
82
- pnpm gen
3
+ [![NPM Version](https://img.shields.io/npm/v/%40effect-ak%2Ftg-bot-api)](https://www.npmjs.com/package/@effect-ak/tg-bot-api)
4
+ ![Telegram Bot API](https://img.shields.io/badge/BotApi-9.4-blue)
5
+ ![Telegram WebApp](https://img.shields.io/badge/Telegram.WebApp-9.1-blue)
83
6
 
84
- # or individually
85
- pnpm gen:bot:api
86
- pnpm gen:webapp:api
87
- ```
7
+ Complete TypeScript types for Telegram Bot API and Mini Apps, auto-generated from official documentation.
88
8
 
89
- ### Tests
9
+ ## Installation
90
10
 
91
11
  ```bash
92
- pnpm test
93
- ```
94
-
95
- Tests use cached HTML fixtures from `input/` — no network requests during test runs after the first download.
96
-
97
- ## Extraction semantics
98
-
99
- The Telegram Bot API documentation page (`core.telegram.org/bots/api`) is a single long HTML page with a regular, predictable structure. Every type and method is defined as a sequence of sibling HTML elements under its heading. The codegen exploits this regularity to extract everything deterministically, without any heuristic guessing.
100
-
101
- ### Page layout: H3 groups and H4 entities
102
-
12
+ npm install @effect-ak/tg-bot-api
103
13
  ```
104
- <h3>Getting updates</h3> ← group name (section header)
105
- <h4><a class="anchor" name="getUpdates"/>getUpdates</h4> ← entity
106
- <p>...</p> ← description paragraph(s)
107
- <table>...</table> ← field definitions (or <ul> for union types)
108
- <h4><a class="anchor" name="update"/>Update</h4>
109
- <p>...</p>
110
- <table>...</table>
111
- ```
112
-
113
- The batch extractor (`entities.ts`) walks all `<h3>` and `<h4>` nodes in document order:
114
- - **`<h3>`** sets the current section group (e.g. "Getting updates", "Available types").
115
- - **`<h4>`** is an individual entity — a type or a method.
116
-
117
- ### Locating a single entity
118
-
119
- Every `<h4>` heading contains an `<a class="anchor" name="...">` child. This gives a stable, lowercase slug for the entity (e.g. `name="sendmessage"`). To look up a specific entity, `DocPage.getEntity()` does:
120
-
121
- ```ts
122
- this.node.querySelector(`a.anchor[name="${name.toLowerCase()}"]`)
123
- ```
124
-
125
- then extracts from the anchor's parent `<h4>` node.
126
-
127
- ### Type vs Method — first character case
128
-
129
- There is no HTML attribute that distinguishes a type from a method. Instead, Telegram consistently uses:
130
-
131
- - **Uppercase first letter** → Type definition (e.g. `User`, `Chat`, `Message`)
132
- - **Lowercase first letter** → API method (e.g. `sendMessage`, `getUpdates`, `setWebhook`)
133
-
134
- The `isComplexType` / `startsWithUpperCase` helper makes this check. It is the single decision point: uppercase entities are extracted as `ExtractedType`, lowercase as `ExtractedMethod`.
135
-
136
- ### Entity structure: walking siblings from H4
137
-
138
- Starting from the `<h4>` node, the extractor walks `nextElementSibling` to collect:
139
-
140
- 1. **`<p>` paragraphs** — entity description, and (for methods) the return type sentence.
141
- 2. **`<table>`** — field/parameter definitions → produces `EntityFields` (an object type with named properties).
142
- 3. **`<ul>`** — union type members → produces `NormalType` (a union `A | B | C`).
143
14
 
144
- The walk stops when it hits another `<h4>` (next entity), a `<table>`, or a `<ul>`. A safety limit of 10 sibling steps prevents runaway walks on malformed HTML.
15
+ ## Features
145
16
 
146
- ### Description and return type extraction
17
+ - **Always Up-to-Date** generated from [official Telegram docs](https://core.telegram.org/bots/api) via code generator
18
+ - **WebApp Types** — types for `Telegram.WebApp` included
19
+ - **Smart Type Mapping** — `Integer` → `number`, `True` → `boolean`, enums → union literals, etc.
147
20
 
148
- Description `<p>` paragraphs are split on `. ` (period + space) or `.<br>` into individual sentences. Each sentence is stripped of HTML tags to get plain text.
21
+ ## Documentation
149
22
 
150
- For **methods**, return type sentences are identified by three patterns:
23
+ Full documentation, codegen internals, and API reference: **[tg-bot-sdk.website](https://tg-bot-sdk.website)**
151
24
 
152
- | Pattern | Example |
153
- |---------|---------|
154
- | Starts with `"On success"` | "On success, a Message object is returned" |
155
- | Starts with `"Returns "` | "Returns an Array of Update objects" |
156
- | Ends with `"is returned"` | "The sent Message is returned" |
25
+ ## License
157
26
 
158
- Type names are extracted from `<a>` and `<em>` tags inside these sentences using the regex `/\w+(?=<\/(a\|em)>)/g` — this matches the word just before a closing `</a>` or `</em>` tag. Only uppercase-initial names pass (primitives like "true" are skipped).
159
-
160
- Array return types are detected by checking for `"an array of <TypeName>"` (case-insensitive) in the plain text.
161
-
162
- ### Table parsing: 3-column vs 4-column
163
-
164
- Telegram uses two table layouts:
165
-
166
- **4-column tables** (method parameters):
167
-
168
- | Field | Type | Required | Description |
169
- |-------|------|----------|-------------|
170
- | chat_id | Integer or String | Yes | Unique identifier... |
171
- | text | String | Yes | Text of the message... |
172
- | parse_mode | String | Optional | Mode for parsing... |
173
-
174
- Columns: `name` (0), `type` (1), `required` (2), `description` (3).
175
- Column 2 is either `"Yes"` or `"Optional"`.
176
-
177
- **3-column tables** (type fields):
178
-
179
- | Field | Type | Description |
180
- |-------|------|-------------|
181
- | message_id | Integer | Unique message identifier... |
182
- | from | User | Optional. Sender of the message... |
183
-
184
- Columns: `name` (0), `type` (1), `description` (2).
185
- There is no explicit "Required" column — instead, optional fields have their description start with `"Optional."`. The extractor checks:
186
-
187
- ```ts
188
- if (all.length == 3) {
189
- const isOptional = description[0].includes("Optional")
190
- required = !isOptional
191
- }
192
- ```
193
-
194
- Required fields are sorted before optional ones in the output.
195
-
196
- ### Union types from `<ul>` lists
197
-
198
- Some types are defined not by a table but by a bulleted list:
199
-
200
- ```html
201
- <h4>ChatMemberStatus</h4>
202
- <p>This object represents ...</p>
203
- <ul>
204
- <li>ChatMemberOwner</li>
205
- <li>ChatMemberAdministrator</li>
206
- <li>ChatMemberMember</li>
207
- ...
208
- </ul>
209
- ```
210
-
211
- Each `<li>` text becomes one arm of the TypeScript union:
212
-
213
- ```ts
214
- type ChatMemberStatus = ChatMemberOwner | ChatMemberAdministrator | ChatMemberMember | ...
215
- ```
216
-
217
- ### Pseudo-type mapping
218
-
219
- Telegram uses its own type names (pseudo-types). The mapping is straightforward:
220
-
221
- | Telegram pseudo-type | TypeScript |
222
- |---------------------|------------|
223
- | `String` | `string` |
224
- | `Integer`, `Int` | `number` |
225
- | `Float` | `number` |
226
- | `Boolean`, `True`, `False` | `boolean` |
227
- | `Array of X` | `X[]` |
228
- | `X or Y` | `X \| Y` |
229
- | `InputFile` | `{ file_content: Uint8Array, file_name: string }` |
230
-
231
- Nested arrays (`Array of Array of PhotoSize`) are handled by counting `Array of` occurrences and appending the matching number of `[]` brackets.
232
-
233
- ### Enum extraction from descriptions
234
-
235
- Some `String` fields actually represent a finite set of values. The descriptions contain natural-language hints:
236
-
237
- > Type of the emoji, currently one of "dice", "darts", "bowling", "basketball", "football", "slot_machine"
238
-
239
- The extractor looks for **indicator keywords**: `"must be"`, `"always"`, `"one of"`, `"can be"`. When found, it extracts quoted values using a regex that handles both straight quotes (`"`) and Unicode curly quotes (`\u201C`/`\u201D`), which appear in different parts of the Telegram docs.
240
-
241
- These are emitted as string literal unions:
242
-
243
- ```ts
244
- emoji: "dice" | "darts" | "bowling" | "basketball" | "football" | "slot_machine"
245
- ```
246
-
247
- The `parse_mode` field is a special case — it is always overridden to `"HTML" | "MarkdownV2"` regardless of the description text.
248
-
249
- ### The `Function` pseudo-type (Mini Apps)
250
-
251
- The Mini Apps documentation uses `Function` as a pseudo-type for callable fields. When the table says:
252
-
253
- | Field | Type | Description |
254
- |-------|------|-------------|
255
- | sendData() | Function | ... |
256
- | isVersionAtLeast() | Function | ... |
257
-
258
- The extractor detects `pseudoType == "Function"` and converts:
259
- - Fields ending with `()` → function signatures (return type derived from the entity name)
260
- - The field name is trimmed to remove the `()` suffix
261
-
262
- Since the documentation doesn't specify parameter types for these functions, most webapp methods have **manual type overrides** in `typeOverrides` (see `type-system.ts`).
263
-
264
- ### Manual overrides
265
-
266
- Some types cannot be inferred from the HTML structure alone. Three override mechanisms handle these:
267
-
268
- 1. **`typeOverrides`** — per-entity, per-field type replacements. Used extensively for Mini Apps methods (callbacks, complex parameter types) and a few Bot API fields like `allowed_updates` and `sendChatAction.action`.
269
-
270
- 2. **`typeAliasOverrides`** — for types that have no `<table>` or `<ul>` (e.g. `InputFile`). When `findTypeNode` hits the next `<h4>` without finding a type definition, the override provides the TypeScript type.
271
-
272
- 3. **`returnTypeOverrides`** — for methods whose return type sentence is ambiguous or missing (e.g. `sendMediaGroup` returns `Message[]`).
273
-
274
- ## Module map
275
-
276
- ```
277
- codegen/
278
- ├── main.ts entry point, reads MODULE_NAME env var
279
- ├── runtime.ts Effect runtimes (DI wiring)
280
- ├── types.ts shared type aliases (HtmlElement, TsSourceFile)
281
-
282
- ├── scrape/
283
- │ ├── type-system.ts type representation & conversion (NormalType, EntityFields)
284
- │ ├── entity.ts single-entity extraction from HTML nodes
285
- │ ├── page.ts DocPage & WebAppPage — HTML page models
286
- │ └── entities.ts batch extraction — walks full page, collects all types & methods
287
-
288
- └── service/
289
- ├── index.ts barrel re-exports
290
- ├── page-provider.ts fetches & caches documentation HTML
291
- ├── code-writers.ts ts-morph TypeScript code generation
292
- └── markdown.ts markdown docs generation
293
- ```
27
+ MIT