gramio 0.0.47 → 0.0.49

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Kravets
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <div align="center">
4
4
 
5
- [![Bot API](https://img.shields.io/badge/Bot%20API-7.8-blue?logo=telegram&style=flat&labelColor=000&color=3b82f6)](https://core.telegram.org/bots/api)
5
+ [![Bot API](https://img.shields.io/badge/Bot%20API-7.10-blue?logo=telegram&style=flat&labelColor=000&color=3b82f6)](https://core.telegram.org/bots/api)
6
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
7
  [![JSR](https://jsr.io/badges/@gramio/core)](https://jsr.io/@gramio/core)
8
8
  [![JSR Score](https://jsr.io/badges/@gramio/core/score)](https://jsr.io/@gramio/core)
@@ -15,11 +15,10 @@ TypeScript/JavaScript Telegram Bot API Framework for create your bots with conve
15
15
 
16
16
  🛡️ **Type-safe** - Written in TypeScript with love ❤️
17
17
 
18
- 🌐 **Multi-runtime** - Works on [Node.js](https://nodejs.org/), [Bun](https://bun.sh/) and [Deno](https://deno.com/)\*
18
+ 🌐 **Multi-runtime** - Works on [Node.js](https://nodejs.org/), [Bun](https://bun.sh/) and [Deno](https://deno.com/)
19
19
 
20
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
21
 
22
- **Deno\*** [windows-specific issue with undici](https://github.com/denoland/deno/issues/19532)
23
22
 
24
23
  ## [Get started](https://gramio.dev/get-started)
25
24
 
package/dist/bot.d.ts CHANGED
@@ -17,8 +17,13 @@ import { Updates } from "./updates";
17
17
  * ```
18
18
  */
19
19
  export declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends DeriveDefinitions = DeriveDefinitions> {
20
+ _: {
21
+ /** @internal. Remap generic */
22
+ derives: Derives;
23
+ };
20
24
  /** @internal. Remap generic */
21
25
  __Derives: Derives;
26
+ private filters;
22
27
  /** Options provided to instance */
23
28
  readonly options: BotOptions;
24
29
  /** Bot data (filled in when calling bot.init/bot.start) */
package/dist/bot.js CHANGED
@@ -46,7 +46,6 @@ const files_1 = require("@gramio/files");
46
46
  const format_1 = require("@gramio/format");
47
47
  const debug_1 = __importDefault(require("debug"));
48
48
  const inspectable_1 = require("inspectable");
49
- const undici_1 = require("undici");
50
49
  const errors_1 = require("./errors");
51
50
  const plugin_1 = require("./plugin");
52
51
  const updates_1 = require("./updates");
@@ -81,8 +80,15 @@ let Bot = (() => {
81
80
  if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
82
81
  __runInitializers(_classThis, _classExtraInitializers);
83
82
  }
83
+ _ = {
84
+ /** @internal. Remap generic */
85
+ derives: {},
86
+ };
84
87
  /** @internal. Remap generic */
85
88
  __Derives;
89
+ filters = {
90
+ context: (name) => (context) => context.is(name),
91
+ };
86
92
  /** Options provided to instance */
87
93
  options;
88
94
  /** Bot data (filled in when calling bot.init/bot.start) */
@@ -101,7 +107,10 @@ let Bot = (() => {
101
107
  * [Documentation](https://gramio.dev/bot-api.html)
102
108
  */
103
109
  api = new Proxy({}, {
104
- get: (_target, method) => (args) => this._callApi(method, args),
110
+ get: (_target, method) =>
111
+ // @ts-expect-error
112
+ // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
113
+ (_target[method] ??= (args) => this._callApi(method, args)),
105
114
  });
106
115
  lazyloadPlugins = [];
107
116
  dependencies = [];
@@ -174,8 +183,19 @@ let Bot = (() => {
174
183
  async _callApi(method, params = {}) {
175
184
  const debug$api$method = debug$api.extend(method);
176
185
  const url = `${this.options.api.baseURL}${this.options.token}/${method}`;
186
+ // Omit<
187
+ // NonNullable<Parameters<typeof fetch>[1]>,
188
+ // "headers"
189
+ // > & {
190
+ // headers: Headers;
191
+ // }
192
+ // idk why it cause https://github.com/gramiojs/gramio/actions/runs/10388006206/job/28762703484
193
+ // also in logs types differs
177
194
  const reqOptions = {
178
195
  method: "POST",
196
+ ...this.options.api.fetchOptions,
197
+ // @ts-ignore types node/bun and global missmatch
198
+ headers: new Headers(this.options.api.fetchOptions?.headers),
179
199
  };
180
200
  const context = await this.runHooks("preRequest",
181
201
  // TODO: fix type error
@@ -193,14 +213,12 @@ let Bot = (() => {
193
213
  reqOptions.body = formData;
194
214
  }
195
215
  else {
196
- reqOptions.headers = {
197
- "Content-Type": "application/json",
198
- };
216
+ reqOptions.headers.set("Content-Type", "application/json");
199
217
  reqOptions.body = JSON.stringify(params);
200
218
  }
201
219
  debug$api$method("options: %j", reqOptions);
202
- const response = await (0, undici_1.request)(url, reqOptions);
203
- const data = (await response.body.json());
220
+ const response = await fetch(url, reqOptions);
221
+ const data = (await response.json());
204
222
  debug$api$method("response: %j", data);
205
223
  if (!data.ok) {
206
224
  const err = new errors_1.TelegramError(data, method, params);
@@ -234,8 +252,8 @@ let Bot = (() => {
234
252
  const fileId = typeof attachment === "string" ? attachment : getFileId(attachment);
235
253
  const file = await this.api.getFile({ file_id: fileId });
236
254
  const url = `${this.options.api.baseURL.replace("/bot", "/file/bot")}${this.options.token}/${file.file_path}`;
237
- const res = await (0, undici_1.request)(url);
238
- const buffer = await res.body.arrayBuffer();
255
+ const res = await fetch(url);
256
+ const buffer = await res.arrayBuffer();
239
257
  if (path) {
240
258
  await promises_1.default.writeFile(path, node_buffer_1.Buffer.from(buffer));
241
259
  return path;
@@ -427,6 +445,16 @@ let Bot = (() => {
427
445
  this.hooks.onResponseError.push(methodsOrHandler);
428
446
  return this;
429
447
  }
448
+ // onExperimental(
449
+ // // filter: Filters,
450
+ // filter: (
451
+ // f: Filters<
452
+ // Context<typeof this> & Derives["global"],
453
+ // [{ equal: { prop: number }; addition: { some: () => 2 } }]
454
+ // >,
455
+ // ) => Filters,
456
+ // handler: Handler<Context<typeof this> & Derives["global"]>,
457
+ // ) {}
430
458
  /** Register handler to one or many Updates */
431
459
  on(updateName, handler) {
432
460
  this.updates.composer.on(updateName, handler);
@@ -722,7 +750,15 @@ let Bot = (() => {
722
750
  */
723
751
  async init() {
724
752
  await Promise.all(this.lazyloadPlugins.map(async (plugin) => this.extend(await plugin)));
725
- this.info = await this.api.getMe();
753
+ const info = await this.api.getMe({
754
+ suppress: true,
755
+ });
756
+ if (info instanceof errors_1.TelegramError) {
757
+ if (info.code === 404)
758
+ info.message = "The bot token is incorrect. Check it in BotFather.";
759
+ throw info;
760
+ }
761
+ this.info = info;
726
762
  }
727
763
  /**
728
764
  * Start receive updates via long-polling or webhook
@@ -0,0 +1,20 @@
1
+ import type { Context, ContextType, MaybeArray, UpdateName } from "@gramio/contexts";
2
+ import type { Bot } from "./bot";
3
+ export interface AdditionDefinitions {
4
+ equal: any;
5
+ addition: Record<string, any>;
6
+ }
7
+ type ReturnIfNonNever<T> = [T] extends [never] ? {} : T;
8
+ export type Filters<BotType extends Bot = Bot, Base = Context<BotType>, ConditionalAdditions extends AdditionDefinitions[] = []> = {
9
+ _s: Base;
10
+ _ad: ConditionalAdditions;
11
+ __filters: ((context: Context<BotType>) => boolean)[];
12
+ context<T extends UpdateName>(updateName: MaybeArray<T>): Filters<BotType, ContextType<BotType, T>, ConditionalAdditions>;
13
+ is2(): Filters<BotType, 2, ConditionalAdditions>;
14
+ } & ReturnIfNonNever<{
15
+ [K in keyof ConditionalAdditions & number]: ConditionalAdditions[K] extends {
16
+ equal: infer E;
17
+ addition: infer T;
18
+ } ? Base extends E ? T : {} : {};
19
+ }[number]>;
20
+ export {};
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // type filter = Filters<
4
+ // Context<Bot> & {prop: 2},
5
+ // [{ equal: { prop: 2 }; addition: { some: 2 } }]
6
+ // >;
7
+ // const a = {} as filter;
8
+ // // a.s;
9
+ // type S = [{ equal: { prop: 2 }; addition: { some: 2 } }];
10
+ // type C = {[K in keyof S & number]: S[K]};
11
+ // type SA = {
12
+ // [K in keyof S & number]: S[K] extends {
13
+ // equal: infer E;
14
+ // addition: infer T;
15
+ // } ? Context<Bot> & {prop: 2} extends E ? T : {} : {}}[number];
16
+ // type A = Context<Bot> & {prop: 2} extends SA ? true : false;
17
+ // export const filters: Filters = {
18
+ // __filters: [],
19
+ // context(updateName) {
20
+ // this.__filters.push((context) => context.is(updateName));
21
+ // return this;
22
+ // },
23
+ // };
package/dist/types.d.ts CHANGED
@@ -15,6 +15,8 @@ export interface BotOptions {
15
15
  };
16
16
  /** Options to configure how to send requests to the Telegram Bot API */
17
17
  api: {
18
+ /** Configure {@link fetch} parameters */
19
+ fetchOptions?: Parameters<typeof fetch>[1];
18
20
  /** URL which will be used to send requests to. @default "https://api.telegram.org/bot" */
19
21
  baseURL: string;
20
22
  /**
@@ -232,6 +234,7 @@ export declare namespace Hooks {
232
234
  export type ErrorDefinitions = Record<string, Error>;
233
235
  /** Map of derives */
234
236
  export type DeriveDefinitions = Record<UpdateName | "global", {}>;
237
+ export type FilterDefinitions = Record<string, (...args: any[]) => (context: Context<Bot>) => boolean>;
235
238
  /** Type of Bot that accepts any generics */
236
239
  export type AnyBot = Bot<any, any>;
237
240
  /** Type of Bot that accepts any generics */
@@ -1,5 +1,4 @@
1
1
  import type { TelegramUpdate } from "@gramio/types";
2
- import { Response } from "undici";
3
2
  import type { MaybePromise } from "../types";
4
3
  export interface FrameworkHandler {
5
4
  update: MaybePromise<TelegramUpdate>;
@@ -12,7 +11,7 @@ export declare const frameworks: {
12
11
  elysia: ({ body, headers }: any) => {
13
12
  update: any;
14
13
  header: any;
15
- unauthorized: () => Response;
14
+ unauthorized: () => import("bun-types/fetch").Response;
16
15
  };
17
16
  fastify: (request: any, reply: any) => {
18
17
  update: any;
@@ -42,13 +41,13 @@ export declare const frameworks: {
42
41
  "std/http": (req: any) => {
43
42
  update: any;
44
43
  header: any;
45
- response: () => Response;
46
- unauthorized: () => Response;
44
+ response: () => import("bun-types/fetch").Response;
45
+ unauthorized: () => import("bun-types/fetch").Response;
47
46
  };
48
47
  "Bun.serve": (req: any) => {
49
48
  update: any;
50
49
  header: any;
51
- response: () => Response;
52
- unauthorized: () => Response;
50
+ response: () => import("bun-types/fetch").Response;
51
+ unauthorized: () => import("bun-types/fetch").Response;
53
52
  };
54
53
  };
@@ -1,14 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.frameworks = void 0;
4
- const undici_1 = require("undici");
5
4
  const SECRET_TOKEN_HEADER = "X-Telegram-Bot-Api-Secret-Token";
6
5
  const WRONG_TOKEN_ERROR = "secret token is invalid";
7
6
  exports.frameworks = {
8
7
  elysia: ({ body, headers }) => ({
9
8
  update: body,
10
9
  header: headers[SECRET_TOKEN_HEADER],
11
- unauthorized: () => new undici_1.Response(WRONG_TOKEN_ERROR, { status: 401 }),
10
+ unauthorized: () => new Response(WRONG_TOKEN_ERROR, { status: 401 }),
12
11
  }),
13
12
  fastify: (request, reply) => ({
14
13
  update: request.body,
@@ -47,13 +46,13 @@ exports.frameworks = {
47
46
  "std/http": (req) => ({
48
47
  update: req.json(),
49
48
  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 }),
49
+ response: () => new Response("ok!"),
50
+ unauthorized: () => new Response(WRONG_TOKEN_ERROR, { status: 401 }),
52
51
  }),
53
52
  "Bun.serve": (req) => ({
54
53
  update: req.json(),
55
54
  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 }),
55
+ response: () => new Response("ok!"),
56
+ unauthorized: () => new Response(WRONG_TOKEN_ERROR, { status: 401 }),
58
57
  }),
59
58
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gramio",
3
3
  "type": "commonjs",
4
- "version": "0.0.47",
4
+ "version": "0.0.49",
5
5
  "description": "Powerful, extensible and really type-safe Telegram Bot API framework",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -25,25 +25,24 @@
25
25
  "try-deno": "deno publish --unstable-sloppy-imports --dry-run --allow-slow-types --allow-dirty"
26
26
  },
27
27
  "author": "kravets",
28
- "license": "ISC",
28
+ "license": "MIT",
29
29
  "devDependencies": {
30
- "@biomejs/biome": "1.7.3",
31
- "@types/bun": "^1.1.6",
30
+ "@biomejs/biome": "1.8.3",
31
+ "@types/bun": "^1.1.8",
32
32
  "@types/debug": "^4.1.12",
33
- "@types/node": "^20.14.13",
33
+ "pkgroll": "^2.4.2",
34
34
  "typescript": "^5.5.4"
35
35
  },
36
36
  "dependencies": {
37
37
  "@gramio/callback-data": "^0.0.3",
38
- "@gramio/contexts": "^0.0.21",
39
- "@gramio/files": "^0.0.11",
38
+ "@gramio/contexts": "^0.0.23",
39
+ "@gramio/files": "^0.0.12",
40
40
  "@gramio/format": "^0.1.3",
41
41
  "@gramio/keyboards": "^0.3.3",
42
- "@gramio/types": "^7.8.0",
43
- "debug": "^4.3.6",
42
+ "@gramio/types": "^7.10.0",
43
+ "debug": "^4.3.7",
44
44
  "inspectable": "^3.0.2",
45
- "middleware-io": "^2.8.1",
46
- "undici": "^6.19.5"
45
+ "middleware-io": "^2.8.1"
47
46
  },
48
47
  "files": ["dist"]
49
48
  }