( opts: SlackPaginateOptions )
| 119 | * the `ok` field is checked on every page. |
| 120 | */ |
| 121 | export async function fetchSlackMessagesPaginated( |
| 122 | opts: SlackPaginateOptions |
| 123 | ): Promise<SlackPaginateResult> { |
| 124 | const { token, method, baseParams, limit, maxPages, missingScopeHint } = opts |
| 125 | const perPage = Math.min(Math.max(Number(limit) || 0, 1), SLACK_PAGE_MAX) |
| 126 | |
| 127 | const messages: any[] = [] |
| 128 | let cursor = opts.cursor?.trim() || undefined |
| 129 | let nextCursor: string | null = null |
| 130 | let pages = 0 |
| 131 | |
| 132 | while (pages < maxPages) { |
| 133 | const url = new URL(`https://slack.com/api/${method}`) |
| 134 | for (const [key, value] of Object.entries(baseParams)) { |
| 135 | const trimmed = typeof value === 'string' ? value.trim() : value |
| 136 | if (trimmed) url.searchParams.append(key, String(trimmed)) |
| 137 | } |
| 138 | url.searchParams.append('limit', String(perPage)) |
| 139 | if (cursor) url.searchParams.append('cursor', cursor) |
| 140 | |
| 141 | let response: Response |
| 142 | let attempt = 0 |
| 143 | while (true) { |
| 144 | response = await fetch(url.toString(), { |
| 145 | method: 'GET', |
| 146 | headers: { Authorization: `Bearer ${token}` }, |
| 147 | }) |
| 148 | |
| 149 | if (response.status === 429 && attempt < SLACK_RATE_LIMIT_MAX_RETRIES) { |
| 150 | attempt += 1 |
| 151 | const retryAfter = parseRetryAfter(response.headers.get('retry-after')) ?? 1000 |
| 152 | await sleep(retryAfter) |
| 153 | continue |
| 154 | } |
| 155 | break |
| 156 | } |
| 157 | |
| 158 | const data = await response.json() |
| 159 | |
| 160 | if (!data.ok) { |
| 161 | if (data.error === 'missing_scope') { |
| 162 | throw new Error( |
| 163 | `Missing required permissions. Please reconnect your Slack account with the necessary scopes (${missingScopeHint}).` |
| 164 | ) |
| 165 | } |
| 166 | if (data.error === 'invalid_auth') { |
| 167 | throw new Error('Invalid authentication. Please check your Slack credentials.') |
| 168 | } |
| 169 | if (data.error === 'channel_not_found') { |
| 170 | throw new Error('Channel not found. Please check the channel ID.') |
| 171 | } |
| 172 | if (data.error === 'ratelimited') { |
| 173 | throw new Error('Slack rate limit exceeded. Please retry in a moment.') |
| 174 | } |
| 175 | throw new Error(data.error || `Failed to call ${method}`) |
| 176 | } |
| 177 | |
| 178 | for (const msg of data.messages ?? []) messages.push(mapSlackMessage(msg)) |
no test coverage detected