// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. import { KernelError } from './error'; import { FinalRequestOptions } from '../internal/request-options'; import { defaultParseResponse } from '../internal/parse'; import { type Kernel } from '../client'; import { APIPromise } from './api-promise'; import { type APIResponseProps } from '../internal/parse'; import { maybeCoerceBoolean, maybeCoerceInteger, maybeObj } from '../internal/utils/values'; export type PageRequestOptions = Pick; export abstract class AbstractPage implements AsyncIterable { #client: Kernel; protected options: FinalRequestOptions; protected response: Response; protected body: unknown; constructor(client: Kernel, response: Response, body: unknown, options: FinalRequestOptions) { this.#client = client; this.options = options; this.response = response; this.body = body; } abstract nextPageRequestOptions(): PageRequestOptions | null; abstract getPaginatedItems(): Item[]; hasNextPage(): boolean { const items = this.getPaginatedItems(); if (!items.length) return false; return this.nextPageRequestOptions() != null; } async getNextPage(): Promise { const nextOptions = this.nextPageRequestOptions(); if (!nextOptions) { throw new KernelError( 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.', ); } return await this.#client.requestAPIList(this.constructor as any, nextOptions); } async *iterPages(): AsyncGenerator { let page: this = this; yield page; while (page.hasNextPage()) { page = await page.getNextPage(); yield page; } } async *[Symbol.asyncIterator](): AsyncGenerator { for await (const page of this.iterPages()) { for (const item of page.getPaginatedItems()) { yield item; } } } } /** * This subclass of Promise will resolve to an instantiated Page once the request completes. * * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: * * for await (const item of client.items.list()) { * console.log(item) * } */ export class PagePromise< PageClass extends AbstractPage, Item = ReturnType[number], > extends APIPromise implements AsyncIterable { constructor( client: Kernel, request: Promise, Page: new (...args: ConstructorParameters) => PageClass, ) { super( client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options), ); } /** * Allow auto-paginating iteration on an unawaited list call, eg: * * for await (const item of client.items.list()) { * console.log(item) * } */ async *[Symbol.asyncIterator](): AsyncGenerator { const page = await this; for await (const item of page) { yield item; } } } export type PageTokenPaginationResponse = Item[]; export interface PageTokenPaginationParams { page_token?: string; limit?: number; } export class PageTokenPagination extends AbstractPage { items: Array; next_page_token: string | null; has_more: boolean | null; constructor( client: Kernel, response: Response, body: PageTokenPaginationResponse, options: FinalRequestOptions, ) { super(client, response, body, options); this.items = body || []; this.next_page_token = this.response.headers.get('x-next-page-token') ?? null; this.has_more = maybeCoerceBoolean(this.response.headers.get('x-has-more')) ?? null; } getPaginatedItems(): Item[] { return this.items ?? []; } override hasNextPage(): boolean { if (this.has_more === false) { return false; } return super.hasNextPage(); } nextPageRequestOptions(): PageRequestOptions | null { const cursor = this.next_page_token; if (!cursor) { return null; } return { ...this.options, query: { ...maybeObj(this.options.query), page_token: cursor, }, }; } } export type OffsetPaginationResponse = Item[]; export interface OffsetPaginationParams { offset?: number; limit?: number; } export class OffsetPagination extends AbstractPage { items: Array; has_more: boolean | null; next_offset: number | null; constructor( client: Kernel, response: Response, body: OffsetPaginationResponse, options: FinalRequestOptions, ) { super(client, response, body, options); this.items = body || []; this.has_more = maybeCoerceBoolean(this.response.headers.get('x-has-more')) ?? null; this.next_offset = maybeCoerceInteger(this.response.headers.get('x-next-offset')) ?? null; } getPaginatedItems(): Item[] { return this.items ?? []; } override hasNextPage(): boolean { if (this.has_more === false) { return false; } return super.hasNextPage(); } nextPageRequestOptions(): PageRequestOptions | null { // X-Next-Offset is the absolute start of the next page, or 0 on the last // page (the API's stop sentinel). The old code added the current page // length on top, skipping a full page per iteration. Only a positive // offset advances; 0 is a value the server affirmatively sent to mean // "no more", so we stop on it (matching the Go SDK pager). const offset = this.next_offset; if (offset == null) { if (this.has_more) { throw new KernelError( 'Server reported X-Has-More: true without an X-Next-Offset header; refusing to silently truncate pagination', ); } return null; } if (offset === 0) { return null; } return { ...this.options, query: { ...maybeObj(this.options.query), offset, }, }; } }