| 1 | export async function paginateCursor(opts) { |
| 2 | const { maxPages, pageDelayMs = 1000 } = opts; |
| 3 | let cursor = opts.cursor; |
| 4 | if (maxPages !== undefined) { |
| 5 | if (typeof maxPages !== 'number' || !Number.isFinite(maxPages)) { |
| 6 | return { success: false, error: 'Invalid maxPages' }; |
| 7 | } |
| 8 | if (maxPages <= 0) { |
| 9 | return { success: true, items: [], nextCursor: cursor }; |
| 10 | } |
| 11 | } |
| 12 | const effectiveMaxPages = maxPages !== undefined ? Math.floor(maxPages) : undefined; |
| 13 | if (effectiveMaxPages !== undefined && effectiveMaxPages <= 0) { |
| 14 | return { success: true, items: [], nextCursor: cursor }; |
| 15 | } |
| 16 | const seen = new Set(); |
| 17 | const seenCursors = new Set(cursor ? [cursor] : []); |
| 18 | const items = []; |
| 19 | let pagesFetched = 0; |
| 20 | while (true) { |
| 21 | if (pagesFetched > 0 && pageDelayMs > 0 && typeof opts.sleep === 'function') { |
| 22 | await opts.sleep(pageDelayMs); |
| 23 | } |
| 24 | const page = await opts.fetchPage(cursor); |
| 25 | if (!page.success) { |
| 26 | if (items.length > 0) { |
| 27 | return { success: false, error: page.error, items, nextCursor: cursor }; |
| 28 | } |
| 29 | return page; |
| 30 | } |
| 31 | pagesFetched += 1; |
| 32 | const pageItems = Array.isArray(page.items) ? page.items : []; |
| 33 | let added = 0; |
| 34 | for (const item of pageItems) { |
| 35 | const key = opts.getKey(item); |
| 36 | if (seen.has(key)) { |
| 37 | continue; |
| 38 | } |
| 39 | seen.add(key); |
| 40 | items.push(item); |
| 41 | added += 1; |
| 42 | } |
| 43 | const pageCursor = page.cursor; |
| 44 | if (!pageCursor || seenCursors.has(pageCursor) || pageItems.length === 0 || added === 0) { |
| 45 | return { success: true, items, nextCursor: undefined }; |
| 46 | } |
| 47 | seenCursors.add(pageCursor); |
| 48 | if (effectiveMaxPages !== undefined && pagesFetched >= effectiveMaxPages) { |
| 49 | return { success: true, items, nextCursor: pageCursor }; |
| 50 | } |
| 51 | cursor = pageCursor; |
| 52 | } |
| 53 | } |
| 54 | //# sourceMappingURL=paginate-cursor.js.map |