import {z} from 'zod' export type StimulusInCreate = {stimulusType: string, stimulusValue: number, reason?: string | undefined}; export type BodyStimulusCreateApiV5StimulusSendPost = {stimulus: StimulusInCreate}; export type CreateApiApiV5StimulusSendArgs = {body: BodyStimulusCreateApiV5StimulusSendPost}; export type CreateApiApiV5StimulusSendOptions = {baseUrl?: string | undefined, RWAPIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const stimulus = z.object({id: z.number().int().optional(), type: z.string(), value: z.number().int(), sentAt: z.string().optional(), sentBy: z.number().int().optional(), sentTo: z.number().int(), createdAt: z.string(), updatedAt: z.string(), via: z.string().optional(), message: z.string().optional(), pushedAt: z.string().optional(), failedAt: z.string().optional(), failureMessage: z.string().optional(), sentByApp: z.number().int().optional(), reason: z.string().optional(), pattern: z.string().optional(), repeat: z.number().int().optional(), deleted: z.boolean().optional(), userDate: z.string().optional(), recent: z.boolean().optional(), meta: z.string().optional()}); export const stimulusInResponse = z.object({stimulus: stimulus}); 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 and send a stimulus * * POST /api/v5/stimulus/send */ export const createApiApiV5StimulusSend = async (args: CreateApiApiV5StimulusSendArgs, options?: CreateApiApiV5StimulusSendOptions) => { const {baseUrl = "https://api.pavlok.com", fetch: fetchFn = fetch, RWAPIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (RWAPIKeyHeader !== undefined) headers.set("Authorization", RWAPIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/api/v5/stimulus/send${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(stimulusInResponse, await res.json()) };