@effect/chat-telegram 0.0.0-stage → 4.1.5

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.
Files changed (157) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +121 -2
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/TelegramBotApi.d.ts +153 -0
  88. package/dist/TelegramBotApi.d.ts.map +1 -0
  89. package/dist/TelegramBotApi.js +219 -0
  90. package/dist/TelegramBotApi.js.map +1 -0
  91. package/dist/TelegramChat.d.ts +390 -0
  92. package/dist/TelegramChat.d.ts.map +1 -0
  93. package/dist/TelegramChat.js +359 -0
  94. package/dist/TelegramChat.js.map +1 -0
  95. package/dist/index.d.ts +15 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +16 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/internal/actions.d.ts +2 -0
  100. package/dist/internal/actions.d.ts.map +1 -0
  101. package/dist/internal/actions.js +88 -0
  102. package/dist/internal/actions.js.map +1 -0
  103. package/dist/internal/adapter.d.ts +2 -0
  104. package/dist/internal/adapter.d.ts.map +1 -0
  105. package/dist/internal/adapter.js +309 -0
  106. package/dist/internal/adapter.js.map +1 -0
  107. package/dist/internal/address.d.ts +2 -0
  108. package/dist/internal/address.d.ts.map +1 -0
  109. package/dist/internal/address.js +26 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/commands.d.ts +2 -0
  112. package/dist/internal/commands.d.ts.map +1 -0
  113. package/dist/internal/commands.js +30 -0
  114. package/dist/internal/commands.js.map +1 -0
  115. package/dist/internal/errors.d.ts +2 -0
  116. package/dist/internal/errors.d.ts.map +1 -0
  117. package/dist/internal/errors.js +136 -0
  118. package/dist/internal/errors.js.map +1 -0
  119. package/dist/internal/markdown.d.ts +9 -0
  120. package/dist/internal/markdown.d.ts.map +1 -0
  121. package/dist/internal/markdown.js +708 -0
  122. package/dist/internal/markdown.js.map +1 -0
  123. package/dist/internal/normalize.d.ts +2 -0
  124. package/dist/internal/normalize.d.ts.map +1 -0
  125. package/dist/internal/normalize.js +276 -0
  126. package/dist/internal/normalize.js.map +1 -0
  127. package/dist/internal/options.d.ts +2 -0
  128. package/dist/internal/options.d.ts.map +1 -0
  129. package/dist/internal/options.js +6 -0
  130. package/dist/internal/options.js.map +1 -0
  131. package/dist/internal/polling.d.ts +2 -0
  132. package/dist/internal/polling.d.ts.map +1 -0
  133. package/dist/internal/polling.js +68 -0
  134. package/dist/internal/polling.js.map +1 -0
  135. package/dist/internal/receive.d.ts +2 -0
  136. package/dist/internal/receive.d.ts.map +1 -0
  137. package/dist/internal/receive.js +183 -0
  138. package/dist/internal/receive.js.map +1 -0
  139. package/dist/internal/webhook.d.ts +2 -0
  140. package/dist/internal/webhook.d.ts.map +1 -0
  141. package/dist/internal/webhook.js +61 -0
  142. package/dist/internal/webhook.js.map +1 -0
  143. package/package.json +62 -3
  144. package/src/TelegramBotApi.ts +282 -0
  145. package/src/TelegramChat.ts +542 -0
  146. package/src/index.ts +18 -0
  147. package/src/internal/actions.ts +95 -0
  148. package/src/internal/adapter.ts +319 -0
  149. package/src/internal/address.ts +33 -0
  150. package/src/internal/commands.ts +37 -0
  151. package/src/internal/errors.ts +148 -0
  152. package/src/internal/markdown.ts +805 -0
  153. package/src/internal/normalize.ts +283 -0
  154. package/src/internal/options.ts +12 -0
  155. package/src/internal/polling.ts +86 -0
  156. package/src/internal/receive.ts +268 -0
  157. package/src/internal/webhook.ts +85 -0
