### Install @grammyjs/parse-mode via npm Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Use npm to install the package. This is the standard way to add the library to your Node.js project. ```bash npm install @grammyjs/parse-mode ``` -------------------------------- ### TextWithEntities Interface Usage Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Shows an example of creating a TextWithEntities object with plain text and a bold formatting entity. ```typescript const formatted: TextWithEntities = { text: "Hello world", entities: [ { type: "bold", offset: 0, length: 5 } ] }; ``` -------------------------------- ### Basic Usage Example with Formatting Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Demonstrates how to import and use the fmt and b functions to create a bold message. No plugin registration is needed. ```typescript import { Bot } from "grammy"; import { fmt, b } from "@grammyjs/parse-mode"; const bot = new Bot(token); // No need to register plugin // Just import and use bot.command("demo", (ctx) => { const message = fmt`${b}bold text${b}`; return ctx.reply(message.text, { entities: message.entities }); }); ``` -------------------------------- ### Complex Formatting Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Demonstrates combining multiple entity types, variables, and formatting options within a single `fmt` call for a comprehensive message. ```typescript import { fmt, b, i, a, code } from "@grammyjs/parse-mode"; const username = "Alice"; const repo = "awesome-project"; const message = fmt` ${b}Welcome ${username}!${b} ${i}Repository:${i} ${a("https://github.com/" + repo)} ${repo}${a} ${b}Quick commands:${b} ${code}/start${code} - Start the bot ${code}/help${code} - Show help `; await ctx.reply(message.text, { entities: message.entities }); ``` -------------------------------- ### startsWith Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Checks whether a FormattedString starts with the specified pattern. Both text and entities must match exactly. ```APIDOC ## static startsWith(source, pattern) ### Description Checks whether a FormattedString starts with the specified pattern. Both text and entities must match exactly. ### Method static ### Parameters #### Path Parameters - **source** (FormattedString) - Required - The FormattedString to check - **pattern** (FormattedString) - Required - The pattern to check for at the beginning ### Returns true if the source starts with the pattern, false otherwise ``` -------------------------------- ### fmt Usage Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Demonstrates the basic usage of the fmt function as a tagged template literal to create bold, italic, and combined formatted text. ```APIDOC ## Usage The `fmt` function is primarily used as a tagged template literal: ```typescript import { fmt, b, i, u } from "@grammyjs/parse-mode"; const bold = fmt`${b}bold text${b}`; const italic = fmt`${i}italic text${i}`; const combined = fmt`${b}bold${b} and ${i}italic${i}`; ``` ``` -------------------------------- ### Nested HTML Formatting Example Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates allowed nesting of bold, italic, and underlined tags in HTML. ```html bold and italic underlined bold ``` -------------------------------- ### CI/CD Pipeline Matrix Configuration Source: https://github.com/grammyjs/parse-mode/blob/master/GEMINI.md Example of a GitHub Actions matrix configuration for CI/CD, specifying different test types to be run. ```yaml matrix: testType: ["lint", "fmt", "check", "test"] ``` -------------------------------- ### Stringable Interface Usage Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Demonstrates how to use the Stringable interface with a string literal and a FormattedString object. ```typescript const obj: Stringable = "text"; const formatted = FormattedString.b(obj); ``` -------------------------------- ### Simple MessageEntity Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Example of a basic MessageEntity for text formatting like bold, italic, or code. It includes type, offset, and length. ```typescript // Bold, italic, underline, strikethrough, code, spoiler, blockquote types const simpleEntity: MessageEntity = { type: "bold", offset: 0, length: 5 }; ``` -------------------------------- ### Stringable Implementation Examples Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Demonstrates various types that satisfy the Stringable interface, including primitive strings, custom objects with a `toString()` method, numbers, and `Date` objects. ```typescript // String is Stringable const str: Stringable = "text"; // FormattedString is Stringable const formatted: Stringable = new FormattedString("text"); // Custom objects const custom: Stringable = { toString() { return "custom text"; } }; // Numbers have toString() const num: Stringable = 42; // Objects with toString() const obj: Stringable = new Date(); ``` -------------------------------- ### Pre MessageEntity Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Example of a 'pre' type MessageEntity, used for code blocks. It includes an optional 'language' property for syntax highlighting. ```typescript // Pre type with optional language const preEntity: MessageEntity = { type: "pre", offset: 0, length: 20, language: "javascript" }; ``` -------------------------------- ### Nested Formatting Example Source: https://github.com/grammyjs/parse-mode/blob/master/docs/MarkdownV2.md Demonstrates nesting of bold and italic formatting. Note that code and pre entities cannot be nested. ```typescript import { bold, fmt, italic } from "@grammyjs/parse-mode"; // Bold italic text const boldItalic = fmt`${bold}${italic}bold and italic${italic}${bold}`; ``` ```plaintext *_bold and italic_* ``` -------------------------------- ### Combining Multiple Formatting Utilities Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/utility-functions.md Combines user mentions and message links within a single formatted message. This example shows how to construct a complex notification message. ```typescript import { mentionUser, linkMessage, fmt, b } from "@grammyjs/parse-mode"; const notification = fmt` ${b}New activity:${b} ${mentionUser("User profile", 123456789)} mentioned you in ${linkMessage("this message", -1001234567890, 99)} `; await ctx.reply(notification.text, { entities: notification.entities }); ``` -------------------------------- ### Text Link MessageEntity Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Example of a 'text_link' type MessageEntity, used for creating clickable links within text. It requires a 'url' property. ```typescript // Text link type const linkEntity: MessageEntity = { type: "text_link", offset: 0, length: 4, url: "https://example.com" }; ``` -------------------------------- ### Catch-All Error Handling Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/errors.md Wrap API calls in a try-catch block to handle potential errors during message formatting and sending. Provides a fallback to send plain text if formatting fails. ```typescript import { fmt, b } from "@grammyjs/parse-mode"; try { const formatted = fmt`${b}bold${b}`; await ctx.reply(formatted.text, { entities: formatted.entities }); } catch (error) { console.error("Failed to send message:", error); // Fallback: send plain text await ctx.reply("Message could not be formatted"); } ``` -------------------------------- ### Check if Formatted String Starts With Pattern Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Checks whether a FormattedString starts with a specified pattern. Both the text content and entities of the source and pattern must match exactly. ```typescript static startsWith(source: FormattedString, pattern: FormattedString): boolean ``` -------------------------------- ### Compose Formatted Messages with fmt Source: https://github.com/grammyjs/parse-mode/blob/master/README.md Use the `fmt` function with tagged template literals and formatters like `b` (bold) and `u` (underline) to construct formatted messages and captions. This example demonstrates replying with text and a photo caption. ```typescript import { Bot } from "grammy"; import { b, fmt, u } from "@grammyjs/parse-mode"; const bot = new Bot(""); bot.command("demo", async (ctx) => { // Using return values of fmt const combined = fmt`${b}bolded${b} ${ctx.msg.text} ${u}underlined${u}`; await ctx.reply(combined.text, { entities: combined.entities }); await ctx.replyWithPhoto(photo, { caption: combined.caption, caption_entities: combined.caption_entities, }); }); bot.start(); ``` -------------------------------- ### Compose Formatted Messages with fmt Source: https://github.com/grammyjs/parse-mode/blob/master/src/README.md Use the `fmt` function with tagged template literals and formatters like `b` (bold) and `u` (underline) to construct formatted messages. This example shows how to reply with a formatted text message and a photo caption. ```typescript import { Bot } from "grammy"; import { fmt, b, u } from "@grammyjs/parse-mode"; const bot = new Bot(""); bot.command("demo", async (ctx) => { // Using return values of fmt const combined = fmt`${b}bolded${b} ${ctx.msg.text} ${u}underlined${u}`; await ctx.reply(combined.text, { entities: combined.entities }); await ctx.replyWithPhoto(photo, { caption: combined.caption, caption_entities: combined.caption_entities }); }); bot.start(); ``` -------------------------------- ### Complete HTML Parsing Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/html-stream-parser.md Parses a comprehensive HTML string including various tags like bold, italic, underline, links, preformatted text, spoilers, and blockquotes. This is useful for converting rich HTML into text and entities for bot messages. ```typescript import { HTMLStreamParser } from "@grammyjs/parse-mode"; const html = ` Welcome! This is italic and this is underlined. Visit our website
def hello():
    print("world")
  
