import {z} from 'zod' export type GetApiMethodsOptions = {baseUrl?: string | undefined, APITokens?: string | undefined, fetch?: typeof fetch | undefined}; export const methodParameter = z.object({name: z.string(), description: z.string(), constraints: z.object({allow_empty_string: z.boolean(), allow_whitespace_string: z.boolean(), max_length: z.number().int(), min_length: z.number().int(), regex: z.string(), not_regex: z.string(), select: z.array(z.string())}), type: z.enum(["String", "HereString"])}); export const methods = z.object({id: z.string(), name: z.string(), version: z.string(), category: z.string(), desc: z.string(), documentation: z.string(), parameters: z.array(methodParameter), agents: z.array(z.string()), condition: z.object({prefix: z.string().optional(), parameter: z.string().optional()}), deprecated: z.object({info: z.string().optional(), replacedBy: z.string().optional()})}); export const getApiMethodsResponse = z.object({result: z.enum(["success", "error"]), action: z.literal("listTechniques"), data: z.object({methods: methods})}); 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 }; /** * List methods * * GET /methods */ export const getApiMethods = async (options?: GetApiMethodsOptions) => { const {baseUrl = "https://rudder.example.com/rudder/api/latest", fetch: fetchFn = fetch, APITokens} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (APITokens !== undefined) headers.set("X-API-Token", APITokens) const url = `${baseUrl.replace(/\/+$/, '')}/methods${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiMethodsResponse, await res.json()) };