import {z} from 'zod' export type TestSessionEnvironmentVariable = {key: string, locked?: boolean | undefined, value: unknown, secret: true} | {key: string, locked?: boolean | undefined, value: string | null, secret?: false | undefined}; export type TestSessionGitHubMetadata = {reporting: boolean, repository?: (string | null) | undefined, sha?: (string | null) | undefined, runId?: (string | null) | undefined, runAttempt?: (string | null) | undefined, workflow?: (string | null) | undefined, job?: (string | null) | undefined, eventName?: (string | null) | undefined, ref?: (string | null) | undefined, headRef?: (string | null) | undefined, baseRef?: (string | null) | undefined, serverUrl?: (string | null) | undefined}; export type TestSessionMetadata = {environment?: string | undefined, repoUrl?: (string | null) | undefined, commitId?: (string | null) | undefined, commitOwner?: (string | null) | undefined, commitMessage?: (string | null) | undefined, branchName?: (string | null) | undefined, github?: TestSessionGitHubMetadata | undefined}; export type TriggerTestSessionRequest = {name: string, runLocation: string, target?: ({matchTags?: Array> | undefined, checkId?: Array | undefined, allowDeactivated?: boolean | undefined}) | undefined, environmentVariables?: Array | undefined, retryStrategy?: ({baseBackoffSeconds?: number | undefined, sameRegion?: boolean | undefined, onlyOn?: Array<'NETWORK_ERROR'> | undefined, type: 'FIXED' | 'LINEAR' | 'EXPONENTIAL', maxRetries?: number | undefined, maxDurationSeconds?: number | undefined} | {baseBackoffSeconds?: number | undefined, sameRegion?: boolean | undefined, onlyOn?: Array<'NETWORK_ERROR'> | undefined, type: 'SINGLE_RETRY'} | unknown) | undefined, refreshCache?: boolean | undefined, metadata?: TestSessionMetadata | undefined}; export type CreateApiV1TestSessionsTriggerArgs = {'x-checkly-account'?: string | undefined, body: TriggerTestSessionRequest}; export type CreateApiV1TestSessionsTriggerOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const testSessionGitHubMetadata = z.object({reporting: z.boolean(), repository: z.string().nullable().optional(), sha: z.string().nullable().optional(), runId: z.string().nullable().optional(), runAttempt: z.string().nullable().optional(), workflow: z.string().nullable().optional(), job: z.string().nullable().optional(), eventName: z.string().nullable().optional(), ref: z.string().nullable().optional(), headRef: z.string().nullable().optional(), baseRef: z.string().nullable().optional(), serverUrl: z.string().nullable().optional()}); export const testSessionMetadata = z.object({environment: z.string().min(1).optional(), repoUrl: z.string().nullable().optional(), commitId: z.string().nullable().optional(), commitOwner: z.string().nullable().optional(), commitMessage: z.string().nullable().optional(), branchName: z.string().nullable().optional(), github: testSessionGitHubMetadata.optional()}); export const testSessionResult = z.object({testSessionResultId: z.string(), testSessionResultLink: z.string(), checkId: z.string().nullable().optional(), checkType: z.enum(["AGENTIC", "API", "BROWSER", "HEARTBEAT", "ICMP", "MULTI_STEP", "TCP", "PLAYWRIGHT", "URL", "DNS", "SSL", "GRPC", "TRACEROUTE"]), name: z.string().optional(), runLocation: z.string().optional(), errorGroupIds: z.array(z.string()), resultType: z.enum(["FINAL", "ATTEMPT", "PENDING"]).optional(), status: z.enum(["RUNNING", "FAILED", "PASSED", "CANCELLED"]), hasErrors: z.boolean(), hasFailures: z.boolean(), isDegraded: z.boolean(), aborted: z.boolean(), responseTime: z.number().nullable().optional(), startedAt: z.string().nullable().optional(), stoppedAt: z.string().nullable().optional()}); export const triggerTestSessionResponse = z.object({testSessionId: z.string(), testSessionLink: z.string(), name: z.string(), status: z.enum(["RUNNING", "FAILED", "PASSED", "CANCELLED"]), errorGroupIds: z.array(z.string()), startedAt: z.string(), stoppedAt: z.string().nullable().optional(), timeElapsed: z.number(), metadata: testSessionMetadata.optional(), results: z.array(testSessionResult).optional()}); 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 }; /** * Trigger a new test session * * POST /v1/test-sessions/trigger */ export const createApiV1TestSessionsTrigger = async (args: CreateApiV1TestSessionsTriggerArgs, options?: CreateApiV1TestSessionsTriggerOptions) => { const {baseUrl = "https://api.checklyhq.com", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-checkly-account'] != null) headers.set("x-checkly-account", String(args['x-checkly-account'])) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/test-sessions/trigger${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(triggerTestSessionResponse, await res.json()) };