Hidden content
A quote
`; const parser = new HTMLStreamParser(); parser.add(html); const formatted = parser.toFormattedString(); await ctx.reply(formatted.text, { entities: formatted.entities }); ``` -------------------------------- ### Compose Formatted Messages with FormattedString Source: https://github.com/grammyjs/parse-mode/blob/master/src/README.md Utilize the `FormattedString` class and its methods like `b` (bold), `plain`, and `u` (underline) to build formatted messages. This example demonstrates replying with a formatted text message and a photo caption. ```typescript import { Bot } from "grammy"; import { FormattedString } from "@grammyjs/parse-mode"; const bot = new Bot(""); bot.command("demo", async (ctx) => { // Using return values of Fmt const combined = FormattedString.b("bolded").plain(ctx.msg.text).u("underlined"); await ctx.reply(combined.text, { entities: combined.entities }); await ctx.replyWithPhoto(photo, { caption: combined.caption, caption_entities: combined.caption_entities }); }); bot.start(); ``` -------------------------------- ### Compose Formatted Messages with FormattedString Source: https://github.com/grammyjs/parse-mode/blob/master/README.md Utilize the `FormattedString` class with its chaining methods like `b` (bold) and `u` (underline) to build formatted messages and captions. This example shows replying with text and a photo caption using this alternative approach. ```typescript import { Bot } from "grammy"; import { FormattedString } from "@grammyjs/parse-mode"; const bot = new Bot(""); bot.command("demo", async (ctx) => { // Using return values of Fmt const combined = FormattedString.b("bolded").plain(ctx.msg.text).u( "underlined", ); await ctx.reply(combined.text, { entities: combined.entities }); await ctx.replyWithPhoto(photo, { caption: combined.caption, caption_entities: combined.caption_entities, }); }); bot.start(); ``` -------------------------------- ### Use Tags with Parameters: Links and Code Blocks Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/entity-tags.md Tags that require parameters, such as `a` for links or `pre` for code blocks, use the same tag to close the formatted section after providing the necessary parameter. For example, `a("url")` opens a link, and `a` closes it. ```typescript import { a, pre, fmt } from "@grammyjs/parse-mode"; const link = fmt`${a("https://example.com")}click${a}`; const code = fmt`${pre("python")}print("hello")${pre}`; ``` -------------------------------- ### Custom Emoji MessageEntity Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Example of a 'custom_emoji' type MessageEntity, used for embedding custom emojis. It requires a 'custom_emoji_id'. ```typescript // Custom emoji type const emojiEntity: MessageEntity = { type: "custom_emoji", offset: 0, length: 2, custom_emoji_id: "5321398220249310463" }; ``` -------------------------------- ### Dual Dependencies for Deno and Node.js Source: https://github.com/grammyjs/parse-mode/blob/master/GEMINI.md Illustrates the dual dependency pattern using separate files for Deno and Node.js environments to manage grammY types. ```typescript // deps.deno.ts - Used during Deno development export type { MessageEntity } from "https://lib.deno.dev/x/grammy@^1.36/types.ts"; // deps.node.ts - Used after deno2node transpilation export type { MessageEntity } from "grammy/types"; ``` -------------------------------- ### Combining Multiple Utilities Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/utility-functions.md Demonstrates how to combine various utility functions like `mentionUser` and `linkMessage` within a single formatted string using `fmt`. ```APIDOC ## Combining Multiple Utilities ```typescript import { mentionUser, linkMessage, fmt, b } from "@grammyjs/parse-mode"; const notification = fmt` ${b}New activity:${b} ${mentionUser("User profile", 123456789)} mentioned you in ${linkMessage("this message", -1001234567890, 99)} `; await ctx.reply(notification.text, { entities: notification.entities }); ``` ``` -------------------------------- ### Text Mention MessageEntity Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Example of a 'text_mention' type MessageEntity, used to reference a user within text. It includes a nested 'user' object. ```typescript // Text mention type const mentionEntity: MessageEntity = { type: "text_mention", offset: 0, length: 4, user: { id: 123456789, is_bot: false, first_name: "Alice" } }; ``` -------------------------------- ### Build Process Commands Source: https://github.com/grammyjs/parse-mode/blob/master/AGENTS.md Details the commands for building the project for Node.js compatibility. This includes the `deno task build` command and its equivalent `npm run build` command, both of which delegate to deno2node for transpilation. ```bash # Transpile Deno → Node.js CommonJS den o task build # Equivalent npm command (delegates to deno2node) npm run build ``` -------------------------------- ### Date Time MessageEntity Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Example of a 'date_time' type MessageEntity, used for representing specific dates or times within text. It includes Unix timestamp and format properties. ```typescript // Date time type const dateEntity: MessageEntity = { type: "date_time", offset: 0, length: 10, unix_time: 1700000000, date_time_format: "d" }; ``` -------------------------------- ### Node.js Entry Point Configuration in package.json Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Specifies the main JavaScript file and type definition file for Node.js environments. These point to the compiled output in the 'dist' directory. ```json { "main": "dist/mod.js", "types": "dist/mod.d.ts" } ``` -------------------------------- ### Development Commands with deno task Source: https://github.com/grammyjs/parse-mode/blob/master/AGENTS.md Provides a list of essential development commands using `deno task`. These commands cover formatting, linting, testing, type-checking, building, and cleaning project artifacts. ```bash deno task ok # Format + lint + test + type-check (CI equivalent) deno task test # Run tests only deno task check # Type-check only den o task build # Generate Node.js artifacts in dist/ den o task clean # Remove generated files ``` -------------------------------- ### Essential Development Commands Source: https://github.com/grammyjs/parse-mode/blob/master/GEMINI.md Provides a list of essential commands for developing and validating the project, including full validation, testing, type-checking, and building. ```bash # Full validation (equivalent to CI) den o task ok # Individual operations den o task test # Run test suite den o task check # Type-check source den o task build # Generate Node.js dist/ # Cleanup den o task clean # Remove generated artifacts ``` -------------------------------- ### CaptionWithEntities Interface Usage Example Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/types.md Illustrates how to create a CaptionWithEntities object and use its properties when sending a photo with a caption and entities. ```typescript const caption: CaptionWithEntities = { caption: "Photo description", caption_entities: [ { type: "italic", offset: 0, length: 5 } ] }; await ctx.replyWithPhoto(photo, { caption: caption.caption, caption_entities: caption.caption_entities }); ``` -------------------------------- ### Expandable Blockquote Attribute Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/html-stream-parser.md Use the 'expandable' attribute to make blockquotes collapsible. This example shows how to add an expandable blockquote to the parser. ```html
content
``` ```typescript const parser = new HTMLStreamParser(); parser.add('
Collapsed quote
'); const formatted = parser.toFormattedString(); ``` -------------------------------- ### Catch Exceptions When Calling Telegram API Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/errors.md A general example of catching exceptions when interacting with the Telegram API, specifically during a reply operation. ```typescript try { await ctx.reply(formatted.text, { entities: formatted.entities }); } catch (error) { console.error("Reply failed:", error); } ``` -------------------------------- ### fmt with TextWithEntities Values Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Demonstrates how to include objects with 'text' and 'entities' properties, preserving their defined formatting. ```APIDOC ## TextWithEntities Values Objects with `text` and `entities` properties: ```typescript import { fmt } from "@grammyjs/parse-mode"; const existing = { text: "formatted", entities: [{ type: "bold", offset: 0, length: 10 }] }; const result = fmt`Before: ${existing} After`; ``` ``` -------------------------------- ### Deno and Node.js Dependency Files Source: https://github.com/grammyjs/parse-mode/blob/master/AGENTS.md Illustrates how to manage dependencies for Deno and Node.js environments using separate files. Always import from the Deno version in source files, as deno2node handles the rewrite for Node builds. Use type imports when only importing types. ```typescript // src/deps.deno.ts - Deno imports (URL-based) export type { MessageEntity, User, } from "https://lib.deno.dev/x/grammy@^1.36/types.ts"; // src/deps.node.ts - Node imports (npm package) export type { MessageEntity, User } from "grammy/types"; ``` -------------------------------- ### FormattedString Usage for Bold Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating bold text using FormattedString methods. ```typescript import { bold, fmt, FormattedString } from "@grammyjs/parse-mode"; // Using entity tag const fromFmt = fmt`${bold}bold text${bold}`; // Using static method const fromStatic = FormattedString.bold("bold text"); // Using static method (alias) const fromAlias = FormattedString.b("bold text"); ``` -------------------------------- ### Deno Imports Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Import the library in Deno using the provided URL. ```typescript import { fmt, b } from "https://deno.land/x/grammy_parse_mode/mod.ts"; ``` -------------------------------- ### Find All Occurrences in FormattedString Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Use the `findAll` method to find all occurrences of a FormattedString pattern within another FormattedString. It returns an array of starting indices. ```typescript const text = fmt`${b}bold${b} and ${i}italic${i}`; const boldText = fmt`${b}bold${b}`; const indices = text.findAll(boldText); // Returns [0] ``` -------------------------------- ### Import Conventions for Deno Projects Source: https://github.com/grammyjs/parse-mode/blob/master/GEMINI.md Illustrates correct and incorrect import conventions within a Deno project, emphasizing the use of `deps.deno.ts` and avoiding direct URL imports. ```typescript // ✅ Always import from deps.deno.ts in source import type { MessageEntity } from "./deps.deno.ts"; // ✅ Use type imports for type-only imports import type { User } from "./deps.deno.ts"; // ❌ Never import directly from URLs in non-deps files import { something } from "https://..."; // ❌ Never use Node-specific globals without shimming const dir = __dirname; // Won't work in Deno ``` -------------------------------- ### Node.js CommonJS and ES Modules Imports Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Demonstrates how to import the library in Node.js environments using both CommonJS (`require`) and ES Modules (`import`) syntax. ```javascript // CommonJS const { fmt, b } = require("@grammyjs/parse-mode"); // ES Modules import { fmt, b } from "@grammyjs/parse-mode"; ``` -------------------------------- ### Consolidate Adjacent Bold Entities Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Adjacent or overlapping entities of the same type are automatically consolidated. This example shows how two separate bold entities are merged into a single one. ```typescript import { fmt, b } from "@grammyjs/parse-mode"; // Automatic consolidation const text = fmt`${b}part1${b}${b}part2${b}`; // Results in single bold entity covering both parts ``` -------------------------------- ### Deno Entry Point Exports in src/mod.ts Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md These are the exports from the main module file for Deno. Deno can import directly from the 'src/' directory. ```typescript // src/mod.ts export * from "./entity-tag.ts"; export * from "./format.ts"; export * from "./stream-html-to-format.ts"; ``` -------------------------------- ### Package.json Build Script for @grammyjs/parse-mode Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md This script defines how the library is built using deno2node. The build process is typically automated during 'npm prepare'. ```json { "scripts": { "build": "deno2node tsconfig.json" } } ``` -------------------------------- ### Find Pattern in FormattedString Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Use the `find` method to locate the first occurrence of a FormattedString pattern within another FormattedString. It returns the starting index of the pattern or -1 if not found. ```typescript const text = fmt`${b}bold${b} and ${i}italic${i}`; const boldText = fmt`${b}bold${b}`; const index = text.find(boldText); // Returns 0 ``` -------------------------------- ### Re-export Entry Point for Clean API Source: https://github.com/grammyjs/parse-mode/blob/master/GEMINI.md Demonstrates how the main entry point (`mod.ts`) re-exports core functionalities from other modules to provide a clean public API surface. ```typescript // mod.ts - Clean public API surface export * from "./format.ts"; ``` -------------------------------- ### startsWith(pattern) Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Checks if the FormattedString begins with a specified pattern. ```APIDOC ## startsWith(pattern) ### Description Checks whether this FormattedString starts with the specified pattern. ### Parameters #### Path Parameters - **pattern** (FormattedString) - Required - The pattern to check for ### Returns true if starts with pattern, false otherwise ``` -------------------------------- ### FormattedString Usage for Underline Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating underlined text using FormattedString methods. ```typescript import { fmt, FormattedString, underline } from "@grammyjs/parse-mode"; const fromFmt = fmt`${underline}underline text${underline}`; const fromStatic = FormattedString.underline("underline text"); const fromAlias = FormattedString.u("underline text"); // alias ``` -------------------------------- ### fmt with Plain Strings Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Demonstrates that plain strings passed to the fmt function are inserted without any additional formatting. ```APIDOC ## Plain Strings Plain strings are inserted without formatting: ```typescript import { fmt, b } from "@grammyjs/parse-mode"; const text = fmt`${b}bold${b} and plain text`; ``` ``` -------------------------------- ### Bold Formatting with FormattedString Source: https://github.com/grammyjs/parse-mode/blob/master/docs/MarkdownV2.md Demonstrates three ways to apply bold formatting using the @grammyjs/parse-mode library: with entity tags, static methods, and instance methods. Ensure the library is imported. ```typescript import { bold, fmt, FormattedString } from "@grammyjs/parse-mode"; // Using entity tag const fromFmt = fmt`${bold}bold text${bold}`; // Using static method const fromStatic = FormattedString.bold("bold text"); // Using instance method const fromInstance = new FormattedString("").bold("bold text"); ``` -------------------------------- ### pre(language?) Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/entity-tags.md Creates a code block (pre) entity tag with an optional language specification for syntax highlighting. This format cannot be combined with any other formats. ```APIDOC ## pre(language?) ### Description Creates a code block (pre) entity tag with optional language specification for syntax highlighting. Cannot be combined with any other formats. ### Method Signature ```typescript function pre(language?: string): EntityTag ``` ### Parameters #### Path Parameters - **language** (string) - Optional - The programming language for syntax highlighting. Defaults to `undefined`. ### Returns EntityTag with type "pre" and optional language ### Example ```typescript import { pre, fmt } from "@grammyjs/parse-mode"; const js = fmt`${pre("javascript")}console.log('hello');${pre}`; const plain = fmt`${pre()}plain code${pre}`; ``` ``` -------------------------------- ### Basic Usage of @grammyjs/parse-mode Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Import and use the formatting functions directly. No initialization or configuration is needed before using the library's features. ```typescript import { fmt, b, i, FormattedString, HTMLStreamParser } from "@grammyjs/parse-mode"; // Ready to use immediately - no configuration needed const message = fmt`${b}hello${b}`; ``` -------------------------------- ### FormattedString Usage for User Mention Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating user mentions using FormattedString methods. ```typescript import { FormattedString, mentionUser } from "@grammyjs/parse-mode"; const fromFunc = mentionUser("user name", 123456789); const fromStatic = FormattedString.mentionUser("user name", 123456789); ``` -------------------------------- ### Basic Usage of fmt Tagged Template Literal Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Demonstrates the basic usage of the fmt tagged template literal for creating bold, italic, and combined formatted text. ```typescript import { fmt, b, i, u } from "@grammyjs/parse-mode"; const bold = fmt`${b}bold text${b}`; const italic = fmt`${i}italic text${i}`; const combined = fmt`${b}bold${b} and ${i}italic${i}`; ``` -------------------------------- ### HTML Syntax for User Mention Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Shows the HTML tag used to create a link to a user profile. ```html user name ``` -------------------------------- ### Runtime-Specific Code Implementation Source: https://github.com/grammyjs/parse-mode/blob/master/AGENTS.md Demonstrates how to implement different code versions for Deno and Node.js. The consumer file imports from the Deno-specific file, and deno2node automatically rewrites this import for Node builds. ```typescript // feature.deno.ts - Deno-specific implementation export function doSomething() {/* uses Deno APIs */} // feature.node.ts - Node-specific implementation export function doSomething() {/* uses Node APIs */} // consumer.ts - imports the Deno version import { doSomething } from "./feature.deno.ts"; // deno2node rewrites this to "./feature.node.ts" for Node builds ``` -------------------------------- ### FormattedString.pre Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Creates a code block formatted string with optional syntax highlighting. ```APIDOC ## FormattedString.pre ### Description Creates a code block formatted string with optional syntax highlighting. ### Method static pre(text: Stringable, language?: string): FormattedString ### Parameters #### Path Parameters - **text** (Stringable) - Required - The text content to format as a code block - **language** (string) - Optional - The programming language for syntax highlighting ### Response FormattedString with pre formatting ### Example ```typescript const codeBlock = FormattedString.pre("console.log('hello')", "javascript"); ``` ``` -------------------------------- ### Create a Code Block Entity Tag (pre) Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/entity-tags.md Use the `pre()` function to create a code block entity tag. An optional language parameter can be provided for syntax highlighting. This format cannot be combined with any other formats. ```typescript import { pre, fmt } from "@grammyjs/parse-mode"; const js = fmt`${pre("javascript")}console.log('hello');${pre}`; const plain = fmt`${pre()}plain code${pre}`; ``` -------------------------------- ### FormattedString Usage for Pre-formatted Code Block Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating pre-formatted code blocks with or without a language using FormattedString. ```typescript import { fmt, FormattedString, pre } from "@grammyjs/parse-mode"; // Without language const fromFmt = fmt`${pre()}pre-formatted code${pre}`; // With language const fromFmtLang = fmt`${pre("python")}print("Hello")${pre}`; const fromStatic = FormattedString.pre('print("Hello")', "python"); ``` -------------------------------- ### Strikethrough Formatting with FormattedString Source: https://github.com/grammyjs/parse-mode/blob/master/docs/MarkdownV2.md Demonstrates how to achieve strikethrough formatting using entity tags, static methods, or instance methods from the @grammyjs/parse-mode library. Imports are necessary. ```typescript import { fmt, FormattedString, strikethrough } from "@grammyjs/parse-mode"; const fromFmt = fmt`${strikethrough}strikethrough text${strikethrough}`; const fromStatic = FormattedString.strikethrough("strikethrough text"); ``` -------------------------------- ### Bold Formatting Source: https://github.com/grammyjs/parse-mode/blob/master/docs/MarkdownV2.md Details on how to format text as bold using MarkdownV2 syntax and the @grammyjs/parse-mode library. ```APIDOC ### Bold **Syntax:** `*bold text*` **MessageEntity:** ```json { "type": "bold", "offset": 0, "length": 9 } ``` **FormattedString Usage:** ```typescript import { bold, fmt, FormattedString } from "@grammyjs/parse-mode"; // Using entity tag const fromFmt = fmt`${bold}bold text${bold}`; // Using static method const fromStatic = FormattedString.bold("bold text"); // Using instance method const fromInstance = new FormattedString("").bold("bold text"); ``` ``` -------------------------------- ### CI/CD Checks with Deno Source: https://github.com/grammyjs/parse-mode/blob/master/AGENTS.md GitHub Actions run these checks on all pull requests. Always run `deno task ok` locally before pushing. ```yaml - deno lint # Linting - deno fmt --check # Formatting - deno task check # Type-checking - deno test --allow-import test # Tests ``` -------------------------------- ### fmt with Stringable Values Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Illustrates how the fmt function handles Stringable objects, which have a `toString()` method, by converting them to strings. ```APIDOC ## Stringable Values Any object implementing the `Stringable` interface (with a `toString()` method): ```typescript import { fmt, b } from "@grammyjs/parse-mode"; const obj = { toString() { return "stringable"; } }; const result = fmt`${b}${obj}${b}`; ``` ``` -------------------------------- ### Test File Organization and Structure Source: https://github.com/grammyjs/parse-mode/blob/master/AGENTS.md Shows the standard organization for test files, including imports from local dependencies and the use of `describe` and `it` blocks for structuring tests. It's critical to test entity offsets and lengths explicitly. ```typescript // test/format.featurename.test.ts import { assertEquals, describe, it } from "./deps.test.ts"; import { FormattedString } from "../src/format.ts"; import type { MessageEntity } from "../src/deps.deno.ts"; describe("FormattedString - Feature Name", () => { describe("Subfeature", () => { it("should do something specific", () => { // Arrange const input = new FormattedString("text", []); // Act const result = input.someMethod(); // Assert assertEquals(result.rawText, "expected"); assertEquals(result.rawEntities.length, 1); }); }); }); ``` -------------------------------- ### FormattedString.b Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Creates a **bold** formatted string. This is a shorthand for the `bold` method. ```APIDOC ## FormattedString.b ### Description Creates a **bold** formatted string. ### Method static b(text: Stringable): FormattedString ### Parameters #### Path Parameters - **text** (Stringable) - Required - The text content to format as bold ### Response FormattedString with bold formatting ### Example ```typescript const bold = FormattedString.b("bold text"); ``` ``` -------------------------------- ### Individual Imports Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Import specific functions like `fmt`, `b`, and `i` when you only need a few utilities from the library. ```typescript // Only import what you need import { fmt, b, i } from "@grammyjs/parse-mode"; ``` -------------------------------- ### Automatic Entity Consolidation with fmt Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/internal-utilities.md Demonstrates how `fmt` automatically consolidates adjacent or overlapping entities of the same type, simplifying the process of creating formatted text. ```typescript import { fmt, b } from "@grammyjs/parse-mode"; // Automatically consolidated by fmt const text = fmt`${b}part1${b}${b}part2${b}`; // The two bold entities are consolidated into one ``` -------------------------------- ### Create Hyperlinks and User Mentions Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/README.md Generate hyperlinks using the `a` tag within the `fmt` template literal. Create user mentions with `mentionUser`, providing the display text and the user's ID. ```typescript import { fmt, a, mentionUser } from "@grammyjs/parse-mode"; // Hyperlinks const link = fmt`${a("https://example.com")}click here${a}`; // User mentions const mention = mentionUser("@alice", 123456789); ``` -------------------------------- ### Create HTMLStreamParser Instance Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/html-stream-parser.md Instantiate the HTMLStreamParser to begin parsing HTML-formatted text. This parser maintains internal state for incremental processing. ```typescript import { HTMLStreamParser } from "@grammyjs/parse-mode"; const parser = new HTMLStreamParser(); parser.add("bold"); const formatted = parser.toFormattedString(); ``` -------------------------------- ### Classes Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/INDEX.md Core classes for working with formatted text and parsing HTML. ```APIDOC ## Classes ### Description These classes are fundamental for managing and processing formatted text within the library. ### Classes - **FormattedString**: The main class for creating, manipulating, and working with formatted text and its associated entities. - **HTMLStreamParser**: A parser designed to process HTML-style formatted text, converting it into a structured format suitable for Telegram. ``` -------------------------------- ### Underline Formatting with FormattedString Source: https://github.com/grammyjs/parse-mode/blob/master/docs/MarkdownV2.md Illustrates applying underline formatting through entity tags, static methods, or instance methods provided by the @grammyjs/parse-mode library. Make sure to import necessary components. ```typescript import { fmt, FormattedString, underline } from "@grammyjs/parse-mode"; const fromFmt = fmt`${underline}underline text${underline}`; const fromStatic = FormattedString.underline("underline text"); ``` -------------------------------- ### Underline Formatting Source: https://github.com/grammyjs/parse-mode/blob/master/docs/MarkdownV2.md Details on how to format text as underlined using MarkdownV2 syntax and the @grammyjs/parse-mode library. ```APIDOC ### Underline **Syntax:** `__underline text__` **MessageEntity:** ```json { "type": "underline", "offset": 0, "length": 14 } ``` **FormattedString Usage:** ```typescript import { fmt, FormattedString, underline } from "@grammyjs/parse-mode"; const fromFmt = fmt`${underline}underline text${underline}`; const fromStatic = FormattedString.underline("underline text"); ``` ``` -------------------------------- ### Building Dynamic User Mentions Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/utility-functions.md Creates a formatted string of user mentions from a list of users. Each user is mentioned using their name and ID. ```typescript import { mentionUser, fmt } from "@grammyjs/parse-mode"; function buildUserList(users: { name: string; id: number }[]): FormattedString { const items = users.map(u => mentionUser(u.name, u.id)); return FormattedString.join(items, ", "); } const users = [ { name: "Alice", id: 111 }, { name: "Bob", id: 222 } ]; const message = fmt`Users: ${buildUserList(users)}`; ``` -------------------------------- ### Using Entity Tags with fmt Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Shows how to use entity tags like b(), i() to mark the beginning and end of formatting regions within a formatted string. ```typescript import { fmt, b, i } from "@grammyjs/parse-mode"; const text = fmt`${b}bold${b} normal ${i}italic${i}`; // "bold" is bold, "normal" is plain, "italic" is italic ``` -------------------------------- ### a(url) Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/entity-tags.md Creates a hyperlink entity tag. This is an alias for the `link()` function and is incompatible with `code` and `pre` tags. ```APIDOC ## a(url) ### Description Creates a hyperlink entity tag. Alias for `link()`. Incompatible with `code` and `pre`. ### Method Signature ```typescript function a(url: string): EntityTag ``` ### Parameters #### Path Parameters - **url** (string) - Required - The URL to link to ### Returns EntityTag with type "text_link" and the specified URL ### Example ```typescript import { a, fmt } from "@grammyjs/parse-mode"; const text = fmt`${a("https://example.com")}click here${a}`; ``` ``` -------------------------------- ### FormattedString Usage for Text Link Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating text links using FormattedString methods, including an alias. ```typescript import { fmt, FormattedString, link } from "@grammyjs/parse-mode"; const fromFmt = fmt`${link("https://example.com")}link text${link}`; const fromStatic = FormattedString.link("link text", "https://example.com"); const fromAlias = FormattedString.a("link text", "https://example.com"); // alias ``` -------------------------------- ### Nested Formatting with @grammyjs/parse-mode Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Shows how to create nested formatted text using the fmt template tag and helper functions from @grammyjs/parse-mode. ```typescript import { bold, fmt, italic, underline } from "@grammyjs/parse-mode"; // Bold italic text const boldItalic = fmt`${bold}${italic}bold and italic${italic}${bold}`; // Underlined bold text const underlinedBold = fmt`${underline}${bold}underlined bold${bold}${underline}`; ``` -------------------------------- ### FormattedString Usage for Inline Code Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating inline code using FormattedString methods. Note that code entities cannot be combined with other formatting. ```typescript import { code, fmt, FormattedString } from "@grammyjs/parse-mode"; const fromFmt = fmt`${code}inline code${code}`; const fromStatic = FormattedString.code("inline code"); ``` -------------------------------- ### HTML Syntax for Pre-formatted Code Block Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Shows HTML syntax for pre-formatted code blocks, with and without a specified language. ```html
pre-formatted code
``` ```html
print("Hello")
``` -------------------------------- ### Link Tag Usage Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/html-stream-parser.md Demonstrates how to use the `` tag with an `href` attribute to create a hyperlink. The `href` attribute is required. ```typescript const parser = new HTMLStreamParser(); parser.add('click here'); const formatted = parser.toFormattedString(); ``` -------------------------------- ### FormattedString Constructor Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Creates a new FormattedString instance with the specified text and optional formatting entities. This is the primary way to instantiate the class. ```APIDOC ## Constructor FormattedString ### Description Creates a new `FormattedString` instance with the specified text and optional formatting entities. ### Method ```typescript constructor(public rawText: string, rawEntities?: MessageEntity[]) ``` ### Parameters #### Path Parameters - **rawText** (string) - Required - The plain text content. - **rawEntities** (MessageEntity[]) - Optional - Array of formatting entities that apply to the text. ### Response Returns: FormattedString instance ### Request Example ```typescript import { FormattedString } from "@grammyjs/parse-mode"; const formatted = new FormattedString("Hello world!", [ { type: "bold", offset: 0, length: 5 }, { type: "italic", offset: 6, length: 5 } ]); ``` ``` -------------------------------- ### FormattedString.strikethrough Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Creates a ~~strikethrough~~ formatted string. This is the full name version of the `s` method. ```APIDOC ## FormattedString.strikethrough ### Description Creates a ~~strikethrough~~ formatted string (full name version). ### Method static strikethrough(text: Stringable): FormattedString ``` -------------------------------- ### fmt with CaptionWithEntities Values Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Shows how to incorporate objects containing 'caption' and 'caption_entities' for formatted captions. ```APIDOC ## CaptionWithEntities Values Objects with `caption` and `caption_entities` properties: ```typescript import { fmt } from "@grammyjs/parse-mode"; const caption = { caption: "photo description", caption_entities: [{ type: "italic", offset: 0, length: 5 }] }; const result = fmt`Caption: ${caption}`; ``` ``` -------------------------------- ### fmt with FormattedString Values Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/fmt-function.md Illustrates embedding existing FormattedString instances into a new formatted string, preserving their original formatting. ```APIDOC ## FormattedString Values Existing `FormattedString` instances are embedded with their entities preserved: ```typescript import { fmt, FormattedString } from "@grammyjs/parse-mode"; const bold = FormattedString.b("bold part"); const combined = fmt`${bold} and plain text`; // "bold part" keeps bold formatting, "and plain text" is plain ``` ``` -------------------------------- ### Named Imports vs. Default Export Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/configuration.md Illustrates the correct way to import functions from the library using named imports. The library does not provide a default export. ```typescript // Correct import { fmt, b } from "@grammyjs/parse-mode"; // Incorrect (no default export) import parseMode from "@grammyjs/parse-mode"; // ❌ ``` -------------------------------- ### FormattedString.bold Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Creates a **bold** formatted string. This is the full name version of the `b` method. ```APIDOC ## FormattedString.bold ### Description Creates a **bold** formatted string (full name version). ### Method static bold(text: Stringable): FormattedString ``` -------------------------------- ### FormattedString Usage for Strikethrough Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating strikethrough text using FormattedString methods. ```typescript import { fmt, FormattedString, strikethrough } from "@grammyjs/parse-mode"; const fromFmt = fmt`${strikethrough}strikethrough text${strikethrough}`; const fromStatic = FormattedString.strikethrough("strikethrough text"); const fromAlias = FormattedString.s("strikethrough text"); // alias ``` -------------------------------- ### FormattedString.u Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/formatted-string.md Creates an underline formatted string. This is a shorthand for the `underline` method. ```APIDOC ## FormattedString.u ### Description Creates an underline formatted string. ### Method static u(text: Stringable): FormattedString ``` -------------------------------- ### Provide Fallback Text Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/errors.md Illustrates creating a safe formatted string, falling back to the original user input if formatting fails or results in an empty string. ```typescript const safe = safeFormat(userInput) || new FormattedString(userInput); ``` -------------------------------- ### FormattedString Usage for Italic Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Demonstrates creating italic text using FormattedString methods. ```typescript import { fmt, FormattedString, italic } from "@grammyjs/parse-mode"; const fromFmt = fmt`${italic}italic text${italic}`; const fromStatic = FormattedString.italic("italic text"); const fromAlias = FormattedString.i("italic text"); // alias ``` -------------------------------- ### Pre-formatted Code Snippet Source: https://github.com/grammyjs/parse-mode/blob/master/docs/MarkdownV2.md Use this to format code blocks. Specify the language for syntax highlighting. Pre entities cannot be combined with other formatting. ```plaintext pre-formatted code ``` ```python print("Hello") ``` ```json { "type": "pre", "offset": 0, "length": 18 } ``` ```json { "type": "pre", "offset": 0, "length": 14, "language": "python" } ``` ```typescript import { fmt, FormattedString, pre } from "@grammyjs/parse-mode"; // Without language const fromFmt = fmt`${pre()}pre-formatted code${pre}`; // With language const fromFmtLang = fmt`${pre("python")}print("Hello")${pre}`; const fromStatic = FormattedString.pre('print("Hello")', "python"); ``` -------------------------------- ### Create a Hyperlink Entity Tag (link) Source: https://github.com/grammyjs/parse-mode/blob/master/_autodocs/api-reference/entity-tags.md Use the `link()` function to create a hyperlink entity tag. This is the full name version of `a()`. ```typescript function link(url: string): EntityTag ``` -------------------------------- ### HTML Syntax for Inline Code Source: https://github.com/grammyjs/parse-mode/blob/master/docs/HTML.md Shows the HTML tag used to format text as inline code. ```html inline code ```