gramio 0.0.33 → 0.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,46 +1,46 @@
1
- # GramIO
2
-
3
- <div align="center">
4
-
5
- [![Bot API](https://img.shields.io/badge/Bot%20API-7.3-blue?logo=telegram&style=flat&labelColor=000&color=3b82f6)](https://core.telegram.org/bots/api)
6
- [![npm](https://img.shields.io/npm/v/gramio?logo=npm&style=flat&labelColor=000&color=3b82f6)](https://www.npmjs.org/package/@gramio/core)
7
- [![JSR](https://jsr.io/badges/@gramio/core)](https://jsr.io/@gramio/core)
8
- [![JSR Score](https://jsr.io/badges/@gramio/core/score)](https://jsr.io/@gramio/core)
9
-
10
- </div>
11
-
12
- TypeScript/JavaScript Telegram Bot API Framework for create your bots with convenience!
13
-
14
- ✨ **Extensible** - Our plugin and hook system is awesome
15
-
16
- 🛡️ **Type-safe** - Written in TypeScript with love ❤️
17
-
18
- 🌐 **Multi-runtime** - Works on [Node.js](https://nodejs.org/), [Bun](https://bun.sh/) and [Deno](https://deno.com/)\*
19
-
20
- ⚙️ **Code-generated** - Many parts are code-generated (for example, [code-generated and auto-published Telegram Bot API types](https://github.com/gramiojs/types))
21
-
22
- **Deno\*** [windows-specific issue with undici](https://github.com/denoland/deno/issues/19532)
23
-
24
- ## [Get started](https://gramio.dev/get-started)
25
-
26
- To create your new bot, you just need to write it to the console:
27
-
28
- ```bash [npm]
29
- npm create gramio ./bot
30
- ```
31
-
32
- and GramIO customize your project the way you want it!
33
-
34
- ### Example
35
-
36
- ```typescript
37
- import { Bot } from "gramio";
38
-
39
- const bot = new Bot()
40
- .command("start", (context) => context.send("Hello!"))
41
- .onStart(({ info }) => console.log(`✨ Bot ${info.username} was started!`));
42
-
43
- bot.start();
44
- ```
45
-
46
- For more, please see [documentation](https://gramio.dev).
1
+ # GramIO
2
+
3
+ <div align="center">
4
+
5
+ [![Bot API](https://img.shields.io/badge/Bot%20API-7.3-blue?logo=telegram&style=flat&labelColor=000&color=3b82f6)](https://core.telegram.org/bots/api)
6
+ [![npm](https://img.shields.io/npm/v/gramio?logo=npm&style=flat&labelColor=000&color=3b82f6)](https://www.npmjs.org/package/@gramio/core)
7
+ [![JSR](https://jsr.io/badges/@gramio/core)](https://jsr.io/@gramio/core)
8
+ [![JSR Score](https://jsr.io/badges/@gramio/core/score)](https://jsr.io/@gramio/core)
9
+
10
+ </div>
11
+
12
+ TypeScript/JavaScript Telegram Bot API Framework for create your bots with convenience!
13
+
14
+ ✨ **Extensible** - Our plugin and hook system is awesome
15
+
16
+ 🛡️ **Type-safe** - Written in TypeScript with love ❤️
17
+
18
+ 🌐 **Multi-runtime** - Works on [Node.js](https://nodejs.org/), [Bun](https://bun.sh/) and [Deno](https://deno.com/)\*
19
+
20
+ ⚙️ **Code-generated** - Many parts are code-generated (for example, [code-generated and auto-published Telegram Bot API types](https://github.com/gramiojs/types))
21
+
22
+ **Deno\*** [windows-specific issue with undici](https://github.com/denoland/deno/issues/19532)
23
+
24
+ ## [Get started](https://gramio.dev/get-started)
25
+
26
+ To create your new bot, you just need to write it to the console:
27
+
28
+ ```bash [npm]
29
+ npm create gramio ./bot
30
+ ```
31
+
32
+ and GramIO customize your project the way you want it!
33
+
34
+ ### Example
35
+
36
+ ```typescript
37
+ import { Bot } from "gramio";
38
+
39
+ const bot = new Bot(process.env.TOKEN as string)
40
+ .command("start", (context) => context.send("Hello!"))
41
+ .onStart(({ info }) => console.log(`✨ Bot ${info.username} was started!`));
42
+
43
+ bot.start();
44
+ ```
45
+
46
+ For more, please see [documentation](https://gramio.dev).
package/dist/bot.js CHANGED
@@ -106,6 +106,8 @@ let Bot = (() => {
106
106
  TELEGRAM: errors_1.TelegramError,
107
107
  };
108
108
  errorHandler(context, error) {
109
+ if (!this.hooks.onError.length)
110
+ throw error;
109
111
  return this.runImmutableHooks("onError", {
110
112
  context,
111
113
  //@ts-expect-error ErrorKind exists if user register error-class with .error("kind", SomeError);
@@ -213,8 +215,8 @@ let Bot = (() => {
213
215
  const fileId = typeof attachment === "string" ? attachment : getFileId(attachment);
214
216
  const file = await this.api.getFile({ file_id: fileId });
215
217
  const url = `https://api.telegram.org/file/bot${this.options.token}/${file.file_path}`;
216
- const res = await fetch(url);
217
- const buffer = await res.arrayBuffer();
218
+ const res = await (0, undici_1.request)(url);
219
+ const buffer = await res.body.arrayBuffer();
218
220
  if (path) {
219
221
  await promises_1.default.writeFile(path, node_buffer_1.Buffer.from(buffer));
220
222
  return path;
@@ -539,8 +541,9 @@ let Bot = (() => {
539
541
  return next();
540
542
  if (trigger instanceof RegExp && !trigger.test(context.data))
541
543
  return next();
542
- // @ts-expect-error
543
- context.queryData = trigger.unpack(context.data);
544
+ if (trigger instanceof callback_data_1.CallbackData)
545
+ // @ts-expect-error
546
+ context.queryData = trigger.unpack(context.data);
544
547
  //@ts-expect-error
545
548
  return handler(context);
546
549
  });
package/dist/composer.js CHANGED
@@ -11,9 +11,7 @@ class Composer {
11
11
  constructor(onError) {
12
12
  this.onError =
13
13
  onError ||
14
- ((context, error) => {
15
- // @ts-expect-error
16
- error.context = context;
14
+ ((_, error) => {
17
15
  throw error;
18
16
  });
19
17
  this.recompose();
package/dist/plugin.d.ts CHANGED
@@ -138,7 +138,7 @@ export declare class Plugin<Errors extends ErrorDefinitions = {}, Derives extend
138
138
  preRequest<Methods extends keyof APIMethods, Handler extends Hooks.PreRequest<Methods>>(methods: MaybeArray<Methods>, handler: Handler): this;
139
139
  preRequest(handler: Hooks.PreRequest): this;
140
140
  /**
141
- * This hook called when API return sucesfull response
141
+ * This hook called when API return successful response
142
142
  *
143
143
  * [Documentation](https://gramio.dev/hooks/on-response.html)
144
144
  * */
package/dist/plugin.js CHANGED
@@ -156,7 +156,7 @@ let Plugin = (() => {
156
156
  }
157
157
  /** Register handler to one or many Updates */
158
158
  on(updateName, handler) {
159
- this.on(updateName, handler);
159
+ this._.composer.on(updateName, handler);
160
160
  return this;
161
161
  }
162
162
  /** Register handler to any Updates */
package/dist/updates.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type Context } from "@gramio/contexts";
2
2
  import type { APIMethodParams, TelegramUpdate } from "@gramio/types";
3
- import { type CaughtMiddlewareHandler } from "middleware-io";
3
+ import type { CaughtMiddlewareHandler } from "middleware-io";
4
4
  import { Composer } from "./composer";
5
5
  import type { AnyBot } from "./types";
6
6
  export declare class Updates {
@@ -1,25 +1,54 @@
1
1
  import type { TelegramUpdate } from "@gramio/types";
2
+ import { Response } from "undici";
2
3
  import type { MaybePromise } from "../types";
3
4
  export interface FrameworkHandler {
4
5
  update: MaybePromise<TelegramUpdate>;
5
- header?: string;
6
+ header: string;
7
+ unauthorized: () => unknown;
8
+ response?: () => unknown;
6
9
  }
7
10
  export type FrameworkAdapter = (...args: any[]) => FrameworkHandler;
8
11
  export declare const frameworks: {
9
12
  elysia: ({ body, headers }: any) => {
10
13
  update: any;
11
14
  header: any;
15
+ unauthorized: () => Response;
12
16
  };
13
- fastify: (request: any) => {
17
+ fastify: (request: any, reply: any) => {
14
18
  update: any;
15
19
  header: any;
20
+ unauthorized: () => any;
16
21
  };
17
22
  hono: (c: any) => {
18
23
  update: any;
19
24
  header: any;
25
+ unauthorized: () => any;
20
26
  };
21
- express: (req: any) => {
27
+ express: (req: any, res: any) => {
22
28
  update: any;
23
29
  header: any;
30
+ unauthorized: () => any;
31
+ };
32
+ koa: (ctx: any) => {
33
+ update: any;
34
+ header: any;
35
+ unauthorized: () => void;
36
+ };
37
+ http: (req: any, res: any) => {
38
+ update: Promise<TelegramUpdate>;
39
+ header: any;
40
+ unauthorized: () => any;
41
+ };
42
+ "std/http": (req: any) => {
43
+ update: any;
44
+ header: any;
45
+ response: () => Response;
46
+ unauthorized: () => Response;
47
+ };
48
+ "Bun.serve": (req: any) => {
49
+ update: any;
50
+ header: any;
51
+ response: () => Response;
52
+ unauthorized: () => Response;
24
53
  };
25
54
  };
@@ -1,22 +1,59 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.frameworks = void 0;
4
+ const undici_1 = require("undici");
4
5
  const SECRET_TOKEN_HEADER = "X-Telegram-Bot-Api-Secret-Token";
6
+ const WRONG_TOKEN_ERROR = "secret token is invalid";
5
7
  exports.frameworks = {
6
8
  elysia: ({ body, headers }) => ({
7
9
  update: body,
8
10
  header: headers[SECRET_TOKEN_HEADER],
11
+ unauthorized: () => new undici_1.Response(WRONG_TOKEN_ERROR, { status: 401 }),
9
12
  }),
10
- fastify: (request) => ({
13
+ fastify: (request, reply) => ({
11
14
  update: request.body,
12
15
  header: request.headers[SECRET_TOKEN_HEADER],
16
+ unauthorized: () => reply.code(401).send(WRONG_TOKEN_ERROR),
13
17
  }),
14
18
  hono: (c) => ({
15
19
  update: c.req.json(),
16
20
  header: c.req.header(SECRET_TOKEN_HEADER),
21
+ unauthorized: () => c.text(WRONG_TOKEN_ERROR, 401),
17
22
  }),
18
- express: (req) => ({
23
+ express: (req, res) => ({
19
24
  update: req.body,
20
25
  header: req.header(SECRET_TOKEN_HEADER),
26
+ unauthorized: () => res.status(401).send(WRONG_TOKEN_ERROR),
27
+ }),
28
+ koa: (ctx) => ({
29
+ update: ctx.request.body,
30
+ header: ctx.get(SECRET_TOKEN_HEADER),
31
+ unauthorized: () => {
32
+ ctx.status === 401;
33
+ ctx.body = WRONG_TOKEN_ERROR;
34
+ },
35
+ }),
36
+ http: (req, res) => ({
37
+ update: new Promise((resolve) => {
38
+ let body = "";
39
+ req.on("data", (chunk) => {
40
+ body += chunk.toString();
41
+ });
42
+ req.on("end", () => resolve(JSON.parse(body)));
43
+ }),
44
+ header: req.headers[SECRET_TOKEN_HEADER.toLowerCase()],
45
+ unauthorized: () => res.writeHead(401).end(WRONG_TOKEN_ERROR),
46
+ }),
47
+ "std/http": (req) => ({
48
+ update: req.json(),
49
+ header: req.headers.get(SECRET_TOKEN_HEADER),
50
+ response: () => new undici_1.Response("ok!"),
51
+ unauthorized: () => new undici_1.Response(WRONG_TOKEN_ERROR, { status: 401 }),
52
+ }),
53
+ "Bun.serve": (req) => ({
54
+ update: req.json(),
55
+ header: req.headers.get(SECRET_TOKEN_HEADER),
56
+ response: () => new undici_1.Response("ok!"),
57
+ unauthorized: () => new undici_1.Response(WRONG_TOKEN_ERROR, { status: 401 }),
21
58
  }),
22
59
  };
@@ -30,4 +30,49 @@ export type WebhookHandlers = keyof typeof frameworks;
30
30
  * });
31
31
  * ```
32
32
  */
33
- export declare function webhookHandler(bot: Bot, framework: keyof typeof frameworks): (...args: any[]) => Promise<void>;
33
+ export declare function webhookHandler<Framework extends keyof typeof frameworks>(bot: Bot, framework: Framework, secretToken?: string): ReturnType<{
34
+ elysia: ({ body, headers }: any) => {
35
+ update: any;
36
+ header: any;
37
+ unauthorized: () => import("undici").Response;
38
+ };
39
+ fastify: (request: any, reply: any) => {
40
+ update: any;
41
+ header: any;
42
+ unauthorized: () => any;
43
+ };
44
+ hono: (c: any) => {
45
+ update: any;
46
+ header: any;
47
+ unauthorized: () => any;
48
+ };
49
+ express: (req: any, res: any) => {
50
+ update: any;
51
+ header: any;
52
+ unauthorized: () => any;
53
+ };
54
+ koa: (ctx: any) => {
55
+ update: any;
56
+ header: any;
57
+ unauthorized: () => void;
58
+ };
59
+ http: (req: any, res: any) => {
60
+ update: Promise<import("@gramio/types").TelegramUpdate>;
61
+ header: any;
62
+ unauthorized: () => any;
63
+ };
64
+ "std/http": (req: any) => {
65
+ update: any;
66
+ header: any;
67
+ response: () => import("undici").Response;
68
+ unauthorized: () => import("undici").Response;
69
+ };
70
+ "Bun.serve": (req: any) => {
71
+ update: any;
72
+ header: any;
73
+ response: () => import("undici").Response;
74
+ unauthorized: () => import("undici").Response;
75
+ };
76
+ }[Framework]> extends {
77
+ response: () => any;
78
+ } ? (...args: Parameters<(typeof frameworks)[Framework]>) => ReturnType<ReturnType<(typeof frameworks)[Framework]>["response"]> : (...args: Parameters<(typeof frameworks)[Framework]>) => void;
@@ -30,11 +30,18 @@ const adapters_1 = require("./adapters");
30
30
  * });
31
31
  * ```
32
32
  */
33
- function webhookHandler(bot, framework) {
33
+ function webhookHandler(bot, framework, secretToken) {
34
34
  const frameworkAdapter = adapters_1.frameworks[framework];
35
- return async (...args) => {
36
- const { update } = frameworkAdapter(...args);
35
+ return (async (...args) => {
36
+ // @ts-expect-error
37
+ const { update, response, header, unauthorized } = frameworkAdapter(
38
+ // @ts-expect-error
39
+ ...args);
40
+ if (secretToken && header !== secretToken)
41
+ return unauthorized();
37
42
  await bot.updates.handleUpdate(await update);
38
- };
43
+ if (response)
44
+ return response();
45
+ });
39
46
  }
40
47
  exports.webhookHandler = webhookHandler;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gramio",
3
- "version": "0.0.33",
3
+ "version": "0.0.36",
4
4
  "description": "Powerful Telegram Bot API framework",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -20,25 +20,26 @@
20
20
  "lint": "bunx @biomejs/biome check ./src",
21
21
  "lint:fix": "bun lint --apply",
22
22
  "prepublishOnly": "tsc",
23
- "jsr": "bun scripts/release-jsr.ts"
23
+ "jsr": "bun scripts/release-jsr.ts",
24
+ "try-deno": "deno publish --unstable-sloppy-imports --dry-run --allow-slow-types --allow-dirty"
24
25
  },
25
26
  "author": "kravets",
26
27
  "license": "ISC",
27
28
  "devDependencies": {
28
29
  "@biomejs/biome": "1.7.3",
29
- "@types/node": "^20.12.9",
30
+ "@types/node": "^20.12.12",
30
31
  "typescript": "^5.4.5"
31
32
  },
32
33
  "dependencies": {
33
34
  "@gramio/callback-data": "^0.0.3",
34
35
  "@gramio/contexts": "^0.0.15",
35
36
  "@gramio/files": "^0.0.8",
36
- "@gramio/format": "^0.1.0",
37
+ "@gramio/format": "^0.1.1",
37
38
  "@gramio/keyboards": "^0.3.1",
38
39
  "@gramio/types": "^7.3.4",
39
40
  "inspectable": "^3.0.1",
40
41
  "middleware-io": "^2.8.1",
41
- "undici": "^6.16.1"
42
+ "undici": "^6.17.0"
42
43
  },
43
44
  "files": [
44
45
  "dist"
@@ -1,8 +0,0 @@
1
- import { APIMethodParams, APIMethods, TelegramAPIResponseError, TelegramResponseParameters } from "@gramio/types";
2
- export declare class TelegramError<T extends keyof APIMethods> extends Error {
3
- method: T;
4
- params: APIMethodParams<T>;
5
- code: number;
6
- payload?: TelegramResponseParameters;
7
- constructor(error: TelegramAPIResponseError, method: T, params: APIMethodParams<T>);
8
- }
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TelegramError = void 0;
4
- class TelegramError extends Error {
5
- method;
6
- params;
7
- code;
8
- payload;
9
- constructor(error, method, params) {
10
- super(error.description);
11
- this.name = method;
12
- this.method = method;
13
- this.params = params;
14
- this.code = error.error_code;
15
- if (error.parameters)
16
- this.payload = error.parameters;
17
- }
18
- }
19
- exports.TelegramError = TelegramError;