import {z} from 'zod' export type CreateApiV1TwitterStreamMonitorsArgs = {body: {name: string, usernames: Array, webhook_url?: (string | null) | undefined, webhook_secret?: (string | null) | undefined, filter_types?: (Array<'original' | 'reply' | 'retweet' | 'quote'> | null) | undefined}}; export type CreateApiV1TwitterStreamMonitorsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const streamMonitorResponse = z.object({id: z.string(), name: z.string(), usernames: z.array(z.string()), status: z.enum(["active", "paused", "suspended"]), status_reason: z.string().nullable().optional(), webhook_url: z.string().nullable().optional(), webhook_secret_set: z.boolean().optional(), filter_types: z.array(z.enum(["original", "reply", "retweet", "quote"])).nullable().optional(), credits_per_account_per_day: z.number().optional(), estimated_credits_per_day: z.number().optional(), pricing_tier: z.string().optional(), created_at: z.string(), updated_at: z.string()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create stream monitor * * POST /v1/twitter/stream/monitors */ export const createApiV1TwitterStreamMonitors = async (args: CreateApiV1TwitterStreamMonitorsArgs, options?: CreateApiV1TwitterStreamMonitorsOptions) => { const {baseUrl = "https://scrapebadger.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/twitter/stream/monitors${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(streamMonitorResponse, await res.json()) };