-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mts
218 lines (207 loc) · 4.78 KB
/
index.mts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import type { Bot, RawApi } from 'grammy'
import { webhookCallback } from 'grammy'
import type { Other } from 'grammy/out/core/api'
import type { WebhookOptions } from 'grammy/out/convenience/webhook'
/**
* Options for hostname
*/
export interface OptionsForHost {
/**
* Optional headers from incoming request
*/
headers?: Headers | Record<string, string>
/**
* Optional header name which contains the hostname
*/
header?: string
/**
* Optional fallback hostname
*/
fallback?: string
}
/**
* This method generates a hostname from the options passed to it
* @returns Target hostname
*/
export function getHost(
{
fallback = process.env.VERCEL_BRANCH_URL ||
process.env.VERCEL_URL ||
'localhost',
headers = globalThis.Headers ? new Headers() : {},
header = 'x-forwarded-host',
} = {} as OptionsForHost
): string {
return String(
(globalThis.Headers && headers instanceof Headers
? headers?.get?.(header)
: (headers as Record<string, string>)[header]) ?? fallback
)
}
/**
* Options for URL
*/
export interface OptionsForURL extends OptionsForHost {
/**
* Optional hostname without protocol
*/
host?: string
/**
* Path to a function that receives updates
*/
path?: string
}
/**
* This method generates a URL from the options passed to it
* @returns Target URL
*/
export function getURL(
{ host, path = '', ...other } = {} as OptionsForURL
): string {
return new URL(path, `https://${host ?? getHost(other)}`).href
}
/**
* Options for webhooks
*/
export interface OptionsForWebhook
extends OptionsForURL,
Other<RawApi, 'setWebhook', 'url'> {
/**
* Optional URL for webhooks
*/
url?: string
/**
* Optional strategy for handling errors
*/
onError?: 'throw' | 'return'
/**
* Optional list of environments where this method allowed
*/
allowedEnvs?: string[]
/**
* An optional string to compare to X-Telegram-Bot-Api-Secret-Token
*/
secretToken?: Other<RawApi, 'setWebhook', 'url'>['secret_token']
}
/**
* Callback factory for grammY `bot.api.setWebhook` method
* @returns Target callback method
*/
export function setWebhookCallback(
bot: Bot,
{
allowedEnvs = ['development'],
secretToken: secret_token,
onError = 'throw',
fallback,
header,
host,
path,
url,
...other
} = {} as OptionsForWebhook
): (req: Request) => Promise<Response> {
return async (
{ headers } = {} as Request,
{ json = jsonResponse } = {}
): Promise<Response> => {
try {
const env = process.env.VERCEL_ENV || 'development'
if (!allowedEnvs.includes(env)) return json({ ok: false })
const webhookURL =
url ||
getURL({
headers,
fallback,
host,
path,
header,
})
const ok = await bot.api.setWebhook(webhookURL, {
secret_token,
...other,
})
return json({ ok })
} catch (e) {
if (onError === 'throw') throw e
console.error(e)
return json(e)
}
}
}
/**
* Options for stream
*/
export interface OptionsForStream extends WebhookOptions {
/**
* Optional content for chunks
*/
chunk?: string
/**
* Optional interval for writing chunks to stream
*/
intervalMilliseconds?: number
}
/**
* Callback factory for streaming webhook response
* @returns Target callback method
*/
export function webhookStream(
bot: Bot,
{
intervalMilliseconds = 1_000,
timeoutMilliseconds = 55_000,
chunk = ' ',
...other
} = {} as OptionsForStream
): (req: Request) => Response {
const callback = webhookCallback(bot, 'std/http', {
timeoutMilliseconds,
...other,
})
return (req: Request) =>
new Response(
new ReadableStream({
start: controller => {
const encoder = new TextEncoder()
const streamInterval = setInterval(() => {
controller.enqueue(encoder.encode(chunk))
}, intervalMilliseconds)
return callback(req).finally(() => {
clearInterval(streamInterval)
controller.close()
})
},
})
)
}
/**
* Parameters from `JSON.stringify` method
*/
export type StringifyJSON = Parameters<typeof JSON.stringify>
/**
* Options for JSON response
* @public
*/
export interface OptionsForJSON extends ResponseInit {
replacer?: StringifyJSON[1]
space?: StringifyJSON[2]
}
/**
* This method generates Response objects for JSON
* @returns Target JSON Response
*/
export function jsonResponse(
value: any,
{ space, status, replacer, statusText, headers = {} } = {} as OptionsForJSON
): Response {
const body = JSON.stringify(value, replacer, space)
return new Response(body, {
headers: {
'Content-Type': 'application/json',
...headers,
},
statusText,
status,
})
}