gramstax 0.8.9 → 0.8.11

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.
@@ -1,7 +1,7 @@
1
- "use strict";var ye=Object.create;var V=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,be=Object.prototype.hasOwnProperty;var p=(u,e)=>V(u,"name",{value:e,configurable:!0});var Se=(u,e)=>{for(var t in e)V(u,t,{get:e[t],enumerable:!0})},ie=(u,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ce(e))!be.call(u,s)&&s!==t&&V(u,s,{get:()=>e[s],enumerable:!(n=fe(e,s))||n.enumerable});return u};var oe=(u,e,t)=>(t=u!=null?ye(Te(u)):{},ie(e||!u||!u.__esModule?V(t,"default",{value:u,enumerable:!0}):t,u)),ke=u=>ie(V({},"__esModule",{value:!0}),u);var _e={};Se(_e,{BlockKeyboard:()=>X,CacheExternal:()=>W,Ctx:()=>K,Gramstax:()=>J,LabelKeyboard:()=>Y,LoggingHelper:()=>Q,MockTelegramServer:()=>se,PageManager:()=>x,TemplateEngine:()=>M,TemplateManager:()=>$,WebhookQueue:()=>E,WorkerThreadExport:()=>Z,WorkerThreadGatewayClient:()=>j,WorkerThreadGatewayServer:()=>q,WorkerThreadInit:()=>ee,WorkerThreadLaunch:()=>N,WorkerThreadPool:()=>te,WorkerThreadRpc:()=>P,log:()=>U});module.exports=ke(_e);var we=p(()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,"getImportMetaUrl"),f=we();var ae=require("logging-pretty");var Q=class extends ae.LoggingPretty{static{p(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,n){this.error(`[${t?`${t}:${n}`:n}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let n=this.timers.get(e);if(n===void 0){this.debug(`${e}: Timer was never started`);return}let s=(Number(process.hrtime.bigint()-n)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${s}ms)`):this.debug(`${e} (took ${s}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let n=this.timeCheck(e);if(n===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${n}ms)`):this.debug(`${e} (${n}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},U=new Q;var re=require("keyv"),ce=oe(require("@keyv/redis"),1);var W=class extends re.Keyv{constructor(t="memory",n,s,i){let o;t.startsWith("redis")&&(o=new ce.default(t)),t==="memory"&&(o=new Map),i?.forceStore&&(o=i.forceStore);super({store:o,namespace:s,ttl:n});this.url=t}static{p(this,"CacheExternal")}refreshLruCache(t){let n=this.store,s=this.opts.namespace?this.opts.namespace?.length+1:null,i=n.keys().toArray();for(let o=0;o<i.length;o++){let a=i[o];if(o==t)return;this.get(s?a.slice(s):a)}}};var z=require("timers/promises"),O=require("grammy");var K=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,n,s,i,o,a=!1){try{this.temp.isAnswer=!0;let r=30,c=t.map(l=>this.templateManager.getMessage(this.data.name,i,l,s));for(let l=0;l<e.length;l++){let d=e[l],h=c[l];await this.ct.api.sendMessage(d,h,{parse_mode:"HTML",reply_markup:n,...o}),l+1==r&&await(0,z.setTimeout)(1200)}}catch(r){if(a)throw r}}async broadcastMedia(e,t,n,s,i,o,a=!1){try{this.temp.isAnswer=!0;let r=30,c=t.map(l=>this.templateManager.getMedia(this.data.name,i,l,s));for(let l=0;l<e.length;l++){let d=e[l],h=c[l];if(!h)continue;let m={parse_mode:"HTML",reply_markup:n,...o};h.type=="photo"&&await this.ct.api.sendPhoto(d,h.src,{caption:h.caption,...m}),h.type=="video"&&await this.ct.api.sendVideo(d,h.src,{caption:h.caption,...m}),h.type=="audio"&&await this.ct.api.sendAudio(d,h.src,{caption:h.caption,...m}),h.type=="document"&&await this.ct.api.sendDocument(d,h.src,{caption:h.caption,...m}),h.type=="animation"&&await this.ct.api.sendAnimation(d,h.src,{caption:h.caption,...m}),h.type=="voice"&&await this.ct.api.sendVoice(d,h.src,m),h.type=="video_note"&&await this.ct.api.sendVideoNote(d,h.src,m),h.type=="sticker"&&await this.ct.api.sendSticker(d,h.src,m),h.type=="location"&&await this.ct.api.sendLocation(d,parseInt(h.latitude),parseInt(h.longitude),m),h.type=="contact"&&await this.ct.api.sendContact(d,h.phone,h.first_name,{vcard:h.vcard,...m}),l+1==r&&await(0,z.setTimeout)(1200)}}catch(r){if(a)throw r}}async reply(e,t,n,s){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,n,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...s})}async replyMedia(e,t,n,s,i){this.temp.isAnswer=!0;let o=this.templateManager.getMedia(this.data.name,s,this.userLanguage,n),a={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(o.src,{caption:o.caption,...a});if(e=="video")return await this.ct.replyWithVideo(o.src,{caption:o.caption,...a});if(e=="audio")return await this.ct.replyWithAudio(o.src,{caption:o.caption,...a});if(e=="document")return await this.ct.replyWithDocument(o.src,{caption:o.caption,...a});if(e=="animation")return await this.ct.replyWithAnimation(o.src,{caption:o.caption,...a});if(e=="voice")return await this.ct.replyWithVoice(o.src,a);if(e=="video_note")return await this.ct.replyWithVideoNote(o.src,a);if(e=="sticker")return await this.ct.replyWithSticker(o.src,a);if(e=="location")return await this.ct.replyWithLocation(parseInt(o.latitude),parseInt(o.longitude),a);if(e=="contact")return await this.ct.replyWithContact(o.phone,o.first_name,{vcard:o.vcard,...a})}async replyPhoto(e,t,n,s){return this.replyMedia("photo",e,t,n,s)}async replyVideo(e,t,n,s){return this.replyMedia("video",e,t,n,s)}async replyAudio(e,t,n,s){return this.replyMedia("audio",e,t,n,s)}async replyDocument(e,t,n,s){return this.replyMedia("document",e,t,n,s)}async replyAnimation(e,t,n,s){return this.replyMedia("animation",e,t,n,s)}async replyVoice(e,t,n,s){return this.replyMedia("voice",e,t,n,s)}async replyVideoNote(e,t,n,s){return this.replyMedia("video_note",e,t,n,s)}async replySticker(e,t,n,s){return this.replyMedia("sticker",e,t,n,s)}async replyLocation(e,t,n,s){return this.replyMedia("location",e,t,n,s)}async replyContact(e,t,n,s){return this.replyMedia("contact",e,t,n,s)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,n,s,i=!0){try{this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,n,this.userLanguage,t);return await this.ct.editMessageText(o,{parse_mode:"HTML",reply_markup:e,...s})}catch(o){if(i)await this.reply(e,t,n,s);else throw o}}async editMedia(e,t,n,s,i,o,a=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,s,this.userLanguage,n);return e=="voice"?(await this.delete(),await this.replyVoice(t,n,s,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,n,s,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,n,s,i)):e=="location"?(await this.delete(),await this.replyLocation(t,n,s,i)):e=="contact"?(await this.delete(),await this.replyContact(t,n,s,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...o})}catch(r){if(a===!0)await this.reply(t,n,s,o);else throw r}}async editPhoto(e,t,n,s,i){return await this.editMedia("photo",e,t,n,s,i)}async editVideo(e,t,n,s,i){return await this.editMedia("video",e,t,n,s,i)}async editAudio(e,t,n,s,i){return await this.editMedia("audio",e,t,n,s,i)}async editDocument(e,t,n,s,i){return await this.editMedia("document",e,t,n,s,i)}async editAnimation(e,t,n,s,i){return await this.editMedia("animation",e,t,n,s,i)}async editVoice(e,t,n,s){return await this.editMedia("voice",e,t,n,s)}async editVideoNote(e,t,n,s){return await this.editMedia("video_note",e,t,n,s)}async editSticker(e,t,n,s){return await this.editMedia("sticker",e,t,n,s)}async editLocation(e,t,n,s){return await this.editMedia("location",e,t,n,s)}async editContact(e,t,n,s){return await this.editMedia("contact",e,t,n,s)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,n){try{let s={method:e,params:t,...n},i=await this.cacheSession.set(`${this.userId}`,s);return i&&(this.temp.session=s),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let n=typeof e=="function"?{callbackData:e}:e||{},s=n.callbackData,i=this.prototype.addArgs.bind(this.prototype),o=n.name||"";return{name:o,intentText:n.intentText||o,intentCommandText:n.intentCommandText||o,intentCallbackData:o,callbackData:s?function(...r){return i(this.intentCallbackData,"colon",s(...r))}:function(){return this?.intentCallbackData},_positionArgText:n.intentText?n.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,n,s){let[i,o]=n.split("-"),a=parseInt(i),r=o?parseInt(o):null,c=t.length,l=e;for(let d=0;d<c;d++){let h=t[d];if(s(h,d),r===null)(d+1)%a===0&&d<c-1&&l.row();else{let m=c-(d+1);(m===r||m>r&&(d+1)%a===0)&&l.row()}}return e}bottomKeyboardT(e="1",t,n){return this.bottomKeyboard((s,i)=>this.keyboardCols(s,i,e,o=>s.text(o)),{baseId:t??void 0,data:n})}inlineKeyboardT(e,t="1",n,s){return this.inlineKeyboard((i,o)=>this.keyboardCols(i,o,t,(a,r)=>{let c=e[r],l=typeof c=="string"?c:c.data.callbackData();i.text(a,l)}),{baseId:n??void 0,data:s})}inlineKeyboard(e,t){let n=this.data.name;if(t?.cache===!0){let a=`${n}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(a);if(!r){let c=new O.InlineKeyboard,l=this.templateManager.getKeyboard(n,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,l);return this.cacheKeyboard.set(a,d),d}return r}let s=new O.InlineKeyboard,i=this.templateManager.getKeyboard(n,t?.baseId,this.userLanguage,"inline",t?.data);return e(s,i)}bottomKeyboard(e,t){let n=this.data.name;if(t?.cache===!0){let a=`${n}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(a);if(!r){let c=new O.Keyboard,l=this.templateManager.getKeyboard(n,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,l);return d.resized(!0),this.cacheKeyboard.set(a,d),d}return r}let s=new O.Keyboard,i=this.templateManager.getKeyboard(n,t?.baseId,this.userLanguage,"bottom",t?.data),o=e(s,i);return o.resized(),o}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,n){let s=this.getSeperatorTag(t),i="";for(let o=0;o<n.length;o++){let a=n[o];a!=null&&a!==""&&(i+=s+a)}return e+i}getArgs(e="",t,n=1){if(!e)return[];let s=this.getSeperatorTag(t);return e.split(s).slice(n)}getIntent(e="",t,n=1){if(!e)return"";let s=this.getSeperatorTag(t),i=e.split(s);return n==1?i[0]:i.slice(0,n).join(s)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};var G=require("path"),F=require("fs"),he=require("module");var x=class{static{p(this,"PageManager")}static _getFile(e,t,n=0){let i=Object.values(e)[n];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return(0,G.join)(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let s=(0,he.createRequire)(e)(e);return this._getFile(s,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let n=await import(`${e}?t=${Date.now()}`);return this._getFile(n,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!(0,F.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,F.readdirSync)(e).map(s=>{let i=(0,G.join)(e,s);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!(0,F.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,F.readdirSync)(e).forEach(n=>{let s=(0,G.join)(e,n);delete require.cache[require.resolve(s)]}),!0}};var le=require("fs"),me=require("url"),v=require("path");var w=require("path"),C=require("fs"),de=require("chokidar");var M=class{static{p(this,"TemplateEngine")}static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,n)=>`\${(data && data["${n}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,n)=>`\${(() => { try { return ${n} } catch(e) { try { with(data || {}) { return ${n} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n={};for(let s of e.matchAll(t)){let i=s[2]??"default",a=(s[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();n[i]=a}return n}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,n)=>{let s=n.trim();return s?`\${(() => { if (!data) return ''; try { with(data) { ${s} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,n)=>n.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(n,s,i)=>{if(!s)return"";let o="",a=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=a.exec(i))!==null;){let d=(c[1]||"").split(",").map(m=>m.trim()),h=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(m=>{o+=`case "${m}": `}),o+=`return \`${h}\`; `}let l=r.exec(i);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();o+=`default: return \`${d}\`; `}else o+="default: return ''; ";return`\${(() => { switch((data && data["${s}"])) { ${o} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(n,s,i)=>{let o={},a=/(\w+)="([^"]*)"/g;if(s)for(let h of s.matchAll(a))o[h[1]]=h[2];let r=o.src;if(!r)return"";let c=o.join??"\\n",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(h,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":h);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${l}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,n={};for(let s of e.matchAll(t)){let i=s[1],o=s[2],a={},r=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(r))a[m[1]]=m[2];let c=a.lang||"default",l=a.type,d=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),h={type:l};a.src&&(h.src=a.src),d&&l!=="video_note"&&l!=="sticker"&&(h.caption=d),l==="location"&&(a.latitude&&(h.latitude=a.latitude),a.longitude&&(h.longitude=a.longitude),d&&(h.caption=d)),l==="contact"&&(a.phone&&(h.phone=a.phone),a.first_name&&(h.first_name=a.first_name),a.last_name&&(h.last_name=a.last_name),a.vcard&&(h.vcard=a.vcard),d&&(h.caption=d)),n[c]=h}return n}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,n={};for(let[,s,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(s)for(let l of s.matchAll(a))o[l[1]]=l[2];let r=o.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();n[r]=c}return n}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,n={};for(let[,s,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.scope||"default",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();n[r]||(n[r]={}),n[r][c]=l}return n}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,n={};for(let[,s,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.type==="bottom"?"bottom":"inline",l=i.trim();n[r]||(n[r]={}),n[r][c]=l}return n}static _compileToFunction(e,t){let n;t?n=e.map(o=>`\`${o}\``).join(","):n=`\`${e}\``;let s=n;if(s=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(s))),t){let i=`return [${s}]`;return new Function("data",i)}else{let i=`return ${s}`;return new Function("data",i)}}static compileBlockMedia(e,t){let n=t||this._processBaseBlocks(e),s={};for(let[i,o]of Object.entries(n)){let a=this._processMediaBlocks(o);s[i]={};for(let[r,c]of Object.entries(a)){let l={};for(let[d,h]of Object.entries(c)){if(d==="type"||typeof h!="string")continue;let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(h)))));l[d]=this._compileToFunction(m,!1)}s[i][r]=d=>{let h={...c};for(let[m,g]of Object.entries(l))h[m]=g(d);return h}}}return s}static compileBlockMessage(e,t){let n=t||this._processBaseBlocks(e),s={};for(let[i,o]of Object.entries(n)){let a=this._processMessageBlocks(o);s[i]={};for(let[r,c]of Object.entries(a)){let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));s[i][r]=this._compileToFunction(l,!1)}}return s}static compileBlockDescription(e,t){let n=t||this._processBaseBlocks(e),s={};for(let[i,o]of Object.entries(n)){let a=this._processDescriptionBlocks(o);s[i]={};for(let[r,c]of Object.entries(a))for(let[l,d]of Object.entries(c)){s[i][l]||(s[i][l]={});let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));s[i][l][r]=this._compileToFunction(h,!1)}}return s}static compileBlockKeyboards(e,t){let n=t||this._processBaseBlocks(e),s={};for(let[i,o]of Object.entries(n)){let a=this._processKeyboardBlocks(o);s[i]={};for(let[r,c]of Object.entries(a)){s[i][r]={};for(let[l,d]of Object.entries(c)){let m=d.split(/(?<!\\),\s*/).map(g=>g.replace(/\\,/g,",").trim()).map(g=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(g))))));s[i][r][l]=this._compileToFunction(m,!0)}}}return s}static _extractBlock(e,t,n="default",s="all",i){let o=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,a=e,r=!1;for(let c of e.matchAll(o))if((c[2]??"default")===n){a=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(n==="default"&&!c))return""}if(t){if(t==="all")return a;let c=Array.isArray(t)?t:[t],l=[];for(let h of c){let m=new RegExp(`([ \\t]*)<${h}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${h}>`,"gi");for(let g of a.matchAll(m)){let _=g[2];if(i){let T=/lang="([^"]*)"/i,I=_?.match(T);if(((I?I[1]:void 0)||"default")!==i)continue}l.push({start:g.index,content:g[0],innerContent:g[3]??""})}}l.sort((h,m)=>h.start-m.start);let d=p(h=>{let m=h.split(`
2
- `);if(m.length<=1)return h.trim();let g=m.filter(T=>T.trim().length>0);if(g.length===0)return"";let _=g.reduce((T,I)=>{let k=I.match(/^([ \t]*)/),A=k?k[1].length:0;return A<T?A:T},1/0);return m.map(T=>T.length>=_?T.slice(_):T.trimStart()).join(`
3
- `).trim()},"processResult");return s==="all"?l.map(m=>d(m.content)).join(`
4
- `):l.map(m=>d(m.innerContent)).join(`
5
- `)}return a}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,n=[];return{processed:e.replace(t,(i,o,a)=>{let r={},c=/(\w+)="([^"]*)"/g;if(a)for(let m of a.matchAll(c))r[m[1]]=m[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(m=>m.trim()).filter(m=>m):d=r.block);let h={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:o||""};return n.push(h),`${o}__IMPORT_${n.length-1}__`}),imports:n}}static processImportBlocks(e,t,n=0,s){if(n>10)return"";let{processed:i,imports:o}=this._processImportBlocks(e),a=i;for(let r=0;r<o.length;r++){let c=o[r],l=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(s&&s.has(l))d=s.get(l);else{let m=t(c.src);d=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,t,n+1,s)),s&&s.set(l,d)}let h=d.split(`
6
- `).map((m,g)=>g===0?m:c.indent+m).join(`
7
- `);a=a.replace(`__IMPORT_${r}__`,h)}return a}};var $=class{static{p(this,"TemplateManager")}_map=new Map;_engine=M;_watcher=[];_pageManager=x;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:n=!1}=e;this._path=t,this._isWatchEnabled=n,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!(0,C.existsSync)(t))throw new Error(`Template base path is not exists: ${t}`);if(!(0,C.statSync)(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let n=this._path[t],s=(0,de.watch)(n,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=s,s.on("change",this._handleFileChange.bind(this)),s.on("add",this._handleFileAdd.bind(this)),s.on("unlink",this._handleFileDelete.bind(this)),s.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(e){let t=(0,w.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=(0,w.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=(0,w.basename)(e),n=this._getKey(t);this._map.has(n)&&this._map.delete(n)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=[];for(let s=0;s<this._path.length;s++){let i=this._path[s],a=(0,C.readdirSync)(i,"utf8").filter(r=>this._isValidFile(r));for(let r of a){let c=(0,w.join)(i,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")e.set(d,(0,C.readFileSync)(c,"utf8"));else if(l===".ts"||l===".js"){let h=x.getFileSync(c);h?.template!==void 0&&(e.set(d,h.template),t.push(h))}}}let n=new Map;for(let[s,i]of e.entries())this._compile(s,i,void 0,n,e);e.clear(),n.clear();for(let s of t)s.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let n=this._path[t],s=(0,w.join)(n,e),i=this._getExtension(e),o=this._getKey(e);if(i==".html"){let a=(0,C.readFileSync)(s,"utf8");this._compile(o,a)}else if(i==".ts"||i==".js"){let a=x.getFileSync(s);a?.template!==void 0&&(this._compile(o,a.template),a.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return(0,w.extname)(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let n=(0,w.extname)(e).toLowerCase();if(n){let a=(0,w.join)(t,e);if((0,C.existsSync)(a)&&(0,C.statSync)(a).isFile()){if(n===".html")return(0,C.readFileSync)(a,"utf8");if(n===".ts"||n===".js")try{return x.getFileSync(a)?.template??null}catch{return null}}continue}let s=(0,w.join)(t,`${e}.ts`),i=(0,w.join)(t,`${e}.js`);if((0,C.existsSync)(s)&&(0,C.statSync)(s).isFile())try{return x.getFileSync(s)?.template??null}catch{}else if((0,C.existsSync)(i)&&(0,C.statSync)(i).isFile())try{return x.getFileSync(s)?.template??null}catch{}let o=(0,w.join)(t,`${e}.html`);if((0,C.existsSync)(o)&&(0,C.statSync)(o).isFile())return(0,C.readFileSync)(o,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,n,s,i){let o=this._map.get(e),a=o||{},r=!1,c=M.processImportBlocks(t,d=>i&&i.has(d)?i.get(d):this._readTemplateFile(d),0,s),l=M._processBaseBlocks(c);(n===void 0||n?.media===!1||o?.media===void 0)&&(a.media=M.compileBlockMedia(c,l),r=!0),(n===void 0||n?.message===!1||o?.message===void 0)&&(a.message=M.compileBlockMessage(c,l),r=!0),(n===void 0||n?.keyboard===!1||o?.keyboard===void 0)&&(a.keyboard=M.compileBlockKeyboards(c,l),r=!0),(n===void 0||n?.description===!1||o?.description===void 0)&&(a.description=M.compileBlockDescription(c,l),r=!0),r&&this._map.set(e,a)}getMedia(e,t="default",n="default",s){let o=this._map.get(e)?.media?.[t],a=o?.[n]||o?.default;try{if(!a)throw new Error("Media function not found, please check your template");return a(s)}catch{return{}}}getMessage(e,t="default",n="default",s){try{let o=this._map.get(e)?.message?.[t],a=o?.[n]||o?.default;if(!a)throw"";return a(s)}catch{return""}}getDescription(e,t="default",n="default",s="default",i){try{let a=this._map.get(e)?.description?.[t]?.[s],r=a?.[n]||a?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",n="default"){try{let i=this._map.get(e)?.description?.[t]?.[n];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let s=this._map.get(e)?.description?.[t];return s?Object.keys(s):[]}catch{return[]}}getKeyboard(e,t="default",n="default",s="inline",i){try{let a=this._map.get(e)?.keyboard?.[t],r=a?.[n]?.[s]||a?.default?.[s];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let n=0;n<this._path.length;n++){let s=(0,w.join)(this._path[n],e);if((0,C.existsSync)(s))return(0,C.writeFileSync)(s,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};var L=require("grammy");var E=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}static{p(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var Ie=(0,v.dirname)((()=>{try{return __filename}catch{return(0,me.fileURLToPath)(f)}})()),xe=JSON.parse((0,le.readFileSync)((0,v.join)(Ie,"../../package.json"),"utf-8")).version,J=class{static{p(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?U:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${xe}`),this.cacheSession=e.cacheSession||new W("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new $({path:[(0,v.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.token),this.bot.catch(this._onCatch),this._registerOnCallbackQueryData(),this._registerOnMessageText(),this._registerOnMessagePhoto(),this._registerOnMessageVideo(),this._registerOnMessageAudio(),this._registerOnMessageDocument(),this._registerOnMessageAnimation(),this._registerOnMessageVoice(),this._registerOnMessageVideoNote(),this._registerOnMessageSticker(),this._registerOnMessageLocation(),this._registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this._pageLoads(),process.once("SIGINT",()=>this.bot.stop()),process.once("SIGTERM",()=>this.bot.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this._runPolling();else if(e.deploy.startsWith("webhook:"))this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this._runServerless(e.deploy.split("serverless:")[1]);else if(!e.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,n){await this.executeSyncBlocksDescription(this.pages);let{username:s}=e;this.log?.success?.(`Telegram bot polling started: ${s} ${t=="webhook"||t=="serverless"?`(${n})`:""}`),this.hookAfterStart()}createBot(e){return new L.Bot(e,this.botConfig)}createCtx(e){return new K({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:p(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),n=(0,L.webhookCallback)(this.bot,"bun"),s=this.webhookQueue,i=s?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):n;let o=i?new E(s?.maxQueueSize??5e3):void 0,a=s?.workerCount??8,r=s?.perChatConcurrency??1,c=s?.blockWhenFull!==!1,l=new Map,d=new Map;this.webhookQueueInstance=o;let h=p(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),m=p(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let S=String(y),b=l.get(S)||0;if(b<r)return l.set(S,b+1),()=>this._releaseWebhookChat(S,l,d);await new Promise(ge=>{let ne=d.get(S)||[];ne.push(ge),d.set(S,ne)});let R=(l.get(S)||0)+1;return l.set(S,R),()=>this._releaseWebhookChat(S,l,d)},"acquireChat");if(i&&o){await this.bot.init();for(let y=0;y<a;y++)this._startWebhookWorker(o,m,h)}let g=new URL(e).pathname,_=this.log,T="/stats_queue";this.webhookServer?.stop();let I=t({async fetch(y){let{pathname:S}=new URL(y.url);if(y.method=="POST"&&S==g){if(!i||!o)return n(y);if(!c&&o.length>=(s?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let b=await y.json();return await o.enqueue(b),new Response("OK",{status:200})}catch(b){return _?.error?.(`Webhook queue error: ${String(b)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&S==T){let b=o?.getStats()||{length:0,maxSize:s?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:T,timestamp:new Date().toISOString(),maxQueueSize:s?.maxQueueSize??5e3,workerCount:a,perChatConcurrency:r,blockWhenFull:c,queue:b,activeChats:l.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&S=="/"){let b=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:b}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=I;let k=p(()=>{this.webhookServer?.stop(),this.webhookServer=void 0},"stopServer");process.once("SIGINT",k),process.once("SIGTERM",k),(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let D=await this.bot.api.getMe();await this._onStart(D,"webhook",e)}_startWebhookWorker(e,t,n){p(async()=>{for(;;){let i=await e.dequeue(),o=await t(n(i));try{await this.bot.handleUpdate(i)}catch(a){this.log?.error?.(`Webhook worker error: ${String(a)}`)}finally{o()}}},"run")()}_releaseWebhookChat(e,t,n){let s=t.get(e)||0,i=Math.max(0,s-1);i===0?t.delete(e):t.set(e,i);let o=n.get(e);o&&o.length>0&&(o.shift()(),o.length===0&&n.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,n=this.webhookQueue.workerCount??8,s=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:n,perChatConcurrency:s,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=(0,L.webhookCallback)(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:n}=(0,v.parse)(t);e.data.name||(e.data.name=n),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,n){let s=e.data.name,i=e.prototype,o="handle",a="Args",r="Command",c="Caption",l="Free",d=t.routeDynamic,h=t.routeDynamicSpesific;t.all[s]=e;for(let m=0;m<t.lenListRouteStaticSession;m++){let g=t.listRouteStaticSession[m];if(typeof i[g]!="function")continue;let _=t.routeStatic[g],T=t.routeStaticIntent[g],I=t.routeStaticSession[g],k={name:s,routeName:g},A=_||T;if(A!==void 0){let D=g.includes(r),y=g.endsWith("CallbackData"),S=g.endsWith("Text"),b;if(D){let R=e.data.intentCommandText;b=R?`/${R}`:void 0}else if(y){let R=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(R=String(n),e.data.intentCallbackData=R),b=R}else S?b=e.data.intentText:b=e.data.name;b&&(A[b]=k)}if(I!==void 0){let y=`methodSession${g.replace("handle","")}`,S=i[y]?.(s);I[S]=k}if(g.startsWith("handleFree")){let D=g.replace(o,"").replace(a,"").replace(r,"").replace(c,"").replace(l,"").toLowerCase();h[D].push(k)}}i.handleFree&&d.push(s)}async executeSyncBlocksDescription(e){let t=new Map,n=e.routeStatic.handleCommandText;for(let[,s]of Object.entries(n)){let i=s.name,o=this.templateManager.getDescriptionScopes(i);for(let a of o){t.has(a)||t.set(a,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",a);for(let c of r)t.get(a).add(c)}}for(let[s,i]of t)for(let o of i){let a=[];for(let[,l]of Object.entries(n)){let d=l.name,h=this.templateManager.getDescription(d,"default",o,s);h&&a.push({command:d,description:h})}if(a.length===0)continue;let r={type:s},c=o==="default"?void 0:o;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(m=>({command:m.command,description:m.description})).sort((m,g)=>m.command.localeCompare(g.command))),h=JSON.stringify(a.sort((m,g)=>m.command.localeCompare(g.command)));d!==h&&(await this.bot.api.setMyCommands(a,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${s},${c?` lang: ${c},`:""} total (${a.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${s},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}_pageLoads(){this.log?.info?.("Load pages..");let e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],n=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],s=p((a,r)=>Object.fromEntries(a.map(c=>[c,r()])),"makeObject"),i=p(()=>[],"initDynamicSpesific"),o={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:s(e,()=>({})),routeStaticIntent:s(t,()=>({})),routeStaticSession:s(n,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:n,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:n.length};return x.getFileManySync(void 0).forEach(({path:a,page:r},c)=>{this._pageBuildData(r,a),this._pageSorts(r,o,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(o.all).length})`),o}async _pageRoutes(e,t){let n,s;if(n===void 0){let o=await e.getSession();if(o){let a=o.method,r=this.pages.routeStaticSession,c=e.callbackData,l=e.msgText,d=e.msgCaption,h=c||l||d,m=t==="callbackdata",g=m?"colon":"space",_=h&&e.haveArgs(h,g)?e.getIntent(h,g,1):void 0,T=!m&&h?e.getIntent(h,"space",2):void 0;for(let I=0;I<this.pages.lenListRouteStaticSession;I++){let k=this.pages.listRouteStaticSession[I];if(k.toLowerCase().endsWith(t)){if(h){if(this.pages.routeStatic[k]?.[h])continue;let A=this.pages.routeStaticIntent[k];if(A&&(_&&A[_]||T&&A[T]))continue}s=r[k][a]}if(s)break}s!==void 0&&(n=this.pages.all[s.name])}}if(n===void 0){let o=e.callbackData,a=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.toLowerCase().endsWith(t)&&(s=c[d][o||a||r]),s)break}s!==void 0&&(n=this.pages.all[s.name])}if(n===void 0){let o=this.pages.routeStaticIntent,a=t==="callbackdata",r=a?"colon":"space",c=a?e.callbackData:e.msgText||e.msgCaption,l=e.haveArgs(c,r);if(c&&l)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let h=this.pages.listRouteStaticIntent[d];if(!h.toLowerCase().endsWith(t))continue;let m=o[h];if(s=m[e.getIntent(c,r,1)],!s&&!a&&(s=m[e.getIntent(c,"space",2)]),s)break}s!==void 0&&(n=this.pages.all[s.name])}if(n!==void 0&&s!==void 0){if(!n.prototype[s.routeName])return;let a=await new n(e)[s.routeName]?.();return e.temp.isAnswer===!0?a:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let o=0;o<i.length;o++){let a=i[o];if(a===void 0)continue;let r=this.pages.all[a.name];r!==void 0&&typeof r.prototype[a.routeName]=="function"&&await new r(e)[a.routeName]()}for(let o=0;o<this.pages.routeDynamic.length;o++){let a=this.pages.routeDynamic[o];if(a===void 0)continue;let r=this.pages.all[a];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,n,s){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let n=this.createCtx(e);try{if(await this.hookBeforeRoute(n,t)===!1)return;await this._pageRoutes(n,t)===null&&await this.hookErrorInputNotFoundPage(n)}catch(s){await this.hookErrorPage(n,t,s,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(n){await this.hookErrorPage(t,"onCallbackQueryData",n,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"contact")}_registerOnCallbackQueryData(){this.bot.on("callback_query:data",this._onCallbackQueryData.bind(this))}_registerOnMessageText(){this.bot.on("message:text",this._onMessageText.bind(this))}_registerOnMessagePhoto(){this.bot.on("message:photo",this._onMessagePhoto.bind(this))}_registerOnMessageVideo(){this.bot.on("message:video",this._onMessageVideo.bind(this))}_registerOnMessageAudio(){this.bot.on("message:audio",this._onMessageAudio.bind(this))}_registerOnMessageDocument(){this.bot.on("message:document",this._onMessageDocument.bind(this))}_registerOnMessageAnimation(){this.bot.on("message:animation",this._onMessageAnimation.bind(this))}_registerOnMessageVoice(){this.bot.on("message:voice",this._onMessageVoice.bind(this))}_registerOnMessageVideoNote(){this.bot.on("message:video_note",this._onMessageVideoNote.bind(this))}_registerOnMessageSticker(){this.bot.on("message:sticker",this._onMessageSticker.bind(this))}_registerOnMessageLocation(){this.bot.on("message:location",this._onMessageLocation.bind(this))}_registerOnMessageContact(){this.bot.on("message:contact",this._onMessageContact.bind(this))}};var X=class{static{p(this,"BlockKeyboard")}static label;static _build(e,t,n,s){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");n||(n="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let o=p((a,r)=>`<keyboard type="${n}" lang="${r}">${s?this.label._reverse(a):a}</keyboard>`,"pro");return t?o(i[t],t):Object.keys(i).map(a=>o(i[a],a)).join(" ")}};var Y=class{static{p(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,n)=>(t[n]=this._reverse(e[n]),t),{})}};var H=require("worker_threads");var P=class{constructor(e,t){this.send=e;this.register=t}static{p(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,n=this.send,{id:s,method:i,params:o,result:a,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let l=await c.apply(this.register,o);n({id:s,result:l})}catch(c){n({id:s,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(a!==void 0){let c=t.get(s);c&&(c.resolve(a),t.delete(s))}else if(r!==void 0){let c=t.get(s);c&&(c.reject(r),t.delete(s))}}makeId(){return Math.random()}makeRequest(e,t,n=!0,s){let i=this.makeId(),o={id:i,method:e,params:t,...s};return n?new Promise((a,r)=>{this.map.set(i,{resolve:a,reject:r}),this.send(o)}):this.send(o)}};var N=class{constructor(e,t,n){this.path=e;this.argv=t;this.register=n;this.init(),n||(n=this),this.rpc=new P(this.send.bind(this),n)}static{p(this,"WorkerThreadLaunch")}static isMainThread=H.isMainThread;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new H.Worker(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,n=!0,s){return this.rpc.makeRequest(e,t,n,s)}};var Z=class u{static{p(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(s,i){if(!(typeof i!="string"||i==="then"))return async(o,...a)=>{let r=o.gatewayClients.get(e);return r||(r=await o.createGatewayClient(e)),r.request(i,a)}}}),n=p(function(s){return new Proxy({},{get(i,o){if(!(typeof o!="string"||o==="then"))return async(...a)=>{let r=s.gatewayClients.get(e);return r||(r=await s.createGatewayClient(e)),r.request(o,a)}}})},"ctor");return Object.setPrototypeOf(n,t),n}static init(e){let{WTInit:t,WTLaunch:n=N,path:s,wrap:i}=e,o=`for-${s}`;if(process.argv[2]===o)return new t,{launchGatewayClient:p(d=>u.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let a,r=new Proxy({},{get(d,h){if(h!=="then")return h==="sendRequest"||h==="request"||h==="kill"||h==="send"?(...m)=>{if(!a)throw new Error(`Thread at ${s} not launched yet.`);return a[h](...m)}:(...m)=>{if(!a)throw new Error(`Thread at ${s} not launched yet.`);return a.request(h,m)}}}),l={...i?i(r):{},launchWorker:p(async(d=[])=>(a=new n(s,[o,...d]),await a.ready(),a),"launchWorker"),launchGatewayClient:p(d=>u.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(l,{get(d,h){if(h!=="then")return h==="launchGatewayClient"?d.launchGatewayClient:h==="launchWorker"?d.launchWorker:h in d?d[h]:typeof h=="string"?(...m)=>{if(!a)throw new Error(`Thread at ${s} not launched yet.`);return a.request(h,m)}:d[h]}})}};var pe=require("net-ipc");var j=class{static{p(this,"WorkerThreadGatewayClient")}client=new pe.Client;rpc;constructor(){this.rpc=new P(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(n=>{this.client.once("ready",()=>n(this))});return await this.client.connect(),t}async request(e,t,n=!0,s){return this.rpc.makeRequest(e,t,n,s)}};var ue=require("net-ipc");var q=class{static{p(this,"WorkerThreadGatewayServer")}server=new ue.Server;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new P(n=>e.send(n),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let n=this.rpc.get(t.id);n&&n.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let n=new Promise(s=>{this.server.once("ready",()=>s(this))});return await this.server.start(),n}};var B=require("worker_threads");var ee=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=B.threadId;pid=process.pid;rpc={};parentPort=B.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=B.isMainThread;constructor(){this.init(),this.rpc=new P(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,n=!0,s){return this.rpc.makeRequest(e,t,n,s)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new q,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new j;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var te=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(n=>n.request(e,t,!0)))}async request(e,t,n,s=!0,i){return await this.thread.get(e)?.request(t,n,s,i)}};var se=class{static{p(this,"MockTelegramServer")}token;hostname;port;handlers;defaultHandler;apiRoot="";server;constructor(e){this.token=e.token,this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:p(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}_defaultResponse(e){return e==="getMe"?{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}}:e==="getUpdates"?{ok:!0,result:[]}:e==="getMyCommands"?{ok:!0,result:[]}:e==="setMyCommands"?{ok:!0,result:!0}:e==="setWebhook"?{ok:!0,result:!0}:e==="getWebhookInfo"?{ok:!0,result:{url:""}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),n=`/bot${this.token}/`;if(!t.startsWith(n))return new Response("Not found",{status:404});let s=t.slice(n.length),i=this.handlers[s]??this.defaultHandler,o=i?await i({method:s,request:e}):this._defaultResponse(s);return this._json(o)}};0&&(module.exports={BlockKeyboard,CacheExternal,Ctx,Gramstax,LabelKeyboard,LoggingHelper,MockTelegramServer,PageManager,TemplateEngine,TemplateManager,WebhookQueue,WorkerThreadExport,WorkerThreadGatewayClient,WorkerThreadGatewayServer,WorkerThreadInit,WorkerThreadLaunch,WorkerThreadPool,WorkerThreadRpc,log});
1
+ "use strict";var fe=Object.create;var B=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var p=(g,e)=>B(g,"name",{value:e,configurable:!0});var Se=(g,e)=>{for(var t in e)B(g,t,{get:e[t],enumerable:!0})},ie=(g,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ce(e))!ke.call(g,n)&&n!==t&&B(g,n,{get:()=>e[n],enumerable:!(s=Te(e,n))||s.enumerable});return g};var oe=(g,e,t)=>(t=g!=null?fe(be(g)):{},ie(e||!g||!g.__esModule?B(t,"default",{value:g,enumerable:!0}):t,g)),_e=g=>ie(B({},"__esModule",{value:!0}),g);var Me={};Se(Me,{BlockKeyboard:()=>X,CacheExternal:()=>$,Ctx:()=>K,Gramstax:()=>z,LabelKeyboard:()=>Y,LoggingHelper:()=>Q,MockTelegramServer:()=>se,PageManager:()=>x,TemplateEngine:()=>A,TemplateManager:()=>E,WebhookQueue:()=>L,WorkerThreadExport:()=>Z,WorkerThreadGatewayClient:()=>j,WorkerThreadGatewayServer:()=>N,WorkerThreadInit:()=>ee,WorkerThreadLaunch:()=>U,WorkerThreadPool:()=>te,WorkerThreadRpc:()=>R,log:()=>V});module.exports=_e(Me);var we=p(()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,"getImportMetaUrl"),f=we();var ae=require("logging-pretty");var Q=class extends ae.LoggingPretty{static{p(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,s){this.error(`[${t?`${t}:${s}`:s}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let s=this.timers.get(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}let n=(Number(process.hrtime.bigint()-s)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${n}ms)`):this.debug(`${e} (took ${n}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let s=this.timeCheck(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${s}ms)`):this.debug(`${e} (${s}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},V=new Q;var re=require("keyv"),ce=oe(require("@keyv/redis"),1);var $=class extends re.Keyv{constructor(t="memory",s,n,i){let a;t.startsWith("redis")&&(a=new ce.default(t)),t==="memory"&&(a=new Map),i?.forceStore&&(a=i.forceStore);super({store:a,namespace:n,ttl:s});this.url=t}url;static{p(this,"CacheExternal")}refreshLruCache(t){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,i=s.keys().toArray();for(let a=0;a<i.length;a++){let o=i[a];if(a==t)return;this.get(n?o.slice(n):o)}}};var J=require("timers/promises"),v=require("grammy");var K=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,s,n,i,a,o=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,m=t.map(d=>this.templateManager.getMessage(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let l=e[d],h=m[d];await this.ct.api.sendMessage(l,h,{parse_mode:"HTML",reply_markup:s,...a}),r.successCount+=1,d+1==c&&await(0,J.setTimeout)(1200)}}catch(c){if(r.failedCount+=1,o)throw{...r,err:c}}return r}async broadcastMedia(e,t,s,n,i,a,o=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,m=t.map(d=>this.templateManager.getMedia(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let l=e[d],h=m[d];if(!h)continue;let u={parse_mode:"HTML",reply_markup:s,...a};h.type=="photo"&&await this.ct.api.sendPhoto(l,h.src,{caption:h.caption,...u}),h.type=="video"&&await this.ct.api.sendVideo(l,h.src,{caption:h.caption,...u}),h.type=="audio"&&await this.ct.api.sendAudio(l,h.src,{caption:h.caption,...u}),h.type=="document"&&await this.ct.api.sendDocument(l,h.src,{caption:h.caption,...u}),h.type=="animation"&&await this.ct.api.sendAnimation(l,h.src,{caption:h.caption,...u}),h.type=="voice"&&await this.ct.api.sendVoice(l,h.src,u),h.type=="video_note"&&await this.ct.api.sendVideoNote(l,h.src,u),h.type=="sticker"&&await this.ct.api.sendSticker(l,h.src,u),h.type=="location"&&await this.ct.api.sendLocation(l,parseInt(h.latitude),parseInt(h.longitude),u),h.type=="contact"&&await this.ct.api.sendContact(l,h.phone,h.first_name,{vcard:h.vcard,...u}),r.successCount+=1,d+1==c&&await(0,J.setTimeout)(1200)}}catch(c){if(r.failedCount+=1,o)throw{...r,err:c}}return r}async reply(e,t,s,n){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...n})}async replyMedia(e,t,s,n,i){this.temp.isAnswer=!0;let a=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),o={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...o});if(e=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...o});if(e=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...o});if(e=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...o});if(e=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...o});if(e=="voice")return await this.ct.replyWithVoice(a.src,o);if(e=="video_note")return await this.ct.replyWithVideoNote(a.src,o);if(e=="sticker")return await this.ct.replyWithSticker(a.src,o);if(e=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),o);if(e=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...o})}async replyPhoto(e,t,s,n){return this.replyMedia("photo",e,t,s,n)}async replyVideo(e,t,s,n){return this.replyMedia("video",e,t,s,n)}async replyAudio(e,t,s,n){return this.replyMedia("audio",e,t,s,n)}async replyDocument(e,t,s,n){return this.replyMedia("document",e,t,s,n)}async replyAnimation(e,t,s,n){return this.replyMedia("animation",e,t,s,n)}async replyVoice(e,t,s,n){return this.replyMedia("voice",e,t,s,n)}async replyVideoNote(e,t,s,n){return this.replyMedia("video_note",e,t,s,n)}async replySticker(e,t,s,n){return this.replyMedia("sticker",e,t,s,n)}async replyLocation(e,t,s,n){return this.replyMedia("location",e,t,s,n)}async replyContact(e,t,s,n){return this.replyMedia("contact",e,t,s,n)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,s,n,i=!0){try{this.temp.isAnswer=!0;let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:e,...n})}catch(a){if(i)await this.reply(e,t,s,n);else throw a}}async editMedia(e,t,s,n,i,a,o=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return e=="voice"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,s,n,i)):e=="location"?(await this.delete(),await this.replyLocation(t,s,n,i)):e=="contact"?(await this.delete(),await this.replyContact(t,s,n,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...a})}catch(r){if(o===!0)await this.reply(t,s,n,a);else throw r}}async editPhoto(e,t,s,n,i){return await this.editMedia("photo",e,t,s,n,i)}async editVideo(e,t,s,n,i){return await this.editMedia("video",e,t,s,n,i)}async editAudio(e,t,s,n,i){return await this.editMedia("audio",e,t,s,n,i)}async editDocument(e,t,s,n,i){return await this.editMedia("document",e,t,s,n,i)}async editAnimation(e,t,s,n,i){return await this.editMedia("animation",e,t,s,n,i)}async editVoice(e,t,s,n){return await this.editMedia("voice",e,t,s,n)}async editVideoNote(e,t,s,n){return await this.editMedia("video_note",e,t,s,n)}async editSticker(e,t,s,n){return await this.editMedia("sticker",e,t,s,n)}async editLocation(e,t,s,n){return await this.editMedia("location",e,t,s,n)}async editContact(e,t,s,n){return await this.editMedia("contact",e,t,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,s){try{let n={method:e,params:t,...s},i=await this.cacheSession.set(`${this.userId}`,n);return i&&(this.temp.session=n),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let s=typeof e=="function"?{callbackData:e}:e||{},n=s.callbackData,i=this.prototype.addArgs.bind(this.prototype),a=s.name||"";return{name:a,intentText:s.intentText||a,intentCommandText:s.intentCommandText||a,intentCallbackData:a,callbackData:n?function(...r){return i(this.intentCallbackData,"colon",n(...r))}:function(){return this?.intentCallbackData},_positionArgText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,s,n){let[i,a]=s.split("-"),o=parseInt(i),r=a?parseInt(a):null,c=t.length,m=e;for(let d=0;d<c;d++){let l=t[d];if(n(l,d),r===null)(d+1)%o===0&&d<c-1&&m.row();else{let h=c-(d+1);(h===r||h>r&&(d+1)%o===0)&&m.row()}}return e}bottomKeyboardT(e="1",t,s){return this.bottomKeyboard((n,i)=>this.keyboardCols(n,i,e,a=>n.text(a)),{baseId:t??void 0,data:s})}inlineKeyboardT(e,t="1",s,n){return this.inlineKeyboard((i,a)=>this.keyboardCols(i,a,t,(o,r)=>{let c=e[r],m=typeof c=="string"?c:c.data.callbackData();i.text(o,m)}),{baseId:s??void 0,data:n})}inlineKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let o=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(o);if(!r){let c=new v.InlineKeyboard,m=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,m);return this.cacheKeyboard.set(o,d),d}return r}let n=new v.InlineKeyboard,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data);return e(n,i)}bottomKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let o=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(o);if(!r){let c=new v.Keyboard,m=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,m);return d.resized(!0),this.cacheKeyboard.set(o,d),d}return r}let n=new v.Keyboard,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),a=e(n,i);return a.resized(),a}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,s){let n=this.getSeperatorTag(t),i="";for(let a=0;a<s.length;a++){let o=s[a];o!=null&&o!==""&&(i+=n+o)}return e+i}getArgs(e="",t,s=1){if(!e)return[];let n=this.getSeperatorTag(t);return e.split(n).slice(s)}getIntent(e="",t,s=1){if(!e)return"";let n=this.getSeperatorTag(t),i=e.split(n);return s==1?i[0]:i.slice(0,s).join(n)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};var G=require("path"),D=require("fs"),de=require("module");var x=class{static{p(this,"PageManager")}static _getFile(e,t,s=0){let i=Object.values(e)[s];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return(0,G.join)(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let n=(0,de.createRequire)(e)(e);return this._getFile(n,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let s=await import(`${e}?t=${Date.now()}`);return this._getFile(s,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!(0,D.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,D.readdirSync)(e).map(n=>{let i=(0,G.join)(e,n);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!(0,D.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,D.readdirSync)(e).forEach(s=>{let n=(0,G.join)(e,s);delete require.cache[require.resolve(n)]}),!0}};var le=require("fs"),me=require("url"),P=require("path");var _=require("path"),T=require("fs"),he=require("chokidar");var A=class{static{p(this,"TemplateEngine")}static ALLOWED_BLOCKS=["base","message","keyboard","media","description","script","switch","case","default","map","div","import","space","b","i","u","s","code","pre","a","blockquote","expandable"];static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of e.matchAll(t)){let i=n[2]??"default",o=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[i]=o}return s}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(s,n,i)=>{if(!n)return"";let a="",o=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=o.exec(i))!==null;){let d=(c[1]||"").split(",").map(h=>h.trim()),l=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(h=>{a+=`case "${h}": `}),a+=`return \`${l}\`; `}let m=r.exec(i);if(m){let d=(m[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${a} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(s,n,i)=>{let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(o))a[l[1]]=l[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",m=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");m=m.replace(/\{\{([\w.]+)\}\}/g,(l,h)=>h==="e"||h.startsWith("e.")?`\${${h}}`:h==="i"?"${i}":l);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${m}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of e.matchAll(t)){let i=n[1],a=n[2],o={},r=/(\w+)="([^"]*)"/g;if(i)for(let h of i.matchAll(r))o[h[1]]=h[2];let c=o.lang||"default",m=o.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),l={type:m};o.src&&(l.src=o.src),d&&m!=="video_note"&&m!=="sticker"&&(l.caption=d),m==="location"&&(o.latitude&&(l.latitude=o.latitude),o.longitude&&(l.longitude=o.longitude),d&&(l.caption=d)),m==="contact"&&(o.phone&&(l.phone=o.phone),o.first_name&&(l.first_name=o.first_name),o.last_name&&(l.last_name=o.last_name),o.vcard&&(l.vcard=o.vcard),d&&(l.caption=d)),s[c]=l}return s}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,i]of e.matchAll(t)){let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let m of n.matchAll(o))a[m[1]]=m[2];let r=a.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,i]of e.matchAll(t)){let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(o))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",m=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=m}return s}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,i]of e.matchAll(t)){let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(o))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",m=i.trim();s[r]||(s[r]={}),s[r][c]=m}return s}static _compileToFunction(e,t){let s;t?s=e.map(a=>`\`${a}\``).join(","):s=`\`${e}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),t){let i=`return [${n}]`;return new Function("data",i)}else{let i=`return ${n}`;return new Function("data",i)}}static compileBlockMedia(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processMediaBlocks(a);n[i]={};for(let[r,c]of Object.entries(o)){let m={};for(let[d,l]of Object.entries(c)){if(d==="type"||typeof l!="string")continue;let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(l)))));m[d]=this._compileToFunction(h,!1)}n[i][r]=d=>{let l={...c};for(let[h,u]of Object.entries(m))l[h]=u(d);return l}}}return n}static compileBlockMessage(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processMessageBlocks(a);n[i]={};for(let[r,c]of Object.entries(o)){let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[i][r]=this._compileToFunction(m,!1)}}return n}static compileBlockDescription(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processDescriptionBlocks(a);n[i]={};for(let[r,c]of Object.entries(o))for(let[m,d]of Object.entries(c)){n[i][m]||(n[i][m]={});let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[i][m][r]=this._compileToFunction(l,!1)}}return n}static compileBlockKeyboards(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processKeyboardBlocks(a);n[i]={};for(let[r,c]of Object.entries(o)){n[i][r]={};for(let[m,d]of Object.entries(c)){let h=d.split(/(?<!\\),\s*/).map(u=>u.replace(/\\,/g,",").trim()).map(u=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(u))))));n[i][r][m]=this._compileToFunction(h,!0)}}}return n}static _extractBlock(e,t,s="default",n="all",i){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,o=e,r=!1;for(let c of e.matchAll(a))if((c[2]??"default")===s){o=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(s==="default"&&!c))return""}if(t){if(t==="all")return o;let c=Array.isArray(t)?t:[t],m=[];for(let l of c){let h=new RegExp(`([ \\t]*)<${l}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${l}>`,"gi");for(let u of o.matchAll(h)){let M=u[2];if(i){let b=/lang="([^"]*)"/i,w=M?.match(b);if(((w?w[1]:void 0)||"default")!==i)continue}m.push({start:u.index,content:u[0],innerContent:u[3]??""})}}m.sort((l,h)=>l.start-h.start);let d=p(l=>{let h=l.split(`
2
+ `);if(h.length<=1)return l.trim();let u=h.filter(b=>b.trim().length>0);if(u.length===0)return"";let M=u.reduce((b,w)=>{let S=w.match(/^([ \t]*)/),I=S?S[1].length:0;return I<b?I:b},1/0);return h.map(b=>b.length>=M?b.slice(M):b.trimStart()).join(`
3
+ `).trim()},"processResult");return n==="all"?m.map(h=>d(h.content)).join(`
4
+ `):m.map(h=>d(h.innerContent)).join(`
5
+ `)}return o}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:e.replace(t,(i,a,o)=>{let r={},c=/(\w+)="([^"]*)"/g;if(o)for(let h of o.matchAll(c))r[h[1]]=h[2];let m=r.src;if(!m)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(h=>h.trim()).filter(h=>h):d=r.block);let l={src:m,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(l),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(e,t,s=0,n){if(s>10)return"";let{processed:i,imports:a}=this._processImportBlocks(e),o=i;for(let r=0;r<a.length;r++){let c=a[r],m=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(n&&n.has(m))d=n.get(m);else{let h=t(c.src);d=h?this._extractBlock(h,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,t,s+1,n)),n&&n.set(m,d)}let l=d.split(`
6
+ `).map((h,u)=>u===0?h:c.indent+h).join(`
7
+ `);o=o.replace(`__IMPORT_${r}__`,l)}return o}};var E=class{static{p(this,"TemplateManager")}_map=new Map;_engine=A;_watcher=[];_pageManager=x;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:s=!1}=e;this._path=t,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!(0,T.existsSync)(t))throw new Error(`Template base path is not exists: ${t}`);if(!(0,T.statSync)(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let s=this._path[t],n=(0,he.watch)(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=n,n.on("change",this._handleFileChange.bind(this)),n.on("add",this._handleFileAdd.bind(this)),n.on("unlink",this._handleFileDelete.bind(this)),n.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(e){let t=(0,_.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=(0,_.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=(0,_.basename)(e),s=this._getKey(t);this._map.has(s)&&this._map.delete(s)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=[];for(let n=0;n<this._path.length;n++){let i=this._path[n],o=(0,T.readdirSync)(i,"utf8").filter(r=>this._isValidFile(r));for(let r of o){let c=(0,_.join)(i,r),m=this._getExtension(r),d=this._getKey(r);if(m===".html")e.set(d,(0,T.readFileSync)(c,"utf8"));else if(m===".ts"||m===".js"){let l=x.getFileSync(c);l?.template!==void 0&&(e.set(d,l.template),t.push(l))}}}let s=new Map;for(let[n,i]of e.entries())this._compile(n,i,void 0,s,e);e.clear(),s.clear();for(let n of t)n.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let s=this._path[t],n=(0,_.join)(s,e),i=this._getExtension(e),a=this._getKey(e);if(i==".html"){let o=(0,T.readFileSync)(n,"utf8");this._compile(a,o)}else if(i==".ts"||i==".js"){let o=x.getFileSync(n);o?.template!==void 0&&(this._compile(a,o.template),o.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return(0,_.extname)(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let s=(0,_.extname)(e).toLowerCase();if(s){let o=(0,_.join)(t,e);if((0,T.existsSync)(o)&&(0,T.statSync)(o).isFile()){if(s===".html")return(0,T.readFileSync)(o,"utf8");if(s===".ts"||s===".js")try{return x.getFileSync(o)?.template??null}catch{return null}}continue}let n=(0,_.join)(t,`${e}.ts`),i=(0,_.join)(t,`${e}.js`);if((0,T.existsSync)(n)&&(0,T.statSync)(n).isFile())try{return x.getFileSync(n)?.template??null}catch{}else if((0,T.existsSync)(i)&&(0,T.statSync)(i).isFile())try{return x.getFileSync(n)?.template??null}catch{}let a=(0,_.join)(t,`${e}.html`);if((0,T.existsSync)(a)&&(0,T.statSync)(a).isFile())return(0,T.readFileSync)(a,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,s,n,i){let a=this._map.get(e),o=a||{},r=!1,c=A.processImportBlocks(t,d=>i&&i.has(d)?i.get(d):this._readTemplateFile(d),0,n),m=A._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(o.media=A.compileBlockMedia(c,m),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(o.message=A.compileBlockMessage(c,m),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(o.keyboard=A.compileBlockKeyboards(c,m),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(o.description=A.compileBlockDescription(c,m),r=!0),r&&this._map.set(e,o)}getMedia(e,t="default",s="default",n){let a=this._map.get(e)?.media?.[t],o=a?.[s]||a?.default;try{if(!o)throw new Error("Media function not found, please check your template");return o(n)}catch{return{}}}getMessage(e,t="default",s="default",n){try{let a=this._map.get(e)?.message?.[t],o=a?.[s]||a?.default;if(!o)throw"";return o(n)}catch{return""}}getDescription(e,t="default",s="default",n="default",i){try{let o=this._map.get(e)?.description?.[t]?.[n],r=o?.[s]||o?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",s="default"){try{let i=this._map.get(e)?.description?.[t]?.[s];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let n=this._map.get(e)?.description?.[t];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(e,t="default",s="default",n="inline",i){try{let o=this._map.get(e)?.keyboard?.[t],r=o?.[s]?.[n]||o?.default?.[n];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=(0,_.join)(this._path[s],e);if((0,T.existsSync)(n))return(0,T.writeFileSync)(n,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};var q=require("grammy");var L=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}maxSize;static{p(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var Ie=(0,P.dirname)((()=>{try{return __filename}catch{return(0,me.fileURLToPath)(f)}})()),xe=JSON.parse((0,le.readFileSync)((0,P.join)(Ie,"../../package.json"),"utf-8")).version,z=class{static{p(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?V:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${xe}`),this.cacheSession=e.cacheSession||new $("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new E({path:[(0,P.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.token),this.bot.catch(this._onCatch),this._registerOnCallbackQueryData(),this._registerOnMessageText(),this._registerOnMessagePhoto(),this._registerOnMessageVideo(),this._registerOnMessageAudio(),this._registerOnMessageDocument(),this._registerOnMessageAnimation(),this._registerOnMessageVoice(),this._registerOnMessageVideoNote(),this._registerOnMessageSticker(),this._registerOnMessageLocation(),this._registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this._pageLoads(),process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this._runPolling();else if(e.deploy.startsWith("webhook:"))this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this._runServerless(e.deploy.split("serverless:")[1]);else if(!e.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}async stop(){await this.bot.stop(),await this.webhookServer?.stop(),this.webhookServer=void 0}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=e;this.log?.success?.(`Telegram bot deploy ${t} started: ${n} ${t=="webhook"||t=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(e){return new q.Bot(e,this.botConfig)}createCtx(e){return new K({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:p(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),s=(0,q.webhookCallback)(this.bot,"bun"),n=this.webhookQueue,i=n?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):s;let a=i?new L(n?.maxQueueSize??5e3):void 0,o=n?.workerCount??8,r=n?.perChatConcurrency??1,c=n?.blockWhenFull!==!1,m=new Map,d=new Map;this.webhookQueueInstance=a;let l=p(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),h=p(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let C=String(y),k=m.get(C)||0;if(k<r)return m.set(C,k+1),()=>this._releaseWebhookChat(C,m,d);await new Promise(ye=>{let ne=d.get(C)||[];ne.push(ye),d.set(C,ne)});let ge=(m.get(C)||0)+1;return m.set(C,ge),()=>this._releaseWebhookChat(C,m,d)},"acquireChat");if(i&&a){await this.bot.init();for(let y=0;y<o;y++)this._startWebhookWorker(a,h,l)}let u=new URL(e),M=u.pathname,b=parseInt(u.port)||3e3,w=this.log,S="/stats_queue";this.webhookServer?.stop();let I=t({port:b,async fetch(y){let{pathname:C}=new URL(y.url);if(y.method=="POST"&&C==M){if(!i||!a)return s(y);if(!c&&a.length>=(n?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let k=await y.json();return await a.enqueue(k),new Response("OK",{status:200})}catch(k){return w?.error?.(`Webhook queue error: ${String(k)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&C==S){let k=a?.getStats()||{length:0,maxSize:n?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:S,timestamp:new Date().toISOString(),maxQueueSize:n?.maxQueueSize??5e3,workerCount:o,perChatConcurrency:r,blockWhenFull:c,queue:k,activeChats:m.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&C=="/"){let k=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:k}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=I,(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let W=await this.bot.api.getMe();await this._onStart(W,"webhook",e)}_startWebhookWorker(e,t,s){p(async()=>{for(;;){let i=await e.dequeue(),a=await t(s(i));try{await this.bot.handleUpdate(i)}catch(o){this.log?.error?.(`Webhook worker error: ${String(o)}`)}finally{a()}}},"run")()}_releaseWebhookChat(e,t,s){let n=t.get(e)||0,i=Math.max(0,n-1);i===0?t.delete(e):t.set(e,i);let a=s.get(e);a&&a.length>0&&(a.shift()(),a.length===0&&s.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,s=this.webhookQueue.workerCount??8,n=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:s,perChatConcurrency:n,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=(0,q.webhookCallback)(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:s}=(0,P.parse)(t);e.data.name||(e.data.name=s),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,s){let n=e.data.name,i=e.prototype,a="handle",o="Args",r="Command",c="Caption",m="Free",d=t.routeDynamic,l=t.routeDynamicSpesific;t.all[n]=e;for(let h=0;h<t.lenListRouteStaticSession;h++){let u=t.listRouteStaticSession[h];if(typeof i[u]!="function")continue;let M=t.routeStatic[u],b=t.routeStaticIntent[u],w=t.routeStaticSession[u],S={name:n,routeName:u},I=M||b;if(I!==void 0){let F=u.includes(r),W=u.endsWith("CallbackData"),y=u.endsWith("Text"),C;if(F){let k=e.data.intentCommandText;C=k?`/${k}`:void 0}else if(W){let k=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(k=String(s),e.data.intentCallbackData=k),C=k}else y?C=e.data.intentText:C=e.data.name;C&&(I[C]=S)}if(w!==void 0){let W=`methodSession${u.replace("handle","")}`,y=i[W]?.(n);w[y]=S}if(u.startsWith("handleFree")){let F=u.replace(a,"").replace(o,"").replace(r,"").replace(c,"").replace(m,"").toLowerCase();l[F].push(S)}}i.handleFree&&d.push(n)}async executeSyncBlocksDescription(e){let t=new Map,s=e.routeStatic.handleCommandText;for(let[,n]of Object.entries(s)){let i=n.name,a=this.templateManager.getDescriptionScopes(i);for(let o of a){t.has(o)||t.set(o,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",o);for(let c of r)t.get(o).add(c)}}for(let[n,i]of t)for(let a of i){let o=[];for(let[,m]of Object.entries(s)){let d=m.name,l=this.templateManager.getDescription(d,"default",a,n);l&&o.push({command:d,description:l})}if(o.length===0)continue;let r={type:n},c=a==="default"?void 0:a;try{let m=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(m.map(h=>({command:h.command,description:h.description})).sort((h,u)=>h.command.localeCompare(u.command))),l=JSON.stringify(o.sort((h,u)=>h.command.localeCompare(u.command)));d!==l&&(await this.bot.api.setMyCommands(o,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${o.length})`))}catch(m){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(m)}`)}}}_pageLoads(){this.log?.info?.("Load pages..");let e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],s=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],n=p((o,r)=>Object.fromEntries(o.map(c=>[c,r()])),"makeObject"),i=p(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:n(e,()=>({})),routeStaticIntent:n(t,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:s,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:s.length};return x.getFileManySync(void 0).forEach(({path:o,page:r},c)=>{this._pageBuildData(r,o),this._pageSorts(r,a,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async _pageRoutes(e,t){let s,n;if(s===void 0){let a=await e.getSession();if(a){let o=a.method,r=this.pages.routeStaticSession,c=e.callbackData,m=e.msgText,d=e.msgCaption,l=c||m||d,h=t==="callbackdata",u=h?"colon":"space",M=l&&e.haveArgs(l,u)?e.getIntent(l,u,1):void 0,b=!h&&l?e.getIntent(l,"space",2):void 0;for(let w=0;w<this.pages.lenListRouteStaticSession;w++){let S=this.pages.listRouteStaticSession[w];if(S.toLowerCase().endsWith(t)){if(l){if(this.pages.routeStatic[S]?.[l])continue;let I=this.pages.routeStaticIntent[S];if(I&&(M&&I[M]||b&&I[b]))continue}n=r[S][o]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let a=e.callbackData,o=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let m=0;m<this.pages.lenListRouteStatic;m++){let d=this.pages.listRouteStatic[m];if(d.toLowerCase().endsWith(t)&&(n=c[d][a||o||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let a=this.pages.routeStaticIntent,o=t==="callbackdata",r=o?"colon":"space",c=o?e.callbackData:e.msgText||e.msgCaption,m=e.haveArgs(c,r);if(c&&m)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let l=this.pages.listRouteStaticIntent[d];if(!l.toLowerCase().endsWith(t))continue;let h=a[l];if(n=h[e.getIntent(c,r,1)],!n&&!o&&(n=h[e.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let o=await new s(e)[n.routeName]?.();return e.temp.isAnswer===!0?o:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let a=0;a<i.length;a++){let o=i[a];if(o===void 0)continue;let r=this.pages.all[o.name];r!==void 0&&typeof r.prototype[o.routeName]=="function"&&await new r(e)[o.routeName]()}for(let a=0;a<this.pages.routeDynamic.length;a++){let o=this.pages.routeDynamic[a];if(o===void 0)continue;let r=this.pages.all[o];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,s,n){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let s=this.createCtx(e);try{if(await this.hookBeforeRoute(s,t)===!1)return;await this._pageRoutes(s,t)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,t,n,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(s){await this.hookErrorPage(t,"onCallbackQueryData",s,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"contact")}_registerOnCallbackQueryData(){this.bot.on("callback_query:data",this._onCallbackQueryData.bind(this))}_registerOnMessageText(){this.bot.on("message:text",this._onMessageText.bind(this))}_registerOnMessagePhoto(){this.bot.on("message:photo",this._onMessagePhoto.bind(this))}_registerOnMessageVideo(){this.bot.on("message:video",this._onMessageVideo.bind(this))}_registerOnMessageAudio(){this.bot.on("message:audio",this._onMessageAudio.bind(this))}_registerOnMessageDocument(){this.bot.on("message:document",this._onMessageDocument.bind(this))}_registerOnMessageAnimation(){this.bot.on("message:animation",this._onMessageAnimation.bind(this))}_registerOnMessageVoice(){this.bot.on("message:voice",this._onMessageVoice.bind(this))}_registerOnMessageVideoNote(){this.bot.on("message:video_note",this._onMessageVideoNote.bind(this))}_registerOnMessageSticker(){this.bot.on("message:sticker",this._onMessageSticker.bind(this))}_registerOnMessageLocation(){this.bot.on("message:location",this._onMessageLocation.bind(this))}_registerOnMessageContact(){this.bot.on("message:contact",this._onMessageContact.bind(this))}};var X=class{static{p(this,"BlockKeyboard")}static label;static _build(e,t,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let a=p((o,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(o):o}</keyboard>`,"pro");return t?a(i[t],t):Object.keys(i).map(o=>a(i[o],o)).join(" ")}};var Y=class{static{p(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,s)=>(t[s]=this._reverse(e[s]),t),{})}};var H=require("worker_threads");var R=class{constructor(e,t){this.send=e;this.register=t}send;register;static{p(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,s=this.send,{id:n,method:i,params:a,result:o,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let m=await c.apply(this.register,a);s({id:n,result:m})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(o!==void 0){let c=t.get(n);c&&(c.resolve(o),t.delete(n))}else if(r!==void 0){let c=t.get(n);c&&(c.reject(r),t.delete(n))}}makeId(){return Math.random()}makeRequest(e,t,s=!0,n){let i=this.makeId(),a={id:i,method:e,params:t,...n};return s?new Promise((o,r)=>{this.map.set(i,{resolve:o,reject:r}),this.send(a)}):this.send(a)}};var U=class{constructor(e,t,s){this.path=e;this.argv=t;this.register=s;this.init(),s||(s=this),this.rpc=new R(this.send.bind(this),s)}path;argv;register;static{p(this,"WorkerThreadLaunch")}static isMainThread=H.isMainThread;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new H.Worker(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var Z=class g{static{p(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(n,i){if(!(typeof i!="string"||i==="then"))return async(a,...o)=>{let r=a.gatewayClients.get(e);return r||(r=await a.createGatewayClient(e)),r.request(i,o)}}}),s=p(function(n){return new Proxy({},{get(i,a){if(!(typeof a!="string"||a==="then"))return async(...o)=>{let r=n.gatewayClients.get(e);return r||(r=await n.createGatewayClient(e)),r.request(a,o)}}})},"ctor");return Object.setPrototypeOf(s,t),s}static init(e){let{WTInit:t,WTLaunch:s=U,path:n,wrap:i}=e,a=`for-${n}`;if(process.argv[2]===a)return new t,{launchGatewayClient:p(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let o,r=new Proxy({},{get(d,l){if(l!=="then")return l==="sendRequest"||l==="request"||l==="kill"||l==="send"?(...h)=>{if(!o)throw new Error(`Thread at ${n} not launched yet.`);return o[l](...h)}:(...h)=>{if(!o)throw new Error(`Thread at ${n} not launched yet.`);return o.request(l,h)}}}),m={...i?i(r):{},launchWorker:p(async(d=[])=>(o=new s(n,[a,...d]),await o.ready(),o),"launchWorker"),launchGatewayClient:p(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(m,{get(d,l){if(l!=="then")return l==="launchGatewayClient"?d.launchGatewayClient:l==="launchWorker"?d.launchWorker:l in d?d[l]:typeof l=="string"?(...h)=>{if(!o)throw new Error(`Thread at ${n} not launched yet.`);return o.request(l,h)}:d[l]}})}};var pe=require("net-ipc");var j=class{static{p(this,"WorkerThreadGatewayClient")}client=new pe.Client;rpc;constructor(){this.rpc=new R(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),t}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var ue=require("net-ipc");var N=class{static{p(this,"WorkerThreadGatewayServer")}server=new ue.Server;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new R(s=>e.send(s),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let s=this.rpc.get(t.id);s&&s.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};var O=require("worker_threads");var ee=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=O.threadId;pid=process.pid;rpc={};parentPort=O.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=O.isMainThread;constructor(){this.init(),this.rpc=new R(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new N,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new j;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var te=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(s=>s.request(e,t,!0)))}async request(e,t,s,n=!0,i){return await this.thread.get(e)?.request(t,s,n,i)}};var se=class{static{p(this,"MockTelegramServer")}botToken="";hostname;port;log;handlers;defaultHandler;apiRoot="";webhookUrl="";requests=[];updates=[];server;_nextUpdateId=1;_nextMessageId=1;constructor(e={}){this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.log=e.log===!0?V:e.log?e.log:void 0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:p(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.log?.info?.(`Mock Telegram server started: ${this.apiRoot}`),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0,this.log?.info?.("Mock Telegram server stopped")}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}lastRequest(e){if(!e)return this.requests[this.requests.length-1];for(let t=this.requests.length-1;t>=0;t--){let s=this.requests[t];if(s?.method===e)return s}}clearRequests(){this.requests.length=0}_defaultResponse(e,t){if(e==="getMe")return{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}};if(e==="getUpdates")return{ok:!0,result:[]};if(e==="getMyCommands")return{ok:!0,result:[]};if(e==="setMyCommands")return{ok:!0,result:!0};if(e==="setWebhook"){let s=this._bodyRecord(t),n=typeof s?.url=="string"?s.url:"";return this.webhookUrl=n,this.log?.info?.(`Mock Telegram webhook set: ${n}`),{ok:!0,result:!0}}return e==="getWebhookInfo"?{ok:!0,result:{url:this.webhookUrl}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),s=t.match(/^\/bot([^/]+)\/(.+)$/);if(!s)return new Response("Not found",{status:404});let n=s[1],i=s[2];if(!n||!i)return new Response("Not found",{status:404});this.botToken=n;let a=await this._readBody(e.clone());this.log?.debug?.(`Mock Telegram API request: ${i}`),this.requests.push({method:i,body:a,url:e.url,requestMethod:e.method,headers:Object.fromEntries(e.headers.entries())});let o=this.handlers[i]??this.defaultHandler,r=o?await o({method:i,request:e}):this._defaultResponse(i,a);return this._json(r)}_bodyRecord(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async _readBody(e){if(e.method==="GET"||e.method==="HEAD")return;let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let n=await e.formData();return Object.fromEntries(n.entries())}let s=await e.text();if(!s)return;try{return JSON.parse(s)}catch{return s}}catch{return}}_defaultUser(e){return{id:e?.id??1001,is_bot:e?.is_bot??!1,first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},language_code:e?.language_code??"en"}}_defaultChat(e){return{id:e?.id??1001,type:e?.type??"private",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},...e?.title?{title:e.title}:{}}}_nextIds(e){return{updateId:this._nextUpdateId++,messageId:e?.message_id??this._nextMessageId++,date:e?.date??Math.floor(Date.now()/1e3)}}_buildMessageUpdate(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return{update_id:s,message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),from:this._defaultUser(t?.user),...e}}}async _postUpdate(e,t){if(await this._waitForWebhookUrl(t?.responseTimeoutMs??1e3),!this.webhookUrl)throw new Error("Webhook URL is not set. Call setWebhook first or assign mockServer.webhookUrl.");let s=this.requests.length;this.updates.push(e),this.log?.info?.(`Mock Telegram update sent: ${this.webhookUrl}`);let n=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Webhook request failed with status ${n.status}`);let i=await this._waitForResponses(s,t?.responseTimeoutMs??1e3);return this.log?.info?.(`Mock Telegram bot responses captured: ${i.length}`),i}async _waitForWebhookUrl(e){if(this.webhookUrl||e<=0)return this.webhookUrl;let t=Date.now();for(;Date.now()-t<e&&(await new Promise(s=>setTimeout(s,5)),!this.webhookUrl););return this.webhookUrl}async _waitForResponses(e,t){if(t<=0)return this._userResponseRequests(e);if(this._userResponseRequests(e).length>0)return this._userResponseRequests(e);let s=Date.now();for(;Date.now()-s<t&&(await new Promise(n=>setTimeout(n,5)),!(this._userResponseRequests(e).length>0)););return this._userResponseRequests(e)}_userResponseRequests(e){return this.requests.slice(e).filter(t=>this._isUserResponseMethod(t.method))}_isUserResponseMethod(e){return e.startsWith("send")||e.startsWith("edit")||e.startsWith("answer")||e.startsWith("delete")||e.startsWith("copy")||e.startsWith("forward")||e==="pinChatMessage"||e==="unpinChatMessage"||e==="setMessageReaction"}async sendText(e,t){let s=e.startsWith("/")?[{offset:0,length:e.split(" ")[0]?.length??e.length,type:"bot_command"}]:void 0;return await this._postUpdate(this._buildMessageUpdate({text:e,...s?{entities:s}:{}},t),t)}async sendPhoto(e){return await this._postUpdate(this._buildMessageUpdate({photo:[{file_id:"mock-photo-file-id",file_unique_id:"mock-photo-unique-id",width:1,height:1}],...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideo(e){return await this._postUpdate(this._buildMessageUpdate({video:{file_id:"mock-video-file-id",file_unique_id:"mock-video-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAudio(e){return await this._postUpdate(this._buildMessageUpdate({audio:{file_id:"mock-audio-file-id",file_unique_id:"mock-audio-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendDocument(e){return await this._postUpdate(this._buildMessageUpdate({document:{file_id:"mock-document-file-id",file_unique_id:"mock-document-unique-id",file_name:"mock.txt"},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAnimation(e){return await this._postUpdate(this._buildMessageUpdate({animation:{file_id:"mock-animation-file-id",file_unique_id:"mock-animation-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVoice(e){return await this._postUpdate(this._buildMessageUpdate({voice:{file_id:"mock-voice-file-id",file_unique_id:"mock-voice-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideoNote(e){return await this._postUpdate(this._buildMessageUpdate({video_note:{file_id:"mock-video-note-file-id",file_unique_id:"mock-video-note-unique-id",length:1,duration:1}},e),e)}async sendSticker(e){return await this._postUpdate(this._buildMessageUpdate({sticker:{file_id:"mock-sticker-file-id",file_unique_id:"mock-sticker-unique-id",type:"regular",width:1,height:1,is_animated:!1,is_video:!1}},e),e)}async sendLocation(e){return await this._postUpdate(this._buildMessageUpdate({location:{latitude:e?.latitude??0,longitude:e?.longitude??0}},e),e)}async sendContact(e){return await this._postUpdate(this._buildMessageUpdate({contact:{phone_number:e?.phone_number??"+10000000000",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.user_id?{user_id:e.user_id}:{}}},e),e)}async sendCallbackQuery(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return await this._postUpdate({update_id:s,callback_query:{id:t?.id??`mock-callback-${s}`,from:this._defaultUser(t?.user),message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),text:t?.messageText??"Mock message"},chat_instance:"mock-chat-instance",data:e}},t)}};0&&(module.exports={BlockKeyboard,CacheExternal,Ctx,Gramstax,LabelKeyboard,LoggingHelper,MockTelegramServer,PageManager,TemplateEngine,TemplateManager,WebhookQueue,WorkerThreadExport,WorkerThreadGatewayClient,WorkerThreadGatewayServer,WorkerThreadInit,WorkerThreadLaunch,WorkerThreadPool,WorkerThreadRpc,log});
@@ -61,6 +61,7 @@ type ITMediaBlock = {
61
61
  vcard?: string;
62
62
  };
63
63
  declare class TemplateEngine {
64
+ static ALLOWED_BLOCKS: readonly ["base", "message", "keyboard", "media", "description", "script", "switch", "case", "default", "map", "div", "import", "space", "b", "i", "u", "s", "code", "pre", "a", "blockquote", "expandable"];
64
65
  static _escape(str: string): string;
65
66
  static _processScopeVariables(template: string): string;
66
67
  static _processScopeExec(template: string): string;
@@ -281,8 +282,16 @@ declare class Ctx {
281
282
  templateManager: TemplateManager;
282
283
  temp: ITTemp;
283
284
  constructor(params: ITCtxParams);
284
- broadcast(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReply, throwError?: boolean): Promise<void>;
285
- broadcastMedia(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReplyPhoto | ITOptReplyVideo | ITOptReplyAudio | ITOptReplyDocument | ITOptReplyAnimation | ITOptReplyVoice | ITOptReplyVideoNote | ITOptReplySticker | ITOptReplyLocation | ITOptReplyContact, throwError?: boolean): Promise<void>;
285
+ broadcast(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReply, throwError?: boolean): Promise<{
286
+ successCount: number;
287
+ failedCount: number;
288
+ totalCount: number;
289
+ }>;
290
+ broadcastMedia(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReplyPhoto | ITOptReplyVideo | ITOptReplyAudio | ITOptReplyDocument | ITOptReplyAnimation | ITOptReplyVoice | ITOptReplyVideoNote | ITOptReplySticker | ITOptReplyLocation | ITOptReplyContact, throwError?: boolean): Promise<{
291
+ successCount: number;
292
+ failedCount: number;
293
+ totalCount: number;
294
+ }>;
286
295
  reply(keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReply): Promise<grammy_types.Message.TextMessage>;
287
296
  replyMedia<T extends ITMediaBlock[`type`]>(type: T, keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: T extends `photo` ? ITOptReplyPhoto : T extends `video` ? ITOptReplyVideo : T extends `audio` ? ITOptReplyAudio : T extends `document` ? ITOptReplyDocument : T extends `animation` ? ITOptReplyAnimation : T extends `voice` ? ITOptReplyVoice : T extends `video_note` ? ITOptReplyVideoNote : T extends `sticker` ? ITOptReplySticker : T extends `location` ? ITOptReplyLocation : T extends `contact` ? ITOptReplyContact : undefined): Promise<grammy_types.Message.LocationMessage | grammy_types.Message.ContactMessage | grammy_types.Message.PhotoMessage | grammy_types.Message.VideoMessage | grammy_types.Message.AudioMessage | grammy_types.Message.DocumentMessage | grammy_types.Message.VoiceMessage | grammy_types.Message.VideoNoteMessage | grammy_types.Message.StickerMessage | undefined>;
288
297
  replyPhoto(keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReplyPhoto): Promise<grammy_types.Message.LocationMessage | grammy_types.Message.ContactMessage | grammy_types.Message.PhotoMessage | grammy_types.Message.VideoMessage | grammy_types.Message.AudioMessage | grammy_types.Message.DocumentMessage | grammy_types.Message.VoiceMessage | grammy_types.Message.VideoNoteMessage | grammy_types.Message.StickerMessage | undefined>;
@@ -555,6 +564,7 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
555
564
  };
556
565
  handlerBotUpdate: any;
557
566
  constructor(params: ITGramstaxParams);
567
+ stop(): Promise<void>;
558
568
  _onCatch(error: BotError<Context>): void;
559
569
  hookBeforeStart(): void;
560
570
  hookAfterStart(): void;
@@ -1077,30 +1087,109 @@ type ITMockTelegramHandler = (payload: {
1077
1087
  method: string;
1078
1088
  request: Request;
1079
1089
  }) => Promise<ITMockTelegramJson> | ITMockTelegramJson;
1090
+ type ITMockTelegramRequestRecord = {
1091
+ method: string;
1092
+ body: any;
1093
+ url: string;
1094
+ requestMethod: string;
1095
+ headers: Record<string, string>;
1096
+ };
1097
+ type ITMockTelegramUser = {
1098
+ id?: number;
1099
+ is_bot?: boolean;
1100
+ first_name?: string;
1101
+ last_name?: string;
1102
+ username?: string;
1103
+ language_code?: string;
1104
+ };
1105
+ type ITMockTelegramChat = {
1106
+ id?: number;
1107
+ type?: `private` | `group` | `supergroup` | `channel`;
1108
+ first_name?: string;
1109
+ last_name?: string;
1110
+ username?: string;
1111
+ title?: string;
1112
+ };
1113
+ type ITMockTelegramUpdateOptions = {
1114
+ user?: ITMockTelegramUser;
1115
+ chat?: ITMockTelegramChat;
1116
+ date?: number;
1117
+ message_id?: number;
1118
+ responseTimeoutMs?: number;
1119
+ };
1120
+ type ITMockTelegramMediaOptions = ITMockTelegramUpdateOptions & {
1121
+ caption?: string;
1122
+ };
1123
+ type ITMockTelegramLocationOptions = ITMockTelegramUpdateOptions & {
1124
+ latitude?: number;
1125
+ longitude?: number;
1126
+ };
1127
+ type ITMockTelegramContactOptions = ITMockTelegramUpdateOptions & {
1128
+ phone_number?: string;
1129
+ first_name?: string;
1130
+ last_name?: string;
1131
+ user_id?: number;
1132
+ };
1133
+ type ITMockTelegramCallbackQueryOptions = ITMockTelegramUpdateOptions & {
1134
+ id?: string;
1135
+ messageText?: string;
1136
+ };
1137
+ type ITMockTelegramLog = Pick<LoggingHelper, `info` | `debug` | `success` | `error`>;
1080
1138
  type ITMockTelegramServerOptions = {
1081
- token: string;
1082
1139
  hostname?: string;
1083
1140
  port?: number;
1141
+ log?: ITMockTelegramLog | boolean | null;
1084
1142
  handlers?: Record<string, ITMockTelegramHandler>;
1085
1143
  defaultHandler?: ITMockTelegramHandler;
1086
1144
  };
1087
1145
  declare class MockTelegramServer {
1088
- token: string;
1146
+ botToken: string;
1089
1147
  hostname: string;
1090
1148
  port: number;
1149
+ log?: ITMockTelegramLog;
1091
1150
  handlers: Record<string, ITMockTelegramHandler>;
1092
1151
  defaultHandler?: ITMockTelegramHandler;
1093
1152
  apiRoot: string;
1153
+ webhookUrl: string;
1154
+ requests: ITMockTelegramRequestRecord[];
1155
+ updates: Record<string, unknown>[];
1094
1156
  server?: {
1095
1157
  port?: number;
1096
1158
  stop: () => void;
1097
1159
  };
1098
- constructor(options: ITMockTelegramServerOptions);
1160
+ private _nextUpdateId;
1161
+ private _nextMessageId;
1162
+ constructor(options?: ITMockTelegramServerOptions);
1099
1163
  start(): Promise<string>;
1100
1164
  stop(): Promise<void>;
1101
1165
  private _json;
1166
+ lastRequest(method?: string): ITMockTelegramRequestRecord | undefined;
1167
+ clearRequests(): void;
1102
1168
  private _defaultResponse;
1103
1169
  private _handleRequest;
1170
+ private _bodyRecord;
1171
+ private _readBody;
1172
+ private _defaultUser;
1173
+ private _defaultChat;
1174
+ private _nextIds;
1175
+ private _buildMessageUpdate;
1176
+ private _postUpdate;
1177
+ private _waitForWebhookUrl;
1178
+ private _waitForResponses;
1179
+ private _userResponseRequests;
1180
+ private _isUserResponseMethod;
1181
+ sendText(text: string, options?: ITMockTelegramUpdateOptions): Promise<ITMockTelegramRequestRecord[]>;
1182
+ sendPhoto(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1183
+ sendVideo(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1184
+ sendAudio(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1185
+ sendDocument(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1186
+ sendAnimation(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1187
+ sendVoice(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1188
+ sendVideoNote(options?: ITMockTelegramUpdateOptions): Promise<ITMockTelegramRequestRecord[]>;
1189
+ sendSticker(options?: ITMockTelegramUpdateOptions): Promise<ITMockTelegramRequestRecord[]>;
1190
+ sendLocation(options?: ITMockTelegramLocationOptions): Promise<ITMockTelegramRequestRecord[]>;
1191
+ sendContact(options?: ITMockTelegramContactOptions): Promise<ITMockTelegramRequestRecord[]>;
1192
+ sendCallbackQuery(data: string, options?: ITMockTelegramCallbackQueryOptions): Promise<ITMockTelegramRequestRecord[]>;
1104
1193
  }
1105
1194
 
1106
- export { BlockKeyboard, CacheExternal, Ctx, Gramstax, type ITBottomKb, type ITBottomKbParams, type ITBuildDataOptions, type ITCacheRpc, type ITCompiledTemplate, type ITCt, type ITCtxParams, type ITData, type ITGramstaxParams, type ITInBoKb, type ITInlineKb, type ITInlineKbParams, type ITKbCols, type ITKbDest, type ITMapRpc, type ITMediaBlock, type ITMockTelegramHandler, type ITMockTelegramJson, type ITMockTelegramServerOptions, type ITOptEdit, type ITOptEditMedia1, type ITOptEditMedia2, type ITOptReply, type ITOptReplyAnimation, type ITOptReplyAudio, type ITOptReplyContact, type ITOptReplyDocument, type ITOptReplyLocation, type ITOptReplyPhoto, type ITOptReplySticker, type ITOptReplyVideo, type ITOptReplyVideoNote, type ITOptReplyVoice, type ITPageData, type ITReplyAction, type ITTemp, type ITTemplateOptions, type ITWebhookQueueConfig, LabelKeyboard, LoggingHelper, MockTelegramServer, PageManager, TemplateEngine, TemplateManager, WebhookQueue, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, WorkerThreadRpc, log };
1195
+ export { BlockKeyboard, CacheExternal, Ctx, Gramstax, type ITBottomKb, type ITBottomKbParams, type ITBuildDataOptions, type ITCacheRpc, type ITCompiledTemplate, type ITCt, type ITCtxParams, type ITData, type ITGramstaxParams, type ITInBoKb, type ITInlineKb, type ITInlineKbParams, type ITKbCols, type ITKbDest, type ITMapRpc, type ITMediaBlock, type ITMockTelegramCallbackQueryOptions, type ITMockTelegramChat, type ITMockTelegramContactOptions, type ITMockTelegramHandler, type ITMockTelegramJson, type ITMockTelegramLocationOptions, type ITMockTelegramMediaOptions, type ITMockTelegramRequestRecord, type ITMockTelegramServerOptions, type ITMockTelegramUpdateOptions, type ITMockTelegramUser, type ITOptEdit, type ITOptEditMedia1, type ITOptEditMedia2, type ITOptReply, type ITOptReplyAnimation, type ITOptReplyAudio, type ITOptReplyContact, type ITOptReplyDocument, type ITOptReplyLocation, type ITOptReplyPhoto, type ITOptReplySticker, type ITOptReplyVideo, type ITOptReplyVideoNote, type ITOptReplyVoice, type ITPageData, type ITReplyAction, type ITTemp, type ITTemplateOptions, type ITWebhookQueueConfig, LabelKeyboard, LoggingHelper, MockTelegramServer, PageManager, TemplateEngine, TemplateManager, WebhookQueue, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, WorkerThreadRpc, log };
@@ -61,6 +61,7 @@ type ITMediaBlock = {
61
61
  vcard?: string;
62
62
  };
63
63
  declare class TemplateEngine {
64
+ static ALLOWED_BLOCKS: readonly ["base", "message", "keyboard", "media", "description", "script", "switch", "case", "default", "map", "div", "import", "space", "b", "i", "u", "s", "code", "pre", "a", "blockquote", "expandable"];
64
65
  static _escape(str: string): string;
65
66
  static _processScopeVariables(template: string): string;
66
67
  static _processScopeExec(template: string): string;
@@ -281,8 +282,16 @@ declare class Ctx {
281
282
  templateManager: TemplateManager;
282
283
  temp: ITTemp;
283
284
  constructor(params: ITCtxParams);
284
- broadcast(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReply, throwError?: boolean): Promise<void>;
285
- broadcastMedia(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReplyPhoto | ITOptReplyVideo | ITOptReplyAudio | ITOptReplyDocument | ITOptReplyAnimation | ITOptReplyVoice | ITOptReplyVideoNote | ITOptReplySticker | ITOptReplyLocation | ITOptReplyContact, throwError?: boolean): Promise<void>;
285
+ broadcast(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReply, throwError?: boolean): Promise<{
286
+ successCount: number;
287
+ failedCount: number;
288
+ totalCount: number;
289
+ }>;
290
+ broadcastMedia(ids: number[], languageCode: string[], keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReplyPhoto | ITOptReplyVideo | ITOptReplyAudio | ITOptReplyDocument | ITOptReplyAnimation | ITOptReplyVoice | ITOptReplyVideoNote | ITOptReplySticker | ITOptReplyLocation | ITOptReplyContact, throwError?: boolean): Promise<{
291
+ successCount: number;
292
+ failedCount: number;
293
+ totalCount: number;
294
+ }>;
286
295
  reply(keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReply): Promise<grammy_types.Message.TextMessage>;
287
296
  replyMedia<T extends ITMediaBlock[`type`]>(type: T, keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: T extends `photo` ? ITOptReplyPhoto : T extends `video` ? ITOptReplyVideo : T extends `audio` ? ITOptReplyAudio : T extends `document` ? ITOptReplyDocument : T extends `animation` ? ITOptReplyAnimation : T extends `voice` ? ITOptReplyVoice : T extends `video_note` ? ITOptReplyVideoNote : T extends `sticker` ? ITOptReplySticker : T extends `location` ? ITOptReplyLocation : T extends `contact` ? ITOptReplyContact : undefined): Promise<grammy_types.Message.LocationMessage | grammy_types.Message.ContactMessage | grammy_types.Message.PhotoMessage | grammy_types.Message.VideoMessage | grammy_types.Message.AudioMessage | grammy_types.Message.DocumentMessage | grammy_types.Message.VoiceMessage | grammy_types.Message.VideoNoteMessage | grammy_types.Message.StickerMessage | undefined>;
288
297
  replyPhoto(keyboard?: ITInBoKb, data?: ITData, baseId?: string, options?: ITOptReplyPhoto): Promise<grammy_types.Message.LocationMessage | grammy_types.Message.ContactMessage | grammy_types.Message.PhotoMessage | grammy_types.Message.VideoMessage | grammy_types.Message.AudioMessage | grammy_types.Message.DocumentMessage | grammy_types.Message.VoiceMessage | grammy_types.Message.VideoNoteMessage | grammy_types.Message.StickerMessage | undefined>;
@@ -555,6 +564,7 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
555
564
  };
556
565
  handlerBotUpdate: any;
557
566
  constructor(params: ITGramstaxParams);
567
+ stop(): Promise<void>;
558
568
  _onCatch(error: BotError<Context>): void;
559
569
  hookBeforeStart(): void;
560
570
  hookAfterStart(): void;
@@ -1077,30 +1087,109 @@ type ITMockTelegramHandler = (payload: {
1077
1087
  method: string;
1078
1088
  request: Request;
1079
1089
  }) => Promise<ITMockTelegramJson> | ITMockTelegramJson;
1090
+ type ITMockTelegramRequestRecord = {
1091
+ method: string;
1092
+ body: any;
1093
+ url: string;
1094
+ requestMethod: string;
1095
+ headers: Record<string, string>;
1096
+ };
1097
+ type ITMockTelegramUser = {
1098
+ id?: number;
1099
+ is_bot?: boolean;
1100
+ first_name?: string;
1101
+ last_name?: string;
1102
+ username?: string;
1103
+ language_code?: string;
1104
+ };
1105
+ type ITMockTelegramChat = {
1106
+ id?: number;
1107
+ type?: `private` | `group` | `supergroup` | `channel`;
1108
+ first_name?: string;
1109
+ last_name?: string;
1110
+ username?: string;
1111
+ title?: string;
1112
+ };
1113
+ type ITMockTelegramUpdateOptions = {
1114
+ user?: ITMockTelegramUser;
1115
+ chat?: ITMockTelegramChat;
1116
+ date?: number;
1117
+ message_id?: number;
1118
+ responseTimeoutMs?: number;
1119
+ };
1120
+ type ITMockTelegramMediaOptions = ITMockTelegramUpdateOptions & {
1121
+ caption?: string;
1122
+ };
1123
+ type ITMockTelegramLocationOptions = ITMockTelegramUpdateOptions & {
1124
+ latitude?: number;
1125
+ longitude?: number;
1126
+ };
1127
+ type ITMockTelegramContactOptions = ITMockTelegramUpdateOptions & {
1128
+ phone_number?: string;
1129
+ first_name?: string;
1130
+ last_name?: string;
1131
+ user_id?: number;
1132
+ };
1133
+ type ITMockTelegramCallbackQueryOptions = ITMockTelegramUpdateOptions & {
1134
+ id?: string;
1135
+ messageText?: string;
1136
+ };
1137
+ type ITMockTelegramLog = Pick<LoggingHelper, `info` | `debug` | `success` | `error`>;
1080
1138
  type ITMockTelegramServerOptions = {
1081
- token: string;
1082
1139
  hostname?: string;
1083
1140
  port?: number;
1141
+ log?: ITMockTelegramLog | boolean | null;
1084
1142
  handlers?: Record<string, ITMockTelegramHandler>;
1085
1143
  defaultHandler?: ITMockTelegramHandler;
1086
1144
  };
1087
1145
  declare class MockTelegramServer {
1088
- token: string;
1146
+ botToken: string;
1089
1147
  hostname: string;
1090
1148
  port: number;
1149
+ log?: ITMockTelegramLog;
1091
1150
  handlers: Record<string, ITMockTelegramHandler>;
1092
1151
  defaultHandler?: ITMockTelegramHandler;
1093
1152
  apiRoot: string;
1153
+ webhookUrl: string;
1154
+ requests: ITMockTelegramRequestRecord[];
1155
+ updates: Record<string, unknown>[];
1094
1156
  server?: {
1095
1157
  port?: number;
1096
1158
  stop: () => void;
1097
1159
  };
1098
- constructor(options: ITMockTelegramServerOptions);
1160
+ private _nextUpdateId;
1161
+ private _nextMessageId;
1162
+ constructor(options?: ITMockTelegramServerOptions);
1099
1163
  start(): Promise<string>;
1100
1164
  stop(): Promise<void>;
1101
1165
  private _json;
1166
+ lastRequest(method?: string): ITMockTelegramRequestRecord | undefined;
1167
+ clearRequests(): void;
1102
1168
  private _defaultResponse;
1103
1169
  private _handleRequest;
1170
+ private _bodyRecord;
1171
+ private _readBody;
1172
+ private _defaultUser;
1173
+ private _defaultChat;
1174
+ private _nextIds;
1175
+ private _buildMessageUpdate;
1176
+ private _postUpdate;
1177
+ private _waitForWebhookUrl;
1178
+ private _waitForResponses;
1179
+ private _userResponseRequests;
1180
+ private _isUserResponseMethod;
1181
+ sendText(text: string, options?: ITMockTelegramUpdateOptions): Promise<ITMockTelegramRequestRecord[]>;
1182
+ sendPhoto(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1183
+ sendVideo(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1184
+ sendAudio(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1185
+ sendDocument(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1186
+ sendAnimation(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1187
+ sendVoice(options?: ITMockTelegramMediaOptions): Promise<ITMockTelegramRequestRecord[]>;
1188
+ sendVideoNote(options?: ITMockTelegramUpdateOptions): Promise<ITMockTelegramRequestRecord[]>;
1189
+ sendSticker(options?: ITMockTelegramUpdateOptions): Promise<ITMockTelegramRequestRecord[]>;
1190
+ sendLocation(options?: ITMockTelegramLocationOptions): Promise<ITMockTelegramRequestRecord[]>;
1191
+ sendContact(options?: ITMockTelegramContactOptions): Promise<ITMockTelegramRequestRecord[]>;
1192
+ sendCallbackQuery(data: string, options?: ITMockTelegramCallbackQueryOptions): Promise<ITMockTelegramRequestRecord[]>;
1104
1193
  }
1105
1194
 
1106
- export { BlockKeyboard, CacheExternal, Ctx, Gramstax, type ITBottomKb, type ITBottomKbParams, type ITBuildDataOptions, type ITCacheRpc, type ITCompiledTemplate, type ITCt, type ITCtxParams, type ITData, type ITGramstaxParams, type ITInBoKb, type ITInlineKb, type ITInlineKbParams, type ITKbCols, type ITKbDest, type ITMapRpc, type ITMediaBlock, type ITMockTelegramHandler, type ITMockTelegramJson, type ITMockTelegramServerOptions, type ITOptEdit, type ITOptEditMedia1, type ITOptEditMedia2, type ITOptReply, type ITOptReplyAnimation, type ITOptReplyAudio, type ITOptReplyContact, type ITOptReplyDocument, type ITOptReplyLocation, type ITOptReplyPhoto, type ITOptReplySticker, type ITOptReplyVideo, type ITOptReplyVideoNote, type ITOptReplyVoice, type ITPageData, type ITReplyAction, type ITTemp, type ITTemplateOptions, type ITWebhookQueueConfig, LabelKeyboard, LoggingHelper, MockTelegramServer, PageManager, TemplateEngine, TemplateManager, WebhookQueue, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, WorkerThreadRpc, log };
1195
+ export { BlockKeyboard, CacheExternal, Ctx, Gramstax, type ITBottomKb, type ITBottomKbParams, type ITBuildDataOptions, type ITCacheRpc, type ITCompiledTemplate, type ITCt, type ITCtxParams, type ITData, type ITGramstaxParams, type ITInBoKb, type ITInlineKb, type ITInlineKbParams, type ITKbCols, type ITKbDest, type ITMapRpc, type ITMediaBlock, type ITMockTelegramCallbackQueryOptions, type ITMockTelegramChat, type ITMockTelegramContactOptions, type ITMockTelegramHandler, type ITMockTelegramJson, type ITMockTelegramLocationOptions, type ITMockTelegramMediaOptions, type ITMockTelegramRequestRecord, type ITMockTelegramServerOptions, type ITMockTelegramUpdateOptions, type ITMockTelegramUser, type ITOptEdit, type ITOptEditMedia1, type ITOptEditMedia2, type ITOptReply, type ITOptReplyAnimation, type ITOptReplyAudio, type ITOptReplyContact, type ITOptReplyDocument, type ITOptReplyLocation, type ITOptReplyPhoto, type ITOptReplySticker, type ITOptReplyVideo, type ITOptReplyVideoNote, type ITOptReplyVoice, type ITPageData, type ITReplyAction, type ITTemp, type ITTemplateOptions, type ITWebhookQueueConfig, LabelKeyboard, LoggingHelper, MockTelegramServer, PageManager, TemplateEngine, TemplateManager, WebhookQueue, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, WorkerThreadRpc, log };
package/dist/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var de=Object.defineProperty;var p=(g,e)=>de(g,"name",{value:e,configurable:!0}),N=(g=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(g,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):g)(function(g){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});import Ve from"path";import{fileURLToPath as le}from"url";var me=p(()=>le(import.meta.url),"getFilename");var f=me();import{LoggingPretty as pe}from"logging-pretty";var j=class extends pe{static{p(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,s){this.error(`[${t?`${t}:${s}`:s}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let s=this.timers.get(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}let n=(Number(process.hrtime.bigint()-s)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${n}ms)`):this.debug(`${e} (took ${n}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let s=this.timeCheck(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${s}ms)`):this.debug(`${e} (${s}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},H=new j;import{Keyv as ue}from"keyv";import ge from"@keyv/redis";var F=class extends ue{constructor(t="memory",s,n,i){let o;t.startsWith("redis")&&(o=new ge(t)),t==="memory"&&(o=new Map),i?.forceStore&&(o=i.forceStore);super({store:o,namespace:n,ttl:s});this.url=t}static{p(this,"CacheExternal")}refreshLruCache(t){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,i=s.keys().toArray();for(let o=0;o<i.length;o++){let a=i[o];if(o==t)return;this.get(n?a.slice(n):a)}}};import{setTimeout as z}from"timers/promises";import{InlineKeyboard as J,Keyboard as U}from"grammy";var B=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,s,n,i,o,a=!1){try{this.temp.isAnswer=!0;let r=30,c=t.map(l=>this.templateManager.getMessage(this.data.name,i,l,n));for(let l=0;l<e.length;l++){let d=e[l],h=c[l];await this.ct.api.sendMessage(d,h,{parse_mode:"HTML",reply_markup:s,...o}),l+1==r&&await z(1200)}}catch(r){if(a)throw r}}async broadcastMedia(e,t,s,n,i,o,a=!1){try{this.temp.isAnswer=!0;let r=30,c=t.map(l=>this.templateManager.getMedia(this.data.name,i,l,n));for(let l=0;l<e.length;l++){let d=e[l],h=c[l];if(!h)continue;let m={parse_mode:"HTML",reply_markup:s,...o};h.type=="photo"&&await this.ct.api.sendPhoto(d,h.src,{caption:h.caption,...m}),h.type=="video"&&await this.ct.api.sendVideo(d,h.src,{caption:h.caption,...m}),h.type=="audio"&&await this.ct.api.sendAudio(d,h.src,{caption:h.caption,...m}),h.type=="document"&&await this.ct.api.sendDocument(d,h.src,{caption:h.caption,...m}),h.type=="animation"&&await this.ct.api.sendAnimation(d,h.src,{caption:h.caption,...m}),h.type=="voice"&&await this.ct.api.sendVoice(d,h.src,m),h.type=="video_note"&&await this.ct.api.sendVideoNote(d,h.src,m),h.type=="sticker"&&await this.ct.api.sendSticker(d,h.src,m),h.type=="location"&&await this.ct.api.sendLocation(d,parseInt(h.latitude),parseInt(h.longitude),m),h.type=="contact"&&await this.ct.api.sendContact(d,h.phone,h.first_name,{vcard:h.vcard,...m}),l+1==r&&await z(1200)}}catch(r){if(a)throw r}}async reply(e,t,s,n){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...n})}async replyMedia(e,t,s,n,i){this.temp.isAnswer=!0;let o=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),a={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(o.src,{caption:o.caption,...a});if(e=="video")return await this.ct.replyWithVideo(o.src,{caption:o.caption,...a});if(e=="audio")return await this.ct.replyWithAudio(o.src,{caption:o.caption,...a});if(e=="document")return await this.ct.replyWithDocument(o.src,{caption:o.caption,...a});if(e=="animation")return await this.ct.replyWithAnimation(o.src,{caption:o.caption,...a});if(e=="voice")return await this.ct.replyWithVoice(o.src,a);if(e=="video_note")return await this.ct.replyWithVideoNote(o.src,a);if(e=="sticker")return await this.ct.replyWithSticker(o.src,a);if(e=="location")return await this.ct.replyWithLocation(parseInt(o.latitude),parseInt(o.longitude),a);if(e=="contact")return await this.ct.replyWithContact(o.phone,o.first_name,{vcard:o.vcard,...a})}async replyPhoto(e,t,s,n){return this.replyMedia("photo",e,t,s,n)}async replyVideo(e,t,s,n){return this.replyMedia("video",e,t,s,n)}async replyAudio(e,t,s,n){return this.replyMedia("audio",e,t,s,n)}async replyDocument(e,t,s,n){return this.replyMedia("document",e,t,s,n)}async replyAnimation(e,t,s,n){return this.replyMedia("animation",e,t,s,n)}async replyVoice(e,t,s,n){return this.replyMedia("voice",e,t,s,n)}async replyVideoNote(e,t,s,n){return this.replyMedia("video_note",e,t,s,n)}async replySticker(e,t,s,n){return this.replyMedia("sticker",e,t,s,n)}async replyLocation(e,t,s,n){return this.replyMedia("location",e,t,s,n)}async replyContact(e,t,s,n){return this.replyMedia("contact",e,t,s,n)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,s,n,i=!0){try{this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.editMessageText(o,{parse_mode:"HTML",reply_markup:e,...n})}catch(o){if(i)await this.reply(e,t,s,n);else throw o}}async editMedia(e,t,s,n,i,o,a=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return e=="voice"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,s,n,i)):e=="location"?(await this.delete(),await this.replyLocation(t,s,n,i)):e=="contact"?(await this.delete(),await this.replyContact(t,s,n,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...o})}catch(r){if(a===!0)await this.reply(t,s,n,o);else throw r}}async editPhoto(e,t,s,n,i){return await this.editMedia("photo",e,t,s,n,i)}async editVideo(e,t,s,n,i){return await this.editMedia("video",e,t,s,n,i)}async editAudio(e,t,s,n,i){return await this.editMedia("audio",e,t,s,n,i)}async editDocument(e,t,s,n,i){return await this.editMedia("document",e,t,s,n,i)}async editAnimation(e,t,s,n,i){return await this.editMedia("animation",e,t,s,n,i)}async editVoice(e,t,s,n){return await this.editMedia("voice",e,t,s,n)}async editVideoNote(e,t,s,n){return await this.editMedia("video_note",e,t,s,n)}async editSticker(e,t,s,n){return await this.editMedia("sticker",e,t,s,n)}async editLocation(e,t,s,n){return await this.editMedia("location",e,t,s,n)}async editContact(e,t,s,n){return await this.editMedia("contact",e,t,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,s){try{let n={method:e,params:t,...s},i=await this.cacheSession.set(`${this.userId}`,n);return i&&(this.temp.session=n),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let s=typeof e=="function"?{callbackData:e}:e||{},n=s.callbackData,i=this.prototype.addArgs.bind(this.prototype),o=s.name||"";return{name:o,intentText:s.intentText||o,intentCommandText:s.intentCommandText||o,intentCallbackData:o,callbackData:n?function(...r){return i(this.intentCallbackData,"colon",n(...r))}:function(){return this?.intentCallbackData},_positionArgText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,s,n){let[i,o]=s.split("-"),a=parseInt(i),r=o?parseInt(o):null,c=t.length,l=e;for(let d=0;d<c;d++){let h=t[d];if(n(h,d),r===null)(d+1)%a===0&&d<c-1&&l.row();else{let m=c-(d+1);(m===r||m>r&&(d+1)%a===0)&&l.row()}}return e}bottomKeyboardT(e="1",t,s){return this.bottomKeyboard((n,i)=>this.keyboardCols(n,i,e,o=>n.text(o)),{baseId:t??void 0,data:s})}inlineKeyboardT(e,t="1",s,n){return this.inlineKeyboard((i,o)=>this.keyboardCols(i,o,t,(a,r)=>{let c=e[r],l=typeof c=="string"?c:c.data.callbackData();i.text(a,l)}),{baseId:s??void 0,data:n})}inlineKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(a);if(!r){let c=new J,l=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,l);return this.cacheKeyboard.set(a,d),d}return r}let n=new J,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data);return e(n,i)}bottomKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(a);if(!r){let c=new U,l=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,l);return d.resized(!0),this.cacheKeyboard.set(a,d),d}return r}let n=new U,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),o=e(n,i);return o.resized(),o}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,s){let n=this.getSeperatorTag(t),i="";for(let o=0;o<s.length;o++){let a=s[o];a!=null&&a!==""&&(i+=n+a)}return e+i}getArgs(e="",t,s=1){if(!e)return[];let n=this.getSeperatorTag(t);return e.split(n).slice(s)}getIntent(e="",t,s=1){if(!e)return"";let n=this.getSeperatorTag(t),i=e.split(n);return s==1?i[0]:i.slice(0,s).join(n)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};import{join as q}from"path";import{existsSync as X,readdirSync as Y}from"fs";import{createRequire as ye}from"module";var _=class{static{p(this,"PageManager")}static _getFile(e,t,s=0){let i=Object.values(e)[s];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return q(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let n=ye(e)(e);return this._getFile(n,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let s=await import(`${e}?t=${Date.now()}`);return this._getFile(s,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).map(n=>{let i=q(e,n);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).forEach(s=>{let n=q(e,s);delete N.cache[N.resolve(n)]}),!0}};import{readFileSync as be}from"fs";import{fileURLToPath as Se}from"url";import{dirname as ke,join as se,parse as we}from"path";import{basename as Q,join as R,extname as Z}from"path";import{readdirSync as fe,readFileSync as V,existsSync as D,statSync as O,writeFileSync as Ce}from"fs";import{watch as Te}from"chokidar";var A=class{static{p(this,"TemplateEngine")}static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of e.matchAll(t)){let i=n[2]??"default",a=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[i]=a}return s}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(s,n,i)=>{if(!n)return"";let o="",a=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=a.exec(i))!==null;){let d=(c[1]||"").split(",").map(m=>m.trim()),h=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(m=>{o+=`case "${m}": `}),o+=`return \`${h}\`; `}let l=r.exec(i);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();o+=`default: return \`${d}\`; `}else o+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${o} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(s,n,i)=>{let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(a))o[h[1]]=h[2];let r=o.src;if(!r)return"";let c=o.join??"\\n",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(h,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":h);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${l}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of e.matchAll(t)){let i=n[1],o=n[2],a={},r=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(r))a[m[1]]=m[2];let c=a.lang||"default",l=a.type,d=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),h={type:l};a.src&&(h.src=a.src),d&&l!=="video_note"&&l!=="sticker"&&(h.caption=d),l==="location"&&(a.latitude&&(h.latitude=a.latitude),a.longitude&&(h.longitude=a.longitude),d&&(h.caption=d)),l==="contact"&&(a.phone&&(h.phone=a.phone),a.first_name&&(h.first_name=a.first_name),a.last_name&&(h.last_name=a.last_name),a.vcard&&(h.vcard=a.vcard),d&&(h.caption=d)),s[c]=h}return s}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(a))o[l[1]]=l[2];let r=o.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.scope||"default",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.type==="bottom"?"bottom":"inline",l=i.trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _compileToFunction(e,t){let s;t?s=e.map(o=>`\`${o}\``).join(","):s=`\`${e}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),t){let i=`return [${n}]`;return new Function("data",i)}else{let i=`return ${n}`;return new Function("data",i)}}static compileBlockMedia(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMediaBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let l={};for(let[d,h]of Object.entries(c)){if(d==="type"||typeof h!="string")continue;let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(h)))));l[d]=this._compileToFunction(m,!1)}n[i][r]=d=>{let h={...c};for(let[m,u]of Object.entries(l))h[m]=u(d);return h}}}return n}static compileBlockMessage(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMessageBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[i][r]=this._compileToFunction(l,!1)}}return n}static compileBlockDescription(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processDescriptionBlocks(o);n[i]={};for(let[r,c]of Object.entries(a))for(let[l,d]of Object.entries(c)){n[i][l]||(n[i][l]={});let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[i][l][r]=this._compileToFunction(h,!1)}}return n}static compileBlockKeyboards(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processKeyboardBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){n[i][r]={};for(let[l,d]of Object.entries(c)){let m=d.split(/(?<!\\),\s*/).map(u=>u.replace(/\\,/g,",").trim()).map(u=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(u))))));n[i][r][l]=this._compileToFunction(m,!0)}}}return n}static _extractBlock(e,t,s="default",n="all",i){let o=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,a=e,r=!1;for(let c of e.matchAll(o))if((c[2]??"default")===s){a=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(s==="default"&&!c))return""}if(t){if(t==="all")return a;let c=Array.isArray(t)?t:[t],l=[];for(let h of c){let m=new RegExp(`([ \\t]*)<${h}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${h}>`,"gi");for(let u of a.matchAll(m)){let I=u[2];if(i){let T=/lang="([^"]*)"/i,w=I?.match(T);if(((w?w[1]:void 0)||"default")!==i)continue}l.push({start:u.index,content:u[0],innerContent:u[3]??""})}}l.sort((h,m)=>h.start-m.start);let d=p(h=>{let m=h.split(`
2
- `);if(m.length<=1)return h.trim();let u=m.filter(T=>T.trim().length>0);if(u.length===0)return"";let I=u.reduce((T,w)=>{let k=w.match(/^([ \t]*)/),x=k?k[1].length:0;return x<T?x:T},1/0);return m.map(T=>T.length>=I?T.slice(I):T.trimStart()).join(`
3
- `).trim()},"processResult");return n==="all"?l.map(m=>d(m.content)).join(`
4
- `):l.map(m=>d(m.innerContent)).join(`
5
- `)}return a}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:e.replace(t,(i,o,a)=>{let r={},c=/(\w+)="([^"]*)"/g;if(a)for(let m of a.matchAll(c))r[m[1]]=m[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(m=>m.trim()).filter(m=>m):d=r.block);let h={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:o||""};return s.push(h),`${o}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(e,t,s=0,n){if(s>10)return"";let{processed:i,imports:o}=this._processImportBlocks(e),a=i;for(let r=0;r<o.length;r++){let c=o[r],l=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(n&&n.has(l))d=n.get(l);else{let m=t(c.src);d=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,t,s+1,n)),n&&n.set(l,d)}let h=d.split(`
6
- `).map((m,u)=>u===0?m:c.indent+m).join(`
7
- `);a=a.replace(`__IMPORT_${r}__`,h)}return a}};var W=class{static{p(this,"TemplateManager")}_map=new Map;_engine=A;_watcher=[];_pageManager=_;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:s=!1}=e;this._path=t,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!D(t))throw new Error(`Template base path is not exists: ${t}`);if(!O(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let s=this._path[t],n=Te(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=n,n.on("change",this._handleFileChange.bind(this)),n.on("add",this._handleFileAdd.bind(this)),n.on("unlink",this._handleFileDelete.bind(this)),n.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=Q(e),s=this._getKey(t);this._map.has(s)&&this._map.delete(s)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=[];for(let n=0;n<this._path.length;n++){let i=this._path[n],a=fe(i,"utf8").filter(r=>this._isValidFile(r));for(let r of a){let c=R(i,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")e.set(d,V(c,"utf8"));else if(l===".ts"||l===".js"){let h=_.getFileSync(c);h?.template!==void 0&&(e.set(d,h.template),t.push(h))}}}let s=new Map;for(let[n,i]of e.entries())this._compile(n,i,void 0,s,e);e.clear(),s.clear();for(let n of t)n.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let s=this._path[t],n=R(s,e),i=this._getExtension(e),o=this._getKey(e);if(i==".html"){let a=V(n,"utf8");this._compile(o,a)}else if(i==".ts"||i==".js"){let a=_.getFileSync(n);a?.template!==void 0&&(this._compile(o,a.template),a.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return Z(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let s=Z(e).toLowerCase();if(s){let a=R(t,e);if(D(a)&&O(a).isFile()){if(s===".html")return V(a,"utf8");if(s===".ts"||s===".js")try{return _.getFileSync(a)?.template??null}catch{return null}}continue}let n=R(t,`${e}.ts`),i=R(t,`${e}.js`);if(D(n)&&O(n).isFile())try{return _.getFileSync(n)?.template??null}catch{}else if(D(i)&&O(i).isFile())try{return _.getFileSync(n)?.template??null}catch{}let o=R(t,`${e}.html`);if(D(o)&&O(o).isFile())return V(o,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,s,n,i){let o=this._map.get(e),a=o||{},r=!1,c=A.processImportBlocks(t,d=>i&&i.has(d)?i.get(d):this._readTemplateFile(d),0,n),l=A._processBaseBlocks(c);(s===void 0||s?.media===!1||o?.media===void 0)&&(a.media=A.compileBlockMedia(c,l),r=!0),(s===void 0||s?.message===!1||o?.message===void 0)&&(a.message=A.compileBlockMessage(c,l),r=!0),(s===void 0||s?.keyboard===!1||o?.keyboard===void 0)&&(a.keyboard=A.compileBlockKeyboards(c,l),r=!0),(s===void 0||s?.description===!1||o?.description===void 0)&&(a.description=A.compileBlockDescription(c,l),r=!0),r&&this._map.set(e,a)}getMedia(e,t="default",s="default",n){let o=this._map.get(e)?.media?.[t],a=o?.[s]||o?.default;try{if(!a)throw new Error("Media function not found, please check your template");return a(n)}catch{return{}}}getMessage(e,t="default",s="default",n){try{let o=this._map.get(e)?.message?.[t],a=o?.[s]||o?.default;if(!a)throw"";return a(n)}catch{return""}}getDescription(e,t="default",s="default",n="default",i){try{let a=this._map.get(e)?.description?.[t]?.[n],r=a?.[s]||a?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",s="default"){try{let i=this._map.get(e)?.description?.[t]?.[s];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let n=this._map.get(e)?.description?.[t];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(e,t="default",s="default",n="inline",i){try{let a=this._map.get(e)?.keyboard?.[t],r=a?.[s]?.[n]||a?.default?.[n];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=R(this._path[s],e);if(D(n))return Ce(n,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};import{Bot as Ie,webhookCallback as ee}from"grammy";var K=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}static{p(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var xe=ke((()=>{try{return f}catch{return Se(import.meta.url)}})()),_e=JSON.parse(be(se(xe,"../../package.json"),"utf-8")).version,te=class{static{p(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?H:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${_e}`),this.cacheSession=e.cacheSession||new F("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new W({path:[se(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.token),this.bot.catch(this._onCatch),this._registerOnCallbackQueryData(),this._registerOnMessageText(),this._registerOnMessagePhoto(),this._registerOnMessageVideo(),this._registerOnMessageAudio(),this._registerOnMessageDocument(),this._registerOnMessageAnimation(),this._registerOnMessageVoice(),this._registerOnMessageVideoNote(),this._registerOnMessageSticker(),this._registerOnMessageLocation(),this._registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this._pageLoads(),process.once("SIGINT",()=>this.bot.stop()),process.once("SIGTERM",()=>this.bot.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this._runPolling();else if(e.deploy.startsWith("webhook:"))this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this._runServerless(e.deploy.split("serverless:")[1]);else if(!e.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=e;this.log?.success?.(`Telegram bot polling started: ${n} ${t=="webhook"||t=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(e){return new Ie(e,this.botConfig)}createCtx(e){return new B({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:p(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),s=ee(this.bot,"bun"),n=this.webhookQueue,i=n?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):s;let o=i?new K(n?.maxQueueSize??5e3):void 0,a=n?.workerCount??8,r=n?.perChatConcurrency??1,c=n?.blockWhenFull!==!1,l=new Map,d=new Map;this.webhookQueueInstance=o;let h=p(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),m=p(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let S=String(y),b=l.get(S)||0;if(b<r)return l.set(S,b+1),()=>this._releaseWebhookChat(S,l,d);await new Promise(he=>{let G=d.get(S)||[];G.push(he),d.set(S,G)});let P=(l.get(S)||0)+1;return l.set(S,P),()=>this._releaseWebhookChat(S,l,d)},"acquireChat");if(i&&o){await this.bot.init();for(let y=0;y<a;y++)this._startWebhookWorker(o,m,h)}let u=new URL(e).pathname,I=this.log,T="/stats_queue";this.webhookServer?.stop();let w=t({async fetch(y){let{pathname:S}=new URL(y.url);if(y.method=="POST"&&S==u){if(!i||!o)return s(y);if(!c&&o.length>=(n?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let b=await y.json();return await o.enqueue(b),new Response("OK",{status:200})}catch(b){return I?.error?.(`Webhook queue error: ${String(b)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&S==T){let b=o?.getStats()||{length:0,maxSize:n?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:T,timestamp:new Date().toISOString(),maxQueueSize:n?.maxQueueSize??5e3,workerCount:a,perChatConcurrency:r,blockWhenFull:c,queue:b,activeChats:l.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&S=="/"){let b=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:b}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=w;let k=p(()=>{this.webhookServer?.stop(),this.webhookServer=void 0},"stopServer");process.once("SIGINT",k),process.once("SIGTERM",k),(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let v=await this.bot.api.getMe();await this._onStart(v,"webhook",e)}_startWebhookWorker(e,t,s){p(async()=>{for(;;){let i=await e.dequeue(),o=await t(s(i));try{await this.bot.handleUpdate(i)}catch(a){this.log?.error?.(`Webhook worker error: ${String(a)}`)}finally{o()}}},"run")()}_releaseWebhookChat(e,t,s){let n=t.get(e)||0,i=Math.max(0,n-1);i===0?t.delete(e):t.set(e,i);let o=s.get(e);o&&o.length>0&&(o.shift()(),o.length===0&&s.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,s=this.webhookQueue.workerCount??8,n=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:s,perChatConcurrency:n,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=ee(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:s}=we(t);e.data.name||(e.data.name=s),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,s){let n=e.data.name,i=e.prototype,o="handle",a="Args",r="Command",c="Caption",l="Free",d=t.routeDynamic,h=t.routeDynamicSpesific;t.all[n]=e;for(let m=0;m<t.lenListRouteStaticSession;m++){let u=t.listRouteStaticSession[m];if(typeof i[u]!="function")continue;let I=t.routeStatic[u],T=t.routeStaticIntent[u],w=t.routeStaticSession[u],k={name:n,routeName:u},x=I||T;if(x!==void 0){let v=u.includes(r),y=u.endsWith("CallbackData"),S=u.endsWith("Text"),b;if(v){let P=e.data.intentCommandText;b=P?`/${P}`:void 0}else if(y){let P=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(P=String(s),e.data.intentCallbackData=P),b=P}else S?b=e.data.intentText:b=e.data.name;b&&(x[b]=k)}if(w!==void 0){let y=`methodSession${u.replace("handle","")}`,S=i[y]?.(n);w[S]=k}if(u.startsWith("handleFree")){let v=u.replace(o,"").replace(a,"").replace(r,"").replace(c,"").replace(l,"").toLowerCase();h[v].push(k)}}i.handleFree&&d.push(n)}async executeSyncBlocksDescription(e){let t=new Map,s=e.routeStatic.handleCommandText;for(let[,n]of Object.entries(s)){let i=n.name,o=this.templateManager.getDescriptionScopes(i);for(let a of o){t.has(a)||t.set(a,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",a);for(let c of r)t.get(a).add(c)}}for(let[n,i]of t)for(let o of i){let a=[];for(let[,l]of Object.entries(s)){let d=l.name,h=this.templateManager.getDescription(d,"default",o,n);h&&a.push({command:d,description:h})}if(a.length===0)continue;let r={type:n},c=o==="default"?void 0:o;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(m=>({command:m.command,description:m.description})).sort((m,u)=>m.command.localeCompare(u.command))),h=JSON.stringify(a.sort((m,u)=>m.command.localeCompare(u.command)));d!==h&&(await this.bot.api.setMyCommands(a,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${a.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}_pageLoads(){this.log?.info?.("Load pages..");let e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],s=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],n=p((a,r)=>Object.fromEntries(a.map(c=>[c,r()])),"makeObject"),i=p(()=>[],"initDynamicSpesific"),o={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:n(e,()=>({})),routeStaticIntent:n(t,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:s,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:s.length};return _.getFileManySync(void 0).forEach(({path:a,page:r},c)=>{this._pageBuildData(r,a),this._pageSorts(r,o,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(o.all).length})`),o}async _pageRoutes(e,t){let s,n;if(s===void 0){let o=await e.getSession();if(o){let a=o.method,r=this.pages.routeStaticSession,c=e.callbackData,l=e.msgText,d=e.msgCaption,h=c||l||d,m=t==="callbackdata",u=m?"colon":"space",I=h&&e.haveArgs(h,u)?e.getIntent(h,u,1):void 0,T=!m&&h?e.getIntent(h,"space",2):void 0;for(let w=0;w<this.pages.lenListRouteStaticSession;w++){let k=this.pages.listRouteStaticSession[w];if(k.toLowerCase().endsWith(t)){if(h){if(this.pages.routeStatic[k]?.[h])continue;let x=this.pages.routeStaticIntent[k];if(x&&(I&&x[I]||T&&x[T]))continue}n=r[k][a]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let o=e.callbackData,a=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.toLowerCase().endsWith(t)&&(n=c[d][o||a||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let o=this.pages.routeStaticIntent,a=t==="callbackdata",r=a?"colon":"space",c=a?e.callbackData:e.msgText||e.msgCaption,l=e.haveArgs(c,r);if(c&&l)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let h=this.pages.listRouteStaticIntent[d];if(!h.toLowerCase().endsWith(t))continue;let m=o[h];if(n=m[e.getIntent(c,r,1)],!n&&!a&&(n=m[e.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let a=await new s(e)[n.routeName]?.();return e.temp.isAnswer===!0?a:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let o=0;o<i.length;o++){let a=i[o];if(a===void 0)continue;let r=this.pages.all[a.name];r!==void 0&&typeof r.prototype[a.routeName]=="function"&&await new r(e)[a.routeName]()}for(let o=0;o<this.pages.routeDynamic.length;o++){let a=this.pages.routeDynamic[o];if(a===void 0)continue;let r=this.pages.all[a];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,s,n){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let s=this.createCtx(e);try{if(await this.hookBeforeRoute(s,t)===!1)return;await this._pageRoutes(s,t)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,t,n,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(s){await this.hookErrorPage(t,"onCallbackQueryData",s,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"contact")}_registerOnCallbackQueryData(){this.bot.on("callback_query:data",this._onCallbackQueryData.bind(this))}_registerOnMessageText(){this.bot.on("message:text",this._onMessageText.bind(this))}_registerOnMessagePhoto(){this.bot.on("message:photo",this._onMessagePhoto.bind(this))}_registerOnMessageVideo(){this.bot.on("message:video",this._onMessageVideo.bind(this))}_registerOnMessageAudio(){this.bot.on("message:audio",this._onMessageAudio.bind(this))}_registerOnMessageDocument(){this.bot.on("message:document",this._onMessageDocument.bind(this))}_registerOnMessageAnimation(){this.bot.on("message:animation",this._onMessageAnimation.bind(this))}_registerOnMessageVoice(){this.bot.on("message:voice",this._onMessageVoice.bind(this))}_registerOnMessageVideoNote(){this.bot.on("message:video_note",this._onMessageVideoNote.bind(this))}_registerOnMessageSticker(){this.bot.on("message:sticker",this._onMessageSticker.bind(this))}_registerOnMessageLocation(){this.bot.on("message:location",this._onMessageLocation.bind(this))}_registerOnMessageContact(){this.bot.on("message:contact",this._onMessageContact.bind(this))}};var ne=class{static{p(this,"BlockKeyboard")}static label;static _build(e,t,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let o=p((a,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(a):a}</keyboard>`,"pro");return t?o(i[t],t):Object.keys(i).map(a=>o(i[a],a)).join(" ")}};var ie=class{static{p(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,s)=>(t[s]=this._reverse(e[s]),t),{})}};import{isMainThread as Ae,Worker as Me}from"worker_threads";var M=class{constructor(e,t){this.send=e;this.register=t}static{p(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,s=this.send,{id:n,method:i,params:o,result:a,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let l=await c.apply(this.register,o);s({id:n,result:l})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(a!==void 0){let c=t.get(n);c&&(c.resolve(a),t.delete(n))}else if(r!==void 0){let c=t.get(n);c&&(c.reject(r),t.delete(n))}}makeId(){return Math.random()}makeRequest(e,t,s=!0,n){let i=this.makeId(),o={id:i,method:e,params:t,...n};return s?new Promise((a,r)=>{this.map.set(i,{resolve:a,reject:r}),this.send(o)}):this.send(o)}};var $=class{constructor(e,t,s){this.path=e;this.argv=t;this.register=s;this.init(),s||(s=this),this.rpc=new M(this.send.bind(this),s)}static{p(this,"WorkerThreadLaunch")}static isMainThread=Ae;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new Me(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var oe=class g{static{p(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(n,i){if(!(typeof i!="string"||i==="then"))return async(o,...a)=>{let r=o.gatewayClients.get(e);return r||(r=await o.createGatewayClient(e)),r.request(i,a)}}}),s=p(function(n){return new Proxy({},{get(i,o){if(!(typeof o!="string"||o==="then"))return async(...a)=>{let r=n.gatewayClients.get(e);return r||(r=await n.createGatewayClient(e)),r.request(o,a)}}})},"ctor");return Object.setPrototypeOf(s,t),s}static init(e){let{WTInit:t,WTLaunch:s=$,path:n,wrap:i}=e,o=`for-${n}`;if(process.argv[2]===o)return new t,{launchGatewayClient:p(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let a,r=new Proxy({},{get(d,h){if(h!=="then")return h==="sendRequest"||h==="request"||h==="kill"||h==="send"?(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a[h](...m)}:(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(h,m)}}}),l={...i?i(r):{},launchWorker:p(async(d=[])=>(a=new s(n,[o,...d]),await a.ready(),a),"launchWorker"),launchGatewayClient:p(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(l,{get(d,h){if(h!=="then")return h==="launchGatewayClient"?d.launchGatewayClient:h==="launchWorker"?d.launchWorker:h in d?d[h]:typeof h=="string"?(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(h,m)}:d[h]}})}};import{Client as Pe}from"net-ipc";var E=class{static{p(this,"WorkerThreadGatewayClient")}client=new Pe;rpc;constructor(){this.rpc=new M(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),t}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};import{Server as Re}from"net-ipc";var L=class{static{p(this,"WorkerThreadGatewayServer")}server=new Re;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new M(s=>e.send(s),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let s=this.rpc.get(t.id);s&&s.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};import{parentPort as ve,threadId as De,isMainThread as Oe}from"worker_threads";var ae=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=De;pid=process.pid;rpc={};parentPort=ve;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=Oe;constructor(){this.init(),this.rpc=new M(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new L,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new E;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var re=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(s=>s.request(e,t,!0)))}async request(e,t,s,n=!0,i){return await this.thread.get(e)?.request(t,s,n,i)}};var ce=class{static{p(this,"MockTelegramServer")}token;hostname;port;handlers;defaultHandler;apiRoot="";server;constructor(e){this.token=e.token,this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:p(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}_defaultResponse(e){return e==="getMe"?{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}}:e==="getUpdates"?{ok:!0,result:[]}:e==="getMyCommands"?{ok:!0,result:[]}:e==="setMyCommands"?{ok:!0,result:!0}:e==="setWebhook"?{ok:!0,result:!0}:e==="getWebhookInfo"?{ok:!0,result:{url:""}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),s=`/bot${this.token}/`;if(!t.startsWith(s))return new Response("Not found",{status:404});let n=t.slice(s.length),i=this.handlers[n]??this.defaultHandler,o=i?await i({method:n,request:e}):this._defaultResponse(n);return this._json(o)}};export{ne as BlockKeyboard,F as CacheExternal,B as Ctx,te as Gramstax,ie as LabelKeyboard,j as LoggingHelper,ce as MockTelegramServer,_ as PageManager,A as TemplateEngine,W as TemplateManager,K as WebhookQueue,oe as WorkerThreadExport,E as WorkerThreadGatewayClient,L as WorkerThreadGatewayServer,ae as WorkerThreadInit,$ as WorkerThreadLaunch,re as WorkerThreadPool,M as WorkerThreadRpc,H as log};
1
+ var le=Object.defineProperty;var p=(g,e)=>le(g,"name",{value:e,configurable:!0}),U=(g=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(g,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):g)(function(g){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});import Ve from"path";import{fileURLToPath as me}from"url";var pe=p(()=>me(import.meta.url),"getFilename");var f=pe();import{LoggingPretty as ue}from"logging-pretty";var j=class extends ue{static{p(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,s){this.error(`[${t?`${t}:${s}`:s}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let s=this.timers.get(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}let n=(Number(process.hrtime.bigint()-s)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${n}ms)`):this.debug(`${e} (took ${n}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let s=this.timeCheck(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${s}ms)`):this.debug(`${e} (${s}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},F=new j;import{Keyv as ge}from"keyv";import ye from"@keyv/redis";var W=class extends ge{constructor(t="memory",s,n,i){let a;t.startsWith("redis")&&(a=new ye(t)),t==="memory"&&(a=new Map),i?.forceStore&&(a=i.forceStore);super({store:a,namespace:n,ttl:s});this.url=t}url;static{p(this,"CacheExternal")}refreshLruCache(t){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,i=s.keys().toArray();for(let a=0;a<i.length;a++){let o=i[a];if(a==t)return;this.get(n?o.slice(n):o)}}};import{setTimeout as H}from"timers/promises";import{InlineKeyboard as J,Keyboard as z}from"grammy";var B=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,s,n,i,a,o=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,m=t.map(d=>this.templateManager.getMessage(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let l=e[d],h=m[d];await this.ct.api.sendMessage(l,h,{parse_mode:"HTML",reply_markup:s,...a}),r.successCount+=1,d+1==c&&await H(1200)}}catch(c){if(r.failedCount+=1,o)throw{...r,err:c}}return r}async broadcastMedia(e,t,s,n,i,a,o=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,m=t.map(d=>this.templateManager.getMedia(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let l=e[d],h=m[d];if(!h)continue;let u={parse_mode:"HTML",reply_markup:s,...a};h.type=="photo"&&await this.ct.api.sendPhoto(l,h.src,{caption:h.caption,...u}),h.type=="video"&&await this.ct.api.sendVideo(l,h.src,{caption:h.caption,...u}),h.type=="audio"&&await this.ct.api.sendAudio(l,h.src,{caption:h.caption,...u}),h.type=="document"&&await this.ct.api.sendDocument(l,h.src,{caption:h.caption,...u}),h.type=="animation"&&await this.ct.api.sendAnimation(l,h.src,{caption:h.caption,...u}),h.type=="voice"&&await this.ct.api.sendVoice(l,h.src,u),h.type=="video_note"&&await this.ct.api.sendVideoNote(l,h.src,u),h.type=="sticker"&&await this.ct.api.sendSticker(l,h.src,u),h.type=="location"&&await this.ct.api.sendLocation(l,parseInt(h.latitude),parseInt(h.longitude),u),h.type=="contact"&&await this.ct.api.sendContact(l,h.phone,h.first_name,{vcard:h.vcard,...u}),r.successCount+=1,d+1==c&&await H(1200)}}catch(c){if(r.failedCount+=1,o)throw{...r,err:c}}return r}async reply(e,t,s,n){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...n})}async replyMedia(e,t,s,n,i){this.temp.isAnswer=!0;let a=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),o={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...o});if(e=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...o});if(e=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...o});if(e=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...o});if(e=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...o});if(e=="voice")return await this.ct.replyWithVoice(a.src,o);if(e=="video_note")return await this.ct.replyWithVideoNote(a.src,o);if(e=="sticker")return await this.ct.replyWithSticker(a.src,o);if(e=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),o);if(e=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...o})}async replyPhoto(e,t,s,n){return this.replyMedia("photo",e,t,s,n)}async replyVideo(e,t,s,n){return this.replyMedia("video",e,t,s,n)}async replyAudio(e,t,s,n){return this.replyMedia("audio",e,t,s,n)}async replyDocument(e,t,s,n){return this.replyMedia("document",e,t,s,n)}async replyAnimation(e,t,s,n){return this.replyMedia("animation",e,t,s,n)}async replyVoice(e,t,s,n){return this.replyMedia("voice",e,t,s,n)}async replyVideoNote(e,t,s,n){return this.replyMedia("video_note",e,t,s,n)}async replySticker(e,t,s,n){return this.replyMedia("sticker",e,t,s,n)}async replyLocation(e,t,s,n){return this.replyMedia("location",e,t,s,n)}async replyContact(e,t,s,n){return this.replyMedia("contact",e,t,s,n)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,s,n,i=!0){try{this.temp.isAnswer=!0;let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:e,...n})}catch(a){if(i)await this.reply(e,t,s,n);else throw a}}async editMedia(e,t,s,n,i,a,o=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return e=="voice"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,s,n,i)):e=="location"?(await this.delete(),await this.replyLocation(t,s,n,i)):e=="contact"?(await this.delete(),await this.replyContact(t,s,n,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...a})}catch(r){if(o===!0)await this.reply(t,s,n,a);else throw r}}async editPhoto(e,t,s,n,i){return await this.editMedia("photo",e,t,s,n,i)}async editVideo(e,t,s,n,i){return await this.editMedia("video",e,t,s,n,i)}async editAudio(e,t,s,n,i){return await this.editMedia("audio",e,t,s,n,i)}async editDocument(e,t,s,n,i){return await this.editMedia("document",e,t,s,n,i)}async editAnimation(e,t,s,n,i){return await this.editMedia("animation",e,t,s,n,i)}async editVoice(e,t,s,n){return await this.editMedia("voice",e,t,s,n)}async editVideoNote(e,t,s,n){return await this.editMedia("video_note",e,t,s,n)}async editSticker(e,t,s,n){return await this.editMedia("sticker",e,t,s,n)}async editLocation(e,t,s,n){return await this.editMedia("location",e,t,s,n)}async editContact(e,t,s,n){return await this.editMedia("contact",e,t,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,s){try{let n={method:e,params:t,...s},i=await this.cacheSession.set(`${this.userId}`,n);return i&&(this.temp.session=n),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let s=typeof e=="function"?{callbackData:e}:e||{},n=s.callbackData,i=this.prototype.addArgs.bind(this.prototype),a=s.name||"";return{name:a,intentText:s.intentText||a,intentCommandText:s.intentCommandText||a,intentCallbackData:a,callbackData:n?function(...r){return i(this.intentCallbackData,"colon",n(...r))}:function(){return this?.intentCallbackData},_positionArgText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,s,n){let[i,a]=s.split("-"),o=parseInt(i),r=a?parseInt(a):null,c=t.length,m=e;for(let d=0;d<c;d++){let l=t[d];if(n(l,d),r===null)(d+1)%o===0&&d<c-1&&m.row();else{let h=c-(d+1);(h===r||h>r&&(d+1)%o===0)&&m.row()}}return e}bottomKeyboardT(e="1",t,s){return this.bottomKeyboard((n,i)=>this.keyboardCols(n,i,e,a=>n.text(a)),{baseId:t??void 0,data:s})}inlineKeyboardT(e,t="1",s,n){return this.inlineKeyboard((i,a)=>this.keyboardCols(i,a,t,(o,r)=>{let c=e[r],m=typeof c=="string"?c:c.data.callbackData();i.text(o,m)}),{baseId:s??void 0,data:n})}inlineKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let o=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(o);if(!r){let c=new J,m=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,m);return this.cacheKeyboard.set(o,d),d}return r}let n=new J,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data);return e(n,i)}bottomKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let o=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(o);if(!r){let c=new z,m=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,m);return d.resized(!0),this.cacheKeyboard.set(o,d),d}return r}let n=new z,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),a=e(n,i);return a.resized(),a}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,s){let n=this.getSeperatorTag(t),i="";for(let a=0;a<s.length;a++){let o=s[a];o!=null&&o!==""&&(i+=n+o)}return e+i}getArgs(e="",t,s=1){if(!e)return[];let n=this.getSeperatorTag(t);return e.split(n).slice(s)}getIntent(e="",t,s=1){if(!e)return"";let n=this.getSeperatorTag(t),i=e.split(n);return s==1?i[0]:i.slice(0,s).join(n)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};import{join as N}from"path";import{existsSync as X,readdirSync as Y}from"fs";import{createRequire as fe}from"module";var x=class{static{p(this,"PageManager")}static _getFile(e,t,s=0){let i=Object.values(e)[s];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return N(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let n=fe(e)(e);return this._getFile(n,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let s=await import(`${e}?t=${Date.now()}`);return this._getFile(s,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).map(n=>{let i=N(e,n);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).forEach(s=>{let n=N(e,s);delete U.cache[U.resolve(n)]}),!0}};import{readFileSync as ke}from"fs";import{fileURLToPath as Se}from"url";import{dirname as _e,join as se,parse as we}from"path";import{basename as Q,join as R,extname as Z}from"path";import{readdirSync as Te,readFileSync as V,existsSync as P,statSync as O,writeFileSync as Ce}from"fs";import{watch as be}from"chokidar";var M=class{static{p(this,"TemplateEngine")}static ALLOWED_BLOCKS=["base","message","keyboard","media","description","script","switch","case","default","map","div","import","space","b","i","u","s","code","pre","a","blockquote","expandable"];static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of e.matchAll(t)){let i=n[2]??"default",o=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[i]=o}return s}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(s,n,i)=>{if(!n)return"";let a="",o=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=o.exec(i))!==null;){let d=(c[1]||"").split(",").map(h=>h.trim()),l=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(h=>{a+=`case "${h}": `}),a+=`return \`${l}\`; `}let m=r.exec(i);if(m){let d=(m[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${a} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(s,n,i)=>{let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(o))a[l[1]]=l[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",m=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");m=m.replace(/\{\{([\w.]+)\}\}/g,(l,h)=>h==="e"||h.startsWith("e.")?`\${${h}}`:h==="i"?"${i}":l);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${m}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of e.matchAll(t)){let i=n[1],a=n[2],o={},r=/(\w+)="([^"]*)"/g;if(i)for(let h of i.matchAll(r))o[h[1]]=h[2];let c=o.lang||"default",m=o.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),l={type:m};o.src&&(l.src=o.src),d&&m!=="video_note"&&m!=="sticker"&&(l.caption=d),m==="location"&&(o.latitude&&(l.latitude=o.latitude),o.longitude&&(l.longitude=o.longitude),d&&(l.caption=d)),m==="contact"&&(o.phone&&(l.phone=o.phone),o.first_name&&(l.first_name=o.first_name),o.last_name&&(l.last_name=o.last_name),o.vcard&&(l.vcard=o.vcard),d&&(l.caption=d)),s[c]=l}return s}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,i]of e.matchAll(t)){let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let m of n.matchAll(o))a[m[1]]=m[2];let r=a.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,i]of e.matchAll(t)){let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(o))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",m=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=m}return s}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,i]of e.matchAll(t)){let a={},o=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(o))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",m=i.trim();s[r]||(s[r]={}),s[r][c]=m}return s}static _compileToFunction(e,t){let s;t?s=e.map(a=>`\`${a}\``).join(","):s=`\`${e}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),t){let i=`return [${n}]`;return new Function("data",i)}else{let i=`return ${n}`;return new Function("data",i)}}static compileBlockMedia(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processMediaBlocks(a);n[i]={};for(let[r,c]of Object.entries(o)){let m={};for(let[d,l]of Object.entries(c)){if(d==="type"||typeof l!="string")continue;let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(l)))));m[d]=this._compileToFunction(h,!1)}n[i][r]=d=>{let l={...c};for(let[h,u]of Object.entries(m))l[h]=u(d);return l}}}return n}static compileBlockMessage(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processMessageBlocks(a);n[i]={};for(let[r,c]of Object.entries(o)){let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[i][r]=this._compileToFunction(m,!1)}}return n}static compileBlockDescription(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processDescriptionBlocks(a);n[i]={};for(let[r,c]of Object.entries(o))for(let[m,d]of Object.entries(c)){n[i][m]||(n[i][m]={});let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[i][m][r]=this._compileToFunction(l,!1)}}return n}static compileBlockKeyboards(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,a]of Object.entries(s)){let o=this._processKeyboardBlocks(a);n[i]={};for(let[r,c]of Object.entries(o)){n[i][r]={};for(let[m,d]of Object.entries(c)){let h=d.split(/(?<!\\),\s*/).map(u=>u.replace(/\\,/g,",").trim()).map(u=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(u))))));n[i][r][m]=this._compileToFunction(h,!0)}}}return n}static _extractBlock(e,t,s="default",n="all",i){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,o=e,r=!1;for(let c of e.matchAll(a))if((c[2]??"default")===s){o=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(s==="default"&&!c))return""}if(t){if(t==="all")return o;let c=Array.isArray(t)?t:[t],m=[];for(let l of c){let h=new RegExp(`([ \\t]*)<${l}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${l}>`,"gi");for(let u of o.matchAll(h)){let I=u[2];if(i){let b=/lang="([^"]*)"/i,_=I?.match(b);if(((_?_[1]:void 0)||"default")!==i)continue}m.push({start:u.index,content:u[0],innerContent:u[3]??""})}}m.sort((l,h)=>l.start-h.start);let d=p(l=>{let h=l.split(`
2
+ `);if(h.length<=1)return l.trim();let u=h.filter(b=>b.trim().length>0);if(u.length===0)return"";let I=u.reduce((b,_)=>{let S=_.match(/^([ \t]*)/),w=S?S[1].length:0;return w<b?w:b},1/0);return h.map(b=>b.length>=I?b.slice(I):b.trimStart()).join(`
3
+ `).trim()},"processResult");return n==="all"?m.map(h=>d(h.content)).join(`
4
+ `):m.map(h=>d(h.innerContent)).join(`
5
+ `)}return o}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:e.replace(t,(i,a,o)=>{let r={},c=/(\w+)="([^"]*)"/g;if(o)for(let h of o.matchAll(c))r[h[1]]=h[2];let m=r.src;if(!m)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(h=>h.trim()).filter(h=>h):d=r.block);let l={src:m,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(l),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(e,t,s=0,n){if(s>10)return"";let{processed:i,imports:a}=this._processImportBlocks(e),o=i;for(let r=0;r<a.length;r++){let c=a[r],m=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(n&&n.has(m))d=n.get(m);else{let h=t(c.src);d=h?this._extractBlock(h,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,t,s+1,n)),n&&n.set(m,d)}let l=d.split(`
6
+ `).map((h,u)=>u===0?h:c.indent+h).join(`
7
+ `);o=o.replace(`__IMPORT_${r}__`,l)}return o}};var $=class{static{p(this,"TemplateManager")}_map=new Map;_engine=M;_watcher=[];_pageManager=x;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:s=!1}=e;this._path=t,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!P(t))throw new Error(`Template base path is not exists: ${t}`);if(!O(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let s=this._path[t],n=be(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=n,n.on("change",this._handleFileChange.bind(this)),n.on("add",this._handleFileAdd.bind(this)),n.on("unlink",this._handleFileDelete.bind(this)),n.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=Q(e),s=this._getKey(t);this._map.has(s)&&this._map.delete(s)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=[];for(let n=0;n<this._path.length;n++){let i=this._path[n],o=Te(i,"utf8").filter(r=>this._isValidFile(r));for(let r of o){let c=R(i,r),m=this._getExtension(r),d=this._getKey(r);if(m===".html")e.set(d,V(c,"utf8"));else if(m===".ts"||m===".js"){let l=x.getFileSync(c);l?.template!==void 0&&(e.set(d,l.template),t.push(l))}}}let s=new Map;for(let[n,i]of e.entries())this._compile(n,i,void 0,s,e);e.clear(),s.clear();for(let n of t)n.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let s=this._path[t],n=R(s,e),i=this._getExtension(e),a=this._getKey(e);if(i==".html"){let o=V(n,"utf8");this._compile(a,o)}else if(i==".ts"||i==".js"){let o=x.getFileSync(n);o?.template!==void 0&&(this._compile(a,o.template),o.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return Z(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let s=Z(e).toLowerCase();if(s){let o=R(t,e);if(P(o)&&O(o).isFile()){if(s===".html")return V(o,"utf8");if(s===".ts"||s===".js")try{return x.getFileSync(o)?.template??null}catch{return null}}continue}let n=R(t,`${e}.ts`),i=R(t,`${e}.js`);if(P(n)&&O(n).isFile())try{return x.getFileSync(n)?.template??null}catch{}else if(P(i)&&O(i).isFile())try{return x.getFileSync(n)?.template??null}catch{}let a=R(t,`${e}.html`);if(P(a)&&O(a).isFile())return V(a,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,s,n,i){let a=this._map.get(e),o=a||{},r=!1,c=M.processImportBlocks(t,d=>i&&i.has(d)?i.get(d):this._readTemplateFile(d),0,n),m=M._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(o.media=M.compileBlockMedia(c,m),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(o.message=M.compileBlockMessage(c,m),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(o.keyboard=M.compileBlockKeyboards(c,m),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(o.description=M.compileBlockDescription(c,m),r=!0),r&&this._map.set(e,o)}getMedia(e,t="default",s="default",n){let a=this._map.get(e)?.media?.[t],o=a?.[s]||a?.default;try{if(!o)throw new Error("Media function not found, please check your template");return o(n)}catch{return{}}}getMessage(e,t="default",s="default",n){try{let a=this._map.get(e)?.message?.[t],o=a?.[s]||a?.default;if(!o)throw"";return o(n)}catch{return""}}getDescription(e,t="default",s="default",n="default",i){try{let o=this._map.get(e)?.description?.[t]?.[n],r=o?.[s]||o?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",s="default"){try{let i=this._map.get(e)?.description?.[t]?.[s];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let n=this._map.get(e)?.description?.[t];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(e,t="default",s="default",n="inline",i){try{let o=this._map.get(e)?.keyboard?.[t],r=o?.[s]?.[n]||o?.default?.[n];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=R(this._path[s],e);if(P(n))return Ce(n,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};import{Bot as Ie,webhookCallback as ee}from"grammy";var K=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}maxSize;static{p(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var xe=_e((()=>{try{return f}catch{return Se(import.meta.url)}})()),Me=JSON.parse(ke(se(xe,"../../package.json"),"utf-8")).version,te=class{static{p(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?F:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${Me}`),this.cacheSession=e.cacheSession||new W("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new $({path:[se(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.token),this.bot.catch(this._onCatch),this._registerOnCallbackQueryData(),this._registerOnMessageText(),this._registerOnMessagePhoto(),this._registerOnMessageVideo(),this._registerOnMessageAudio(),this._registerOnMessageDocument(),this._registerOnMessageAnimation(),this._registerOnMessageVoice(),this._registerOnMessageVideoNote(),this._registerOnMessageSticker(),this._registerOnMessageLocation(),this._registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this._pageLoads(),process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this._runPolling();else if(e.deploy.startsWith("webhook:"))this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this._runServerless(e.deploy.split("serverless:")[1]);else if(!e.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}async stop(){await this.bot.stop(),await this.webhookServer?.stop(),this.webhookServer=void 0}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=e;this.log?.success?.(`Telegram bot deploy ${t} started: ${n} ${t=="webhook"||t=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(e){return new Ie(e,this.botConfig)}createCtx(e){return new B({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:p(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),s=ee(this.bot,"bun"),n=this.webhookQueue,i=n?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):s;let a=i?new K(n?.maxQueueSize??5e3):void 0,o=n?.workerCount??8,r=n?.perChatConcurrency??1,c=n?.blockWhenFull!==!1,m=new Map,d=new Map;this.webhookQueueInstance=a;let l=p(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),h=p(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let C=String(y),k=m.get(C)||0;if(k<r)return m.set(C,k+1),()=>this._releaseWebhookChat(C,m,d);await new Promise(he=>{let G=d.get(C)||[];G.push(he),d.set(C,G)});let de=(m.get(C)||0)+1;return m.set(C,de),()=>this._releaseWebhookChat(C,m,d)},"acquireChat");if(i&&a){await this.bot.init();for(let y=0;y<o;y++)this._startWebhookWorker(a,h,l)}let u=new URL(e),I=u.pathname,b=parseInt(u.port)||3e3,_=this.log,S="/stats_queue";this.webhookServer?.stop();let w=t({port:b,async fetch(y){let{pathname:C}=new URL(y.url);if(y.method=="POST"&&C==I){if(!i||!a)return s(y);if(!c&&a.length>=(n?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let k=await y.json();return await a.enqueue(k),new Response("OK",{status:200})}catch(k){return _?.error?.(`Webhook queue error: ${String(k)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&C==S){let k=a?.getStats()||{length:0,maxSize:n?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:S,timestamp:new Date().toISOString(),maxQueueSize:n?.maxQueueSize??5e3,workerCount:o,perChatConcurrency:r,blockWhenFull:c,queue:k,activeChats:m.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&C=="/"){let k=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:k}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=w,(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let D=await this.bot.api.getMe();await this._onStart(D,"webhook",e)}_startWebhookWorker(e,t,s){p(async()=>{for(;;){let i=await e.dequeue(),a=await t(s(i));try{await this.bot.handleUpdate(i)}catch(o){this.log?.error?.(`Webhook worker error: ${String(o)}`)}finally{a()}}},"run")()}_releaseWebhookChat(e,t,s){let n=t.get(e)||0,i=Math.max(0,n-1);i===0?t.delete(e):t.set(e,i);let a=s.get(e);a&&a.length>0&&(a.shift()(),a.length===0&&s.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,s=this.webhookQueue.workerCount??8,n=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:s,perChatConcurrency:n,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=ee(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:s}=we(t);e.data.name||(e.data.name=s),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,s){let n=e.data.name,i=e.prototype,a="handle",o="Args",r="Command",c="Caption",m="Free",d=t.routeDynamic,l=t.routeDynamicSpesific;t.all[n]=e;for(let h=0;h<t.lenListRouteStaticSession;h++){let u=t.listRouteStaticSession[h];if(typeof i[u]!="function")continue;let I=t.routeStatic[u],b=t.routeStaticIntent[u],_=t.routeStaticSession[u],S={name:n,routeName:u},w=I||b;if(w!==void 0){let v=u.includes(r),D=u.endsWith("CallbackData"),y=u.endsWith("Text"),C;if(v){let k=e.data.intentCommandText;C=k?`/${k}`:void 0}else if(D){let k=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(k=String(s),e.data.intentCallbackData=k),C=k}else y?C=e.data.intentText:C=e.data.name;C&&(w[C]=S)}if(_!==void 0){let D=`methodSession${u.replace("handle","")}`,y=i[D]?.(n);_[y]=S}if(u.startsWith("handleFree")){let v=u.replace(a,"").replace(o,"").replace(r,"").replace(c,"").replace(m,"").toLowerCase();l[v].push(S)}}i.handleFree&&d.push(n)}async executeSyncBlocksDescription(e){let t=new Map,s=e.routeStatic.handleCommandText;for(let[,n]of Object.entries(s)){let i=n.name,a=this.templateManager.getDescriptionScopes(i);for(let o of a){t.has(o)||t.set(o,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",o);for(let c of r)t.get(o).add(c)}}for(let[n,i]of t)for(let a of i){let o=[];for(let[,m]of Object.entries(s)){let d=m.name,l=this.templateManager.getDescription(d,"default",a,n);l&&o.push({command:d,description:l})}if(o.length===0)continue;let r={type:n},c=a==="default"?void 0:a;try{let m=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(m.map(h=>({command:h.command,description:h.description})).sort((h,u)=>h.command.localeCompare(u.command))),l=JSON.stringify(o.sort((h,u)=>h.command.localeCompare(u.command)));d!==l&&(await this.bot.api.setMyCommands(o,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${o.length})`))}catch(m){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(m)}`)}}}_pageLoads(){this.log?.info?.("Load pages..");let e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],s=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],n=p((o,r)=>Object.fromEntries(o.map(c=>[c,r()])),"makeObject"),i=p(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:n(e,()=>({})),routeStaticIntent:n(t,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:s,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:s.length};return x.getFileManySync(void 0).forEach(({path:o,page:r},c)=>{this._pageBuildData(r,o),this._pageSorts(r,a,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async _pageRoutes(e,t){let s,n;if(s===void 0){let a=await e.getSession();if(a){let o=a.method,r=this.pages.routeStaticSession,c=e.callbackData,m=e.msgText,d=e.msgCaption,l=c||m||d,h=t==="callbackdata",u=h?"colon":"space",I=l&&e.haveArgs(l,u)?e.getIntent(l,u,1):void 0,b=!h&&l?e.getIntent(l,"space",2):void 0;for(let _=0;_<this.pages.lenListRouteStaticSession;_++){let S=this.pages.listRouteStaticSession[_];if(S.toLowerCase().endsWith(t)){if(l){if(this.pages.routeStatic[S]?.[l])continue;let w=this.pages.routeStaticIntent[S];if(w&&(I&&w[I]||b&&w[b]))continue}n=r[S][o]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let a=e.callbackData,o=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let m=0;m<this.pages.lenListRouteStatic;m++){let d=this.pages.listRouteStatic[m];if(d.toLowerCase().endsWith(t)&&(n=c[d][a||o||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let a=this.pages.routeStaticIntent,o=t==="callbackdata",r=o?"colon":"space",c=o?e.callbackData:e.msgText||e.msgCaption,m=e.haveArgs(c,r);if(c&&m)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let l=this.pages.listRouteStaticIntent[d];if(!l.toLowerCase().endsWith(t))continue;let h=a[l];if(n=h[e.getIntent(c,r,1)],!n&&!o&&(n=h[e.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let o=await new s(e)[n.routeName]?.();return e.temp.isAnswer===!0?o:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let a=0;a<i.length;a++){let o=i[a];if(o===void 0)continue;let r=this.pages.all[o.name];r!==void 0&&typeof r.prototype[o.routeName]=="function"&&await new r(e)[o.routeName]()}for(let a=0;a<this.pages.routeDynamic.length;a++){let o=this.pages.routeDynamic[a];if(o===void 0)continue;let r=this.pages.all[o];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,s,n){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let s=this.createCtx(e);try{if(await this.hookBeforeRoute(s,t)===!1)return;await this._pageRoutes(s,t)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,t,n,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(s){await this.hookErrorPage(t,"onCallbackQueryData",s,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"contact")}_registerOnCallbackQueryData(){this.bot.on("callback_query:data",this._onCallbackQueryData.bind(this))}_registerOnMessageText(){this.bot.on("message:text",this._onMessageText.bind(this))}_registerOnMessagePhoto(){this.bot.on("message:photo",this._onMessagePhoto.bind(this))}_registerOnMessageVideo(){this.bot.on("message:video",this._onMessageVideo.bind(this))}_registerOnMessageAudio(){this.bot.on("message:audio",this._onMessageAudio.bind(this))}_registerOnMessageDocument(){this.bot.on("message:document",this._onMessageDocument.bind(this))}_registerOnMessageAnimation(){this.bot.on("message:animation",this._onMessageAnimation.bind(this))}_registerOnMessageVoice(){this.bot.on("message:voice",this._onMessageVoice.bind(this))}_registerOnMessageVideoNote(){this.bot.on("message:video_note",this._onMessageVideoNote.bind(this))}_registerOnMessageSticker(){this.bot.on("message:sticker",this._onMessageSticker.bind(this))}_registerOnMessageLocation(){this.bot.on("message:location",this._onMessageLocation.bind(this))}_registerOnMessageContact(){this.bot.on("message:contact",this._onMessageContact.bind(this))}};var ne=class{static{p(this,"BlockKeyboard")}static label;static _build(e,t,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let a=p((o,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(o):o}</keyboard>`,"pro");return t?a(i[t],t):Object.keys(i).map(o=>a(i[o],o)).join(" ")}};var ie=class{static{p(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,s)=>(t[s]=this._reverse(e[s]),t),{})}};import{isMainThread as Ae,Worker as Re}from"worker_threads";var A=class{constructor(e,t){this.send=e;this.register=t}send;register;static{p(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,s=this.send,{id:n,method:i,params:a,result:o,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let m=await c.apply(this.register,a);s({id:n,result:m})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(o!==void 0){let c=t.get(n);c&&(c.resolve(o),t.delete(n))}else if(r!==void 0){let c=t.get(n);c&&(c.reject(r),t.delete(n))}}makeId(){return Math.random()}makeRequest(e,t,s=!0,n){let i=this.makeId(),a={id:i,method:e,params:t,...n};return s?new Promise((o,r)=>{this.map.set(i,{resolve:o,reject:r}),this.send(a)}):this.send(a)}};var E=class{constructor(e,t,s){this.path=e;this.argv=t;this.register=s;this.init(),s||(s=this),this.rpc=new A(this.send.bind(this),s)}path;argv;register;static{p(this,"WorkerThreadLaunch")}static isMainThread=Ae;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new Re(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var oe=class g{static{p(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(n,i){if(!(typeof i!="string"||i==="then"))return async(a,...o)=>{let r=a.gatewayClients.get(e);return r||(r=await a.createGatewayClient(e)),r.request(i,o)}}}),s=p(function(n){return new Proxy({},{get(i,a){if(!(typeof a!="string"||a==="then"))return async(...o)=>{let r=n.gatewayClients.get(e);return r||(r=await n.createGatewayClient(e)),r.request(a,o)}}})},"ctor");return Object.setPrototypeOf(s,t),s}static init(e){let{WTInit:t,WTLaunch:s=E,path:n,wrap:i}=e,a=`for-${n}`;if(process.argv[2]===a)return new t,{launchGatewayClient:p(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let o,r=new Proxy({},{get(d,l){if(l!=="then")return l==="sendRequest"||l==="request"||l==="kill"||l==="send"?(...h)=>{if(!o)throw new Error(`Thread at ${n} not launched yet.`);return o[l](...h)}:(...h)=>{if(!o)throw new Error(`Thread at ${n} not launched yet.`);return o.request(l,h)}}}),m={...i?i(r):{},launchWorker:p(async(d=[])=>(o=new s(n,[a,...d]),await o.ready(),o),"launchWorker"),launchGatewayClient:p(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(m,{get(d,l){if(l!=="then")return l==="launchGatewayClient"?d.launchGatewayClient:l==="launchWorker"?d.launchWorker:l in d?d[l]:typeof l=="string"?(...h)=>{if(!o)throw new Error(`Thread at ${n} not launched yet.`);return o.request(l,h)}:d[l]}})}};import{Client as Pe}from"net-ipc";var L=class{static{p(this,"WorkerThreadGatewayClient")}client=new Pe;rpc;constructor(){this.rpc=new A(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),t}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};import{Server as ve}from"net-ipc";var q=class{static{p(this,"WorkerThreadGatewayServer")}server=new ve;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new A(s=>e.send(s),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let s=this.rpc.get(t.id);s&&s.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};import{parentPort as De,threadId as Oe,isMainThread as Fe}from"worker_threads";var ae=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=Oe;pid=process.pid;rpc={};parentPort=De;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=Fe;constructor(){this.init(),this.rpc=new A(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new q,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new L;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var re=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(s=>s.request(e,t,!0)))}async request(e,t,s,n=!0,i){return await this.thread.get(e)?.request(t,s,n,i)}};var ce=class{static{p(this,"MockTelegramServer")}botToken="";hostname;port;log;handlers;defaultHandler;apiRoot="";webhookUrl="";requests=[];updates=[];server;_nextUpdateId=1;_nextMessageId=1;constructor(e={}){this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.log=e.log===!0?F:e.log?e.log:void 0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:p(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.log?.info?.(`Mock Telegram server started: ${this.apiRoot}`),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0,this.log?.info?.("Mock Telegram server stopped")}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}lastRequest(e){if(!e)return this.requests[this.requests.length-1];for(let t=this.requests.length-1;t>=0;t--){let s=this.requests[t];if(s?.method===e)return s}}clearRequests(){this.requests.length=0}_defaultResponse(e,t){if(e==="getMe")return{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}};if(e==="getUpdates")return{ok:!0,result:[]};if(e==="getMyCommands")return{ok:!0,result:[]};if(e==="setMyCommands")return{ok:!0,result:!0};if(e==="setWebhook"){let s=this._bodyRecord(t),n=typeof s?.url=="string"?s.url:"";return this.webhookUrl=n,this.log?.info?.(`Mock Telegram webhook set: ${n}`),{ok:!0,result:!0}}return e==="getWebhookInfo"?{ok:!0,result:{url:this.webhookUrl}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),s=t.match(/^\/bot([^/]+)\/(.+)$/);if(!s)return new Response("Not found",{status:404});let n=s[1],i=s[2];if(!n||!i)return new Response("Not found",{status:404});this.botToken=n;let a=await this._readBody(e.clone());this.log?.debug?.(`Mock Telegram API request: ${i}`),this.requests.push({method:i,body:a,url:e.url,requestMethod:e.method,headers:Object.fromEntries(e.headers.entries())});let o=this.handlers[i]??this.defaultHandler,r=o?await o({method:i,request:e}):this._defaultResponse(i,a);return this._json(r)}_bodyRecord(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async _readBody(e){if(e.method==="GET"||e.method==="HEAD")return;let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let n=await e.formData();return Object.fromEntries(n.entries())}let s=await e.text();if(!s)return;try{return JSON.parse(s)}catch{return s}}catch{return}}_defaultUser(e){return{id:e?.id??1001,is_bot:e?.is_bot??!1,first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},language_code:e?.language_code??"en"}}_defaultChat(e){return{id:e?.id??1001,type:e?.type??"private",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},...e?.title?{title:e.title}:{}}}_nextIds(e){return{updateId:this._nextUpdateId++,messageId:e?.message_id??this._nextMessageId++,date:e?.date??Math.floor(Date.now()/1e3)}}_buildMessageUpdate(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return{update_id:s,message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),from:this._defaultUser(t?.user),...e}}}async _postUpdate(e,t){if(await this._waitForWebhookUrl(t?.responseTimeoutMs??1e3),!this.webhookUrl)throw new Error("Webhook URL is not set. Call setWebhook first or assign mockServer.webhookUrl.");let s=this.requests.length;this.updates.push(e),this.log?.info?.(`Mock Telegram update sent: ${this.webhookUrl}`);let n=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Webhook request failed with status ${n.status}`);let i=await this._waitForResponses(s,t?.responseTimeoutMs??1e3);return this.log?.info?.(`Mock Telegram bot responses captured: ${i.length}`),i}async _waitForWebhookUrl(e){if(this.webhookUrl||e<=0)return this.webhookUrl;let t=Date.now();for(;Date.now()-t<e&&(await new Promise(s=>setTimeout(s,5)),!this.webhookUrl););return this.webhookUrl}async _waitForResponses(e,t){if(t<=0)return this._userResponseRequests(e);if(this._userResponseRequests(e).length>0)return this._userResponseRequests(e);let s=Date.now();for(;Date.now()-s<t&&(await new Promise(n=>setTimeout(n,5)),!(this._userResponseRequests(e).length>0)););return this._userResponseRequests(e)}_userResponseRequests(e){return this.requests.slice(e).filter(t=>this._isUserResponseMethod(t.method))}_isUserResponseMethod(e){return e.startsWith("send")||e.startsWith("edit")||e.startsWith("answer")||e.startsWith("delete")||e.startsWith("copy")||e.startsWith("forward")||e==="pinChatMessage"||e==="unpinChatMessage"||e==="setMessageReaction"}async sendText(e,t){let s=e.startsWith("/")?[{offset:0,length:e.split(" ")[0]?.length??e.length,type:"bot_command"}]:void 0;return await this._postUpdate(this._buildMessageUpdate({text:e,...s?{entities:s}:{}},t),t)}async sendPhoto(e){return await this._postUpdate(this._buildMessageUpdate({photo:[{file_id:"mock-photo-file-id",file_unique_id:"mock-photo-unique-id",width:1,height:1}],...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideo(e){return await this._postUpdate(this._buildMessageUpdate({video:{file_id:"mock-video-file-id",file_unique_id:"mock-video-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAudio(e){return await this._postUpdate(this._buildMessageUpdate({audio:{file_id:"mock-audio-file-id",file_unique_id:"mock-audio-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendDocument(e){return await this._postUpdate(this._buildMessageUpdate({document:{file_id:"mock-document-file-id",file_unique_id:"mock-document-unique-id",file_name:"mock.txt"},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAnimation(e){return await this._postUpdate(this._buildMessageUpdate({animation:{file_id:"mock-animation-file-id",file_unique_id:"mock-animation-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVoice(e){return await this._postUpdate(this._buildMessageUpdate({voice:{file_id:"mock-voice-file-id",file_unique_id:"mock-voice-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideoNote(e){return await this._postUpdate(this._buildMessageUpdate({video_note:{file_id:"mock-video-note-file-id",file_unique_id:"mock-video-note-unique-id",length:1,duration:1}},e),e)}async sendSticker(e){return await this._postUpdate(this._buildMessageUpdate({sticker:{file_id:"mock-sticker-file-id",file_unique_id:"mock-sticker-unique-id",type:"regular",width:1,height:1,is_animated:!1,is_video:!1}},e),e)}async sendLocation(e){return await this._postUpdate(this._buildMessageUpdate({location:{latitude:e?.latitude??0,longitude:e?.longitude??0}},e),e)}async sendContact(e){return await this._postUpdate(this._buildMessageUpdate({contact:{phone_number:e?.phone_number??"+10000000000",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.user_id?{user_id:e.user_id}:{}}},e),e)}async sendCallbackQuery(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return await this._postUpdate({update_id:s,callback_query:{id:t?.id??`mock-callback-${s}`,from:this._defaultUser(t?.user),message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),text:t?.messageText??"Mock message"},chat_instance:"mock-chat-instance",data:e}},t)}};export{ne as BlockKeyboard,W as CacheExternal,B as Ctx,te as Gramstax,ie as LabelKeyboard,j as LoggingHelper,ce as MockTelegramServer,x as PageManager,M as TemplateEngine,$ as TemplateManager,K as WebhookQueue,oe as WorkerThreadExport,L as WorkerThreadGatewayClient,q as WorkerThreadGatewayServer,ae as WorkerThreadInit,E as WorkerThreadLaunch,re as WorkerThreadPool,A as WorkerThreadRpc,F as log};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gramstax",
3
- "version": "0.8.9",
3
+ "version": "0.8.11",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -47,7 +47,7 @@
47
47
  "dependencies": {
48
48
  "@keyv/redis": "^5.1.4",
49
49
  "chokidar": "^4.0.3",
50
- "grammy": "^1.38.4",
50
+ "grammy": "^1.43.0",
51
51
  "keyv": "^5.5.4",
52
52
  "logging-pretty": "^3.0.0",
53
53
  "net-ipc": "^2.2.2"