import {z} from 'zod' export type TokenGrantType = 'authorization_code' | 'refresh_token' | 'client_credentials'; export type OauthAccessTokenCreate = {code?: string | undefined, continuous_refresh?: string | undefined, grant_type: TokenGrantType, redirect_uri?: string | undefined, refresh_token?: string | undefined, scope?: string | undefined}; export type CreateApiOauthTokenArgs = {body: OauthAccessTokenCreate}; export type CreateApiOauthTokenOptions = {baseUrl?: string | undefined, basic?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const tokenGrantType = z.enum(["authorization_code", "refresh_token", "client_credentials"]); export const oauthAccessToken = z.object({access_token: z.string(), expires_in: z.number().int(), refresh_token: z.string().optional(), refresh_token_expires_at: z.number().int().optional(), refresh_token_expires_in: z.number().int().optional(), response_type: tokenGrantType.optional(), scope: z.string().optional(), token_type: 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 }; /** * Generate OAuth access token * * POST /oauth/token */ export const createApiOauthToken = async (args: CreateApiOauthTokenArgs, options?: CreateApiOauthTokenOptions) => { const {baseUrl = "https://api.pinterest.com/v5", fetch: fetchFn = fetch, basic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/x-www-form-urlencoded") headers.set('accept', "application/json") if (basic !== undefined) headers.set('authorization', `Basic ${btoa(`${basic.username}:${basic.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/oauth/token${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: new URLSearchParams(Object.entries(args.body).flatMap(([key, value]) => (value == null ? [] : [[key, String(value)]])))}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(oauthAccessToken, await res.json()) };