@@ -0,0 +1,708 @@
1
+ /**
2
+ * Rich Markdown for `sendRichMessage`: the escaping that keeps consumer
3
+ * Markdown from reaching Telegram's raw HTML, images, math, spoilers and
4
+ * non-web links, and the `measure` that bounds what it costs.
5
+ *
6
+ * @internal
7
+ */
8
+ /** What one line break or block marker costs, so that a message in budget stays under 500 blocks. @internal */
9
+ export const block = 65;
10
+ /** Telegram's rich message limit. It counts rendered characters, which UTF-8 bytes of the source bound. @internal */
11
+ export const richLimit = 32_768;
12
+ /** Files one post may carry. @internal */
13
+ export const filesPerMessage = 10;
14
+ /** The most nesting and table columns Telegram renders. @internal */
15
+ export const maxDepth = 16;
16
+ /** @internal */
17
+ export const maxColumns = 20;
18
+ /** The reference to the `n`th file of a post, at the end of the Markdown. @internal */
19
+ export const mediaReference = n => `\n\n![](tg://document?id=f${n})`;
20
+ /**
21
+ * What the budget keeps back for media references and the fence a post
22
+ * with files may need to close: each reference's bytes and its block, one
23
+ * block for the message's first, which `measure` does not charge, and 8
24
+ * bytes for the fence.
25
+ *
26
+ * @internal
27
+ */
28
+ export const reservation = filesPerMessage * (32 + block) + block + 8;
29
+ /** @internal */
30
+ export const messageLength = richLimit - reservation;
31
+ const twoByteEscapes = /*#__PURE__*/new Set(["$", "=", "|", "!", "[", "]", "*", "_", "~", "`"]);
32
+ const blockMarkers = /*#__PURE__*/new Set([">", "-", "+", "*", ".", ")"]);
33
+ const isDigit = c => c >= "0" && c <= "9";
34
+ /**
35
+ * A sum of per-character costs, each fixed or depending only on what comes
36
+ * before the character on its own line, which makes it subadditive:
37
+ *
38
+ * - a code point in the Basic Multilingual Plane costs its UTF-8 length,
39
+ * and each UTF-16 surrogate 3, enough for the U+FFFD a lone one becomes.
40
+ * NUL costs 3 too, as Markdown turns it into U+FFFD.
41
+ * - `<` costs 4, a backslash 5 (the numeric reference, such as `&#93;`,
42
+ * that an escape Telegram ignores becomes), and
43
+ * `$ = | ! [ ] * _ ~` and the backtick 2, their escaped length or more,
44
+ * whether or not they are escaped in context.
45
+ * - `\n` and `\r` cost `block`, as does a block marker (`>`, a bullet,
46
+ * the dot or parenthesis of a number) before any other text on its line.
47
+ *
48
+ * @internal
49
+ */
50
+ export const measure = markdown => {
51
+ let cost = 0;
52
+ let prefix = true;
53
+ for (let i = 0; i < markdown.length; i++) {
54
+ const code = markdown.charCodeAt(i);
55
+ if (code === 10 || code === 13) {
56
+ cost += block;
57
+ prefix = true;
58
+ continue;
59
+ }
60
+ if (code >= 0xd800 && code <= 0xdfff) {
61
+ cost += 3;
62
+ prefix = false;
63
+ continue;
64
+ }
65
+ const c = markdown[i];
66
+ if (prefix) {
67
+ if (c === " " || c === "\t" || isDigit(c)) {
68
+ cost += 1;
69
+ continue;
70
+ }
71
+ if (blockMarkers.has(c)) {
72
+ cost += block;
73
+ continue;
74
+ }
75
+ prefix = false;
76
+ }
77
+ cost += c === "\\" ? 5 : code === 0 ? 3 : c === "<" ? 4 : twoByteEscapes.has(c) ? 2 : code < 0x80 ? 1 : code < 0x800 ? 2 : 3;
78
+ }
79
+ return cost;
80
+ };
81
+ const punctuation = /[!-/:-@[-`{-~]/;
82
+ /** A line that opens a fence: up to three spaces, then three or more backticks or tildes. */
83
+ const fenceOpen = /^( {0,3})(`{3,}|~{3,})(.*)$/;
84
+ const opens = line => {
85
+ const match = fenceOpen.exec(line);
86
+ if (match === null || match[2][0] === "`" && match[3].includes("`")) return undefined;
87
+ return {
88
+ char: match[2][0],
89
+ length: match[2].length,
90
+ indent: match[1].length
91
+ };
92
+ };
93
+ const closes = (line, fence) => {
94
+ const match = /^ {0,3}(`+|~+)[ \t]*$/.exec(line);
95
+ return match !== null && match[1][0] === fence.char && match[1].length >= fence.length;
96
+ };
97
+ /** A line that may open a list item or footnote, which an indented fence could belong to. */
98
+ const container = /^[ \t>]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)|^[ \t>]*\[\^/;
99
+ /** A line GFM may read as the start of another block, which ends a table and is no paragraph. */
100
+ const blockStart = /^(?: {0,3}[#>\-*+_~`<=[]| {0,3}\d{1,9}[.)]| {4}| {0,3}\t)/;
101
+ /** Where a line's container markers end, as far as `startsBlock` needs to know. */
102
+ const quotes = /^(?: {0,3}> ?)* {0,3}/;
103
+ /**
104
+ * Whether a line starts a block wherever it is, so that it can be no
105
+ * paragraph's continuation: an ATX heading, or a list item with content
106
+ * that may interrupt a paragraph (a bullet, or an ordered item numbered 1
107
+ * or following one of its list). Tabs and other lines say no, which is
108
+ * safe: the inline count goes on.
109
+ */
110
+ const startsBlock = (line, previousItem) => {
111
+ const rest = line.slice(quotes.exec(line)[0].length);
112
+ if (/^(?:#{1,6}(?: |$)|[-+*] +\S)/.test(rest)) return true;
113
+ const item = /^(\d{1,9})([.)]) +\S/.exec(rest);
114
+ if (item === null) return undefined;
115
+ const key = line.slice(0, line.length - rest.length) + item[2];
116
+ return item[1] === "1" || key === previousItem ? key : undefined;
117
+ };
118
+ const delimiterRow = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
119
+ /** The cells of a table row, split at unescaped pipes as GFM does, even inside code. */
120
+ const cellCount = line => {
121
+ let count = 1;
122
+ for (let i = 0; i < line.length; i++) {
123
+ if (line[i] === "\\") i++;else if (line[i] === "|") count++;
124
+ }
125
+ const trimmed = line.trim();
126
+ if (trimmed.startsWith("|")) count--;
127
+ if (trimmed.length > 1 && trimmed.endsWith("|") && !trimmed.endsWith("\\|")) count--;
128
+ return count;
129
+ };
130
+ /**
131
+ * A blank line as CommonMark defines it: only spaces and tabs. Other
132
+ * whitespace, such as U+00A0, is paragraph text and ends nothing.
133
+ */
134
+ const isBlank = line => /^[ \t]*$/.test(line);
135
+ /** Whether a line can head a table: GFM reads no cell in a lone `|`. */
136
+ const hasPipe = line => (cellCount(line) > 1 || line.trim().startsWith("|")) && line.trim() !== "|";
137
+ /** The decoded form of a link destination, as a Markdown parser and then a URL parser read it. */
138
+ const decodeDestination = raw => {
139
+ let unescaped = raw.replace(/\\([!-/:-@[-`{-~])/g, "$1");
140
+ unescaped = unescaped.replace(/&#(\d{1,7});/g, (_, n) => String.fromCodePoint(Math.min(Number(n), 0x10ffff))).replace(/&#[xX]([0-9a-fA-F]{1,6});/g, (_, n) => String.fromCodePoint(Math.min(parseInt(n, 16), 0x10ffff))).replace(/&(amp|lt|gt|quot|apos);/g, (_, name) => name === "amp" ? "&" : name === "lt" ? "<" : name === "gt" ? ">" : name === "quot" ? "\"" : "'");
141
+ // Any other named reference could be one of HTML's many, such as `&colon;`.
142
+ if (/&[A-Za-z][A-Za-z0-9]*;/.test(unescaped)) return undefined;
143
+ try {
144
+ return {
145
+ unescaped,
146
+ decoded: decodeURIComponent(unescaped)
147
+ };
148
+ } catch {
149
+ return undefined;
150
+ }
151
+ };
152
+ const allowedScheme = /^(?:https?:\/\/|mailto:)/i;
153
+ /** Whether a link to `raw` may stay: http, https and mailto, or a mention the post allows. */
154
+ const allowedDestination = (raw, mentions) => {
155
+ const destination = decodeDestination(raw);
156
+ if (destination === undefined) return false;
157
+ if (allowedScheme.test(destination.unescaped) && allowedScheme.test(destination.decoded)) return true;
158
+ const mention = /^tg:\/\/user\?id=(\d{1,20})$/.exec(destination.decoded);
159
+ return mention !== null && destination.unescaped === destination.decoded && mentions.has(mention[1]);
160
+ };
161
+ const blank = c => c === " " || c === "\t";
162
+ /**
163
+ * The deepest parentheses a kept destination may nest. CommonMark lets a
164
+ * parser refuse deeper ones once it supports three, and GFM refuses past
165
+ * 32 in a link, which would leave the rest of the link as Markdown.
166
+ */
167
+ const maxDestinationDepth = 3;
168
+ /**
169
+ * The destination and optional title from `start`, as CommonMark reads
170
+ * them when they are on this line: a destination not in angle brackets, up
171
+ * to a space, a control character or a `)` it did not open, with its
172
+ * parentheses balanced and at most three deep, then a title after a space. `end` is past the
173
+ * title and the blanks after it.
174
+ */
175
+ const destinationAndTitle = (line, start) => {
176
+ let i = start;
177
+ while (blank(line[i])) i++;
178
+ if (line[i] === "<") return undefined;
179
+ const from = i;
180
+ let depth = 0;
181
+ for (; i < line.length; i++) {
182
+ const c = line[i];
183
+ if (c === "\\" && punctuation.test(line[i + 1] ?? "")) {
184
+ i++;
185
+ continue;
186
+ }
187
+ const code = c.charCodeAt(0);
188
+ if (code <= 0x20 || code === 0x7f) break;
189
+ if (c === "(") {
190
+ if (++depth > maxDestinationDepth) return undefined;
191
+ } else if (c === ")") {
192
+ if (depth === 0) break;
193
+ depth--;
194
+ }
195
+ }
196
+ if (depth > 0) return undefined;
197
+ const destination = line.slice(from, i);
198
+ const spaced = blank(line[i]);
199
+ while (blank(line[i])) i++;
200
+ const open = line[i];
201
+ if (spaced && (open === "\"" || open === "'" || open === "(")) {
202
+ const close = open === "(" ? ")" : open;
203
+ for (i++; i < line.length && line[i] !== close; i++) {
204
+ if (line[i] === "\\" && punctuation.test(line[i + 1] ?? "")) i++;else if (open === "(" && line[i] === "(") return undefined;
205
+ }
206
+ if (i >= line.length) return undefined;
207
+ i++;
208
+ while (blank(line[i])) i++;
209
+ }
210
+ return {
211
+ destination,
212
+ end: i
213
+ };
214
+ };
215
+ /**
216
+ * A link's `(destination "title")` from the `(` at `start`, when all of it
217
+ * is on this line. A tail that goes on to the next line, as CommonMark
218
+ * allows, is not one: the link is then refused.
219
+ */
220
+ const linkTail = (line, start) => {
221
+ const tail = destinationAndTitle(line, start + 1);
222
+ return tail !== undefined && line[tail.end] === ")" ? {
223
+ destination: tail.destination,
224
+ end: tail.end + 1
225
+ } : undefined;
226
+ };
227
+ /**
228
+ * The punctuation whose backslash escape Telegram honors. Before any other
229
+ * punctuation the backslash stays as text and the character is read as
230
+ * syntax: `\<b>` is bold. `\]` hides the bracket from emphasis but still
231
+ * closes a link or a definition label, so it is not here either.
232
+ */
233
+ const honored = /*#__PURE__*/new Set("!#$()*+-.=>[\\_`{|}~");
234
+ /** A consumer's escape of `c` as Telegram reads it: kept, or a numeric character reference. */
235
+ const escapeOf = c => honored.has(c) ? "\\" + c : `&#${c.charCodeAt(0)};`;
236
+ /**
237
+ * A kept destination as Telegram needs it. Telegram reads a destination
238
+ * verbatim, with no escapes, so they are decoded, a parenthesis or
239
+ * backslash percent-encoded, and a `<` too, which would end the link.
240
+ */
241
+ const destinationOf = raw => raw.replace(/\\([!-/:-@[-`{-~])|</g, (match, escaped) => {
242
+ const c = escaped ?? match;
243
+ return percentEncoded[c] ?? c;
244
+ });
245
+ const percentEncoded = {
246
+ "(": "%28",
247
+ ")": "%29",
248
+ "\\": "%5C",
249
+ "<": "%3C",
250
+ ">": "%3E"
251
+ };
252
+ /**
253
+ * The destination of a reference definition after `]:`, when the rest of
254
+ * the line is a nonempty destination and an optional title. Anything else
255
+ * after it, a title that goes on to the next line, or a destination there,
256
+ * makes it no definition here.
257
+ */
258
+ const definitionDestination = (line, start) => {
259
+ const tail = destinationAndTitle(line, start);
260
+ return tail !== undefined && tail.end === line.length ? tail.destination : undefined;
261
+ };
262
+ /** The most characters CommonMark reads between a label's brackets. */
263
+ const maxLabelLength = 999;
264
+ /**
265
+ * The most characters the renderer can make of a simple label: an escape
266
+ * becomes at most `%5C&lt;`, and each of `$ = | * _ ~` at most two. The
267
+ * label it sends, not the consumer's, must fit in 999.
268
+ */
269
+ const renderedLabelBound = text => {
270
+ let n = 0;
271
+ for (let i = 0; i < text.length; i++) {
272
+ if (text[i] === "\\") {
273
+ n += 7;
274
+ i++;
275
+ } else n += "$=|*_~".includes(text[i]) ? 2 : 1;
276
+ }
277
+ return n;
278
+ };
279
+ /**
280
+ * A label CommonMark and the renderer both close at its first `]`: no
281
+ * other bracket, code span or autolink in it, and no escape at its end.
282
+ */
283
+ const simpleLabel = /^(?:[^\\[\]`<]|\\.)*$/;
284
+ /**
285
+ * The reference definition the line whose first `[` is at `start` may
286
+ * keep: a simple label, not blank, not a footnote's and at most 999
287
+ * characters once rendered, closed by `]:`, then a destination it allows.
288
+ */
289
+ const keptDefinition = (line, start, mentions) => {
290
+ const close = line.indexOf("]", start);
291
+ const text = line.slice(start + 1, close);
292
+ if (close < 0 || line[close + 1] !== ":" || !simpleLabel.test(text) || isBlank(text) || text[0] === "^" || renderedLabelBound(text) > maxLabelLength) return undefined;
293
+ const destination = definitionDestination(line, close + 2);
294
+ return destination !== undefined && allowedDestination(destination, mentions) ? {
295
+ close,
296
+ destination
297
+ } : undefined;
298
+ };
299
+ /**
300
+ * The end of the code span whose opening backticks are at `start`, found as
301
+ * CommonMark finds it: the next run of as many backticks on the line. A
302
+ * run with no partner on the line opens no span: the renderer escapes it,
303
+ * so no span can pair across lines. In a table row a span holding a pipe
304
+ * is refused, since GFM splits cells before it reads code.
305
+ */
306
+ const codeSpanEnd = (line, start, tableRow) => {
307
+ let length = 0;
308
+ while (line[start + length] === "`") length++;
309
+ for (let j = start + length; j < line.length;) {
310
+ if (line[j] !== "`") {
311
+ j++;
312
+ continue;
313
+ }
314
+ let run = 0;
315
+ while (line[j + run] === "`") run++;
316
+ if (run === length) return tableRow && line.slice(start, j).includes("|") ? undefined : j + run;
317
+ j += run;
318
+ }
319
+ return undefined;
320
+ };
321
+ /**
322
+ * Where GFM starts a bare URL link. It runs to the next space, taking
323
+ * backslashes and backticks with it, so inside one an escape is not
324
+ * needed and a backtick opens no span.
325
+ */
326
+ const bareUrl = /^(?:https?:\/\/|www\.)/i;
327
+ /** A thematic break, whose delimiters stand alone. */
328
+ const thematicBreak = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
329
+ const autolink = /^<([A-Za-z][A-Za-z0-9+.-]{1,31}):[^\s<>`\p{Cc}]*>/u;
330
+ /** The inline nodes one paragraph may hold. Telegram refuses a paragraph past about 4,387. @internal */
331
+ export const maxInlineNodes = 4000;
332
+ /** What one footnote reference costs against `maxInlineNodes`: its superscript, anchor and link. */
333
+ const footnoteNodes = 3;
334
+ /** The footnote references one message may hold. Telegram refuses about 774 to one footnote. @internal */
335
+ export const maxFootnoteReferences = 700;
336
+ /**
337
+ * The container markers at the start of a line, with those past the depth
338
+ * limit escaped, and where the line's text starts.
339
+ */
340
+ const renderPrefix = line => {
341
+ let out = "";
342
+ let i = 0;
343
+ let depth = 0;
344
+ let indent = 0;
345
+ for (;;) {
346
+ const space = /^[ \t]*/.exec(line.slice(i))[0];
347
+ indent += space.length;
348
+ out += space;
349
+ i += space.length;
350
+ const marker = /^(?:>|[-+*](?=[ \t]|$)|\d{1,9}[.)](?=[ \t]|$))/.exec(line.slice(i));
351
+ if (marker === null) break;
352
+ depth++;
353
+ const token = marker[0];
354
+ const escape = depth + Math.floor(indent / 2) >= maxDepth;
355
+ out += escape ? token.slice(0, -1) + "\\" + token.slice(-1) : token;
356
+ i += token.length;
357
+ }
358
+ return {
359
+ text: out,
360
+ rest: i,
361
+ depth: depth + Math.floor(indent / 2)
362
+ };
363
+ };
364
+ const renderLine = (line, context) => {
365
+ const prefix = renderPrefix(line);
366
+ // A footnote definition opens a block, so not behind a tab or four
367
+ // spaces: there, after a definition, GFM reads one with a label `^a`.
368
+ const indent = /[ \t]*$/.exec(line.slice(0, prefix.rest))[0];
369
+ const footnote = !indent.includes("\t") && indent.length < 4 && /^\[\^[\w-]+\]:/.test(line.slice(prefix.rest));
370
+ const inline = context.inline;
371
+ inline.containers = Math.max(inline.containers, prefix.depth);
372
+ const limit = Math.max(0, maxDepth - 1 - inline.containers);
373
+ /** Counts `n` inline nodes, or says no when the paragraph has no room left. */
374
+ const node = n => {
375
+ if (inline.nodes + n > maxInlineNodes) return false;
376
+ inline.nodes += n;
377
+ return true;
378
+ };
379
+ // Telegram reads a definition wherever the line's first `[` closes at a
380
+ // `]:`, also past other brackets, code or autolinks, and GFM reads one
381
+ // at the start of a footnote's text. One is kept only where CommonMark
382
+ // reads the same, with a label and destination both accept. Otherwise
383
+ // the line's `[` is escaped before it is read, so no raw destination is
384
+ // sent behind a label that is text.
385
+ const shaped = line[prefix.rest] === "[" && line.includes("]:", footnote ? line.indexOf("]:", prefix.rest) + 2 : prefix.rest);
386
+ const definition = shaped && context.definitions.allowed && prefix.depth === 0 ? keptDefinition(line, prefix.rest, context.mentions) : undefined;
387
+ context.definitions.allowed = false;
388
+ // Where the line's opening `[` is in `out`, while it may close on a later line.
389
+ const label = line[prefix.rest] === "[" ? prefix.text.length : undefined;
390
+ // Where the `[` of a label with no other bracket in it is, until a `]`
391
+ // closes it. Only such a label keeps its destination: around a nested
392
+ // label, a reference or a footnote, whether the outer brackets make a
393
+ // link depends on definitions and on Telegram's precedence, and a raw
394
+ // tail would be read as Markdown.
395
+ let opener;
396
+ // Where each `[` not yet closed on this line is in `out`.
397
+ const unclosed = [];
398
+ let out = prefix.text;
399
+ let urlEnd = -1;
400
+ let i = prefix.rest;
401
+ if (shaped && definition === undefined) {
402
+ out += "\\[";
403
+ i++;
404
+ }
405
+ while (i < line.length) {
406
+ const c = line[i];
407
+ const next = line[i + 1];
408
+ if (i >= urlEnd && bareUrl.test(line.slice(i, i + 8))) {
409
+ urlEnd = i;
410
+ while (urlEnd < line.length && line[urlEnd] !== " " && line[urlEnd] !== "\t") urlEnd++;
411
+ }
412
+ const inUrl = i < urlEnd;
413
+ // In a bare URL a backslash escapes nothing, outside one it does: as
414
+ // `%5C` it is the same character to a browser and inert to both.
415
+ if (c === "\\" && inUrl && next !== undefined && punctuation.test(next)) {
416
+ out += "%5C";
417
+ i++;
418
+ continue;
419
+ }
420
+ if (c === "\\" && next !== undefined && punctuation.test(next)) {
421
+ out += escapeOf(next);
422
+ i += 2;
423
+ continue;
424
+ }
425
+ switch (c) {
426
+ case "`":
427
+ {
428
+ const end = inUrl ? undefined : codeSpanEnd(line, i, context.cells);
429
+ if (end !== undefined && node(1)) {
430
+ out += line.slice(i, end);
431
+ i = end;
432
+ continue;
433
+ }
434
+ while (line[i] === "`") {
435
+ out += "\\`";
436
+ i++;
437
+ }
438
+ continue;
439
+ }
440
+ case "<":
441
+ {
442
+ const match = inUrl ? null : autolink.exec(line.slice(i));
443
+ if (match !== null && /^(?:https?|mailto)$/i.test(match[1]) && node(1)) {
444
+ out += match[0];
445
+ i += match[0].length;
446
+ } else {
447
+ out += "&lt;";
448
+ i++;
449
+ }
450
+ continue;
451
+ }
452
+ case "$":
453
+ out += "\\$";
454
+ i++;
455
+ continue;
456
+ case "=":
457
+ out += context.setext ? "=" : "\\=";
458
+ i++;
459
+ continue;
460
+ case "|":
461
+ out += context.tableRow && !context.widePipes ? "|" : "\\|";
462
+ i++;
463
+ continue;
464
+ case "!":
465
+ out += next === "[" ? "\\!" : "!";
466
+ i++;
467
+ continue;
468
+ case "[":
469
+ // A footnote reference, unless it opens the line's footnote definition.
470
+ if (next === "^" && !(footnote && i === prefix.rest)) {
471
+ if (context.footnotes.count >= maxFootnoteReferences || !node(footnoteNodes)) {
472
+ out += "\\[";
473
+ i++;
474
+ continue;
475
+ }
476
+ context.footnotes.count++;
477
+ opener = undefined;
478
+ } else if (!inUrl) {
479
+ // Each `[` that could open a link or a reference counts as a node.
480
+ if (!node(1)) {
481
+ out += "\\[";
482
+ i++;
483
+ continue;
484
+ }
485
+ opener = i;
486
+ }
487
+ unclosed.push(out.length);
488
+ out += "[";
489
+ i++;
490
+ continue;
491
+ case "]":
492
+ {
493
+ // Telegram closes a link at `]` even when it is escaped, so a refused
494
+ // link loses its `(`. A kept destination is sent verbatim, which is
495
+ // inert only if it is read as one: a link needs an opener on its
496
+ // line, and not `[a][b](…)` or `[a][](…)`, where `[a]` may be the link.
497
+ const plain = opener !== undefined && line[opener - 1] !== "]";
498
+ const labelOpener = opener;
499
+ opener = undefined;
500
+ unclosed.pop();
501
+ if (next === "(") {
502
+ const tail = linkTail(line, i + 1);
503
+ if (plain && tail !== undefined && allowedDestination(tail.destination, context.mentions)) {
504
+ out += "](" + destinationOf(tail.destination) + ")";
505
+ i = tail.end;
506
+ continue;
507
+ }
508
+ out += "]\\(";
509
+ i += 2;
510
+ continue;
511
+ }
512
+ // The `[` at the line's start counted as a node, so it is still a label.
513
+ if (definition !== undefined && i === definition.close && labelOpener === prefix.rest) {
514
+ context.definitions.allowed = true;
515
+ return out + "]: " + destinationOf(definition.destination);
516
+ }
517
+ out += "]";
518
+ i++;
519
+ continue;
520
+ }
521
+ case "*":
522
+ case "_":
523
+ case "~":
524
+ {
525
+ let end = i;
526
+ while (line[end] === c) end++;
527
+ const run = line.slice(i, end);
528
+ const after = line[end];
529
+ const spaced = ch => ch === undefined || ch === " " || ch === "\t";
530
+ // A run with space on both sides is text to CommonMark, but Telegram
531
+ // opens emphasis with it: `2 * 3 * 4` (live check 2).
532
+ if (spaced(i === prefix.rest ? undefined : line[i - 1]) && spaced(after) && !thematicBreak.test(line)) {
533
+ out += run.split("").map(char => "\\" + char).join("");
534
+ i = end;
535
+ continue;
536
+ }
537
+ // A run of n delimiters can open n levels: `***a*b*c*` is three.
538
+ // One followed by a space or the line's end can't open.
539
+ if (!spaced(after)) {
540
+ if (inline.open + run.length > limit) {
541
+ out += run.split("").map(char => "\\" + char).join("");
542
+ i = end;
543
+ continue;
544
+ }
545
+ inline.open += run.length;
546
+ }
547
+ out += run;
548
+ i = end;
549
+ continue;
550
+ }
551
+ default:
552
+ out += c;
553
+ i++;
554
+ }
555
+ }
556
+ // A label left open at the start of a line could close on a later one,
557
+ // as a definition's.
558
+ if (label !== undefined && unclosed[0] === label) out = out.slice(0, label) + "\\" + out.slice(label);
559
+ return out;
560
+ };
561
+ /**
562
+ * Consumer Markdown as rich Markdown that keeps to what `measure` charged:
563
+ *
564
+ * - Fences pass verbatim, as do code spans, which are found left to right
565
+ * as CommonMark finds them. A fence indented by one to three spaces after
566
+ * a list item could belong to it, so from such a fence on nothing is
567
+ * verbatim. Inside a bare URL a backtick opens no span.
568
+ * - `<` becomes `&lt;` unless it opens an http, https or mailto autolink,
569
+ * so there is no raw HTML, also after a bare URL, which would take a
570
+ * backslash with it. `$` and `=` are escaped (math, marks), except `=`
571
+ * under a paragraph of plain top-level lines (a setext heading), as is `|` outside tables
572
+ * (spoilers), and `!` before `[` (images).
573
+ * - A backslash escape Telegram ignores becomes a numeric character
574
+ * reference, so `\<` is no HTML and `\]` closes no link.
575
+ * - A link or reference definition whose destination, decoded as a
576
+ * Markdown parser and then a URL parser would, is not http, https or
577
+ * mailto is text: a link loses its `(`, a definition its opening `[`.
578
+ * A `tg://user` link stays for an id in `mentions`. A kept link needs its
579
+ * `[` and its whole tail on its line, a label with no other bracket in
580
+ * it, and no `]` right before it. A line whose first `[` meets a `]:`
581
+ * is a definition to Telegram, and is kept only at the top level after
582
+ * a blank line or another definition, with a label that starts the
583
+ * line, holds no other bracket, code span, autolink or escaped `]`, is
584
+ * not blank or a footnote's and is at most 999 characters, and with
585
+ * nothing after its destination but a title. Otherwise its `[` is
586
+ * escaped. Either needs balanced parentheses and no control character
587
+ * in its destination. Its destination is sent as Telegram reads it,
588
+ * verbatim, and its title is dropped.
589
+ * - A `*`, `_` or `~` run with space on both sides is escaped, outside a
590
+ * thematic break: Telegram would open emphasis with it.
591
+ * - Code spans, `[` that could open a link or reference, and footnote
592
+ * references past `maxInlineNodes` in a paragraph, or footnote
593
+ * references past `maxFootnoteReferences` in the message, are text. A
594
+ * `[` that starts a line and is not closed on it is escaped, as it could
595
+ * open a definition whose label ends on a later line.
596
+ * - Container markers and emphasis past 16 levels are escaped. Every
597
+ * delimiter that could open emphasis counts as a level until the
598
+ * paragraph ends, at a blank line or a line that surely starts a block,
599
+ * and a lazy continuation line keeps the paragraph's container depth.
600
+ * - A table keeps its pipes only when its header is at the start of a line
601
+ * after a blank line, a heading or the start of the text, where it can
602
+ * be no paragraph's continuation. A table wider than 20 columns has its
603
+ * pipes escaped. A table ends at a line that may start another block.
604
+ * - `files` references are added at the end, after closing a fence left
605
+ * open.
606
+ *
607
+ * @internal
608
+ */
609
+ export const render = (markdown, options = {}) => {
610
+ const mentions = options.mentions ?? new Set();
611
+ const lines = markdown.replace(/\r\n?/g, "\n").replace(/\0/g, "\ufffd").split("\n");
612
+ const fenced = [];
613
+ let fence;
614
+ let containers = false;
615
+ let verbatim = true;
616
+ for (const line of lines) {
617
+ if (fence !== undefined) {
618
+ fenced.push(true);
619
+ if (closes(line, fence)) fence = undefined;
620
+ continue;
621
+ }
622
+ const opened = verbatim ? opens(line) : undefined;
623
+ if (opened !== undefined && opened.indent > 0 && containers) verbatim = false;else if (opened !== undefined) {
624
+ fence = opened;
625
+ fenced.push(true);
626
+ continue;
627
+ }
628
+ if (container.test(line)) containers = true;
629
+ fenced.push(false);
630
+ }
631
+ const tableRows = new Map();
632
+ const cellLines = new Set();
633
+ for (let i = 0; i + 1 < lines.length; i++) {
634
+ if (fenced[i] || fenced[i + 1] || tableRows.has(i) || blockStart.test(lines[i])) continue;
635
+ // Neither row indented, nor the header after a line it could continue.
636
+ if (/^\s/.test(lines[i]) || /^\s/.test(lines[i + 1])) continue;
637
+ const above = i === 0 ? "" : lines[i - 1];
638
+ if (!isBlank(above) && !/^#{1,6}(?: |$)/.test(above)) continue;
639
+ if (!delimiterRow.test(lines[i + 1]) || !lines[i + 1].includes("|") || !hasPipe(lines[i])) continue;
640
+ // A delimiter row that is also a list item ends the paragraph first.
641
+ if (/^ {0,3}-[ \t]+\S/.test(lines[i + 1])) continue;
642
+ const columns = cellCount(lines[i]);
643
+ if (columns !== cellCount(lines[i + 1])) continue;
644
+ let end = i + 2;
645
+ while (end < lines.length && !fenced[end] && !isBlank(lines[end]) && !blockStart.test(lines[end])) end++;
646
+ const rows = Array.from({
647
+ length: end - i
648
+ }, (_, k) => i + k);
649
+ for (const row of rows) tableRows.set(row, columns > maxColumns || cellCount(lines[row]) > maxColumns);
650
+ // GFM ends a table at fewer lines than `blockStart` names, so a line
651
+ // past its rows here may still be one of its rows there.
652
+ for (let k = end; k < lines.length && !fenced[k] && !isBlank(lines[k]); k++) cellLines.add(k);
653
+ i = end - 1;
654
+ }
655
+ const inline = {
656
+ open: 0,
657
+ containers: 0,
658
+ nodes: 0
659
+ };
660
+ const footnotes = {
661
+ count: 0
662
+ };
663
+ const definitions = {
664
+ allowed: true
665
+ };
666
+ let item;
667
+ // Whether every line since the last blank one is plain text at the top
668
+ // level: no container, definition, table or other block that a `=` under
669
+ // it could be the lazy continuation of.
670
+ let plain = true;
671
+ const out = lines.map((line, i) => {
672
+ const blank = isBlank(line);
673
+ const setext = plain && i > 0 && !isBlank(lines[i - 1]) && /^ {0,3}=+[ \t]*$/.test(line);
674
+ plain = !fenced[i] && (blank || plain && !/^\s/.test(line) && !blockStart.test(line) && !line.includes("|"));
675
+ if (fenced[i]) {
676
+ definitions.allowed = false;
677
+ return line;
678
+ }
679
+ const wide = tableRows.get(i);
680
+ const starts = blank ? undefined : startsBlock(line, item);
681
+ item = typeof starts === "string" ? starts : undefined;
682
+ if (blank || starts !== undefined || wide !== undefined) {
683
+ inline.open = 0;
684
+ inline.containers = 0;
685
+ inline.nodes = 0;
686
+ }
687
+ const rendered = renderLine(line, {
688
+ tableRow: wide !== undefined,
689
+ cells: wide !== undefined || cellLines.has(i),
690
+ widePipes: wide === true,
691
+ setext,
692
+ inline,
693
+ mentions,
694
+ footnotes,
695
+ definitions
696
+ });
697
+ if (blank) definitions.allowed = true;
698
+ return rendered;
699
+ });
700
+ let text = out.join("\n");
701
+ const files = options.files ?? 0;
702
+ if (files > 0) {
703
+ if (fence !== undefined) text += "\n" + fence.char.repeat(fence.length);
704
+ for (let n = 1; n <= files; n++) text += mediaReference(n);
705
+ }
706
+ return text;
707
+ };
708
+ //# sourceMappingURL=markdown.js.map