import {z} from 'zod' export type CreateApiV1NameWaitArgs = {name: string, body: Record}; export type CreateApiV1NameWaitOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const v1SecretEnvironmentVariable = z.object({secretVersion: z.string()}); export const v1ProcessState = z.enum(["STATE_UNSPECIFIED", "STATE_PENDING", "STATE_RUNNING", "STATE_SUCCEEDED", "STATE_FAILED"]); export const v1Process = z.object({name: z.string().optional(), command: z.string(), args: z.array(z.string()).optional(), workingDirectory: z.string().optional(), environmentVariables: z.record(z.string(), z.string()).optional(), secretEnvironmentVariables: z.record(z.string(), v1SecretEnvironmentVariable).optional(), state: v1ProcessState.optional(), exitCode: z.number().int().optional(), createTime: z.string().optional(), startTime: z.string().nullable().optional(), endTime: z.string().nullable().optional()}); export const v1WaitProcessResponse = z.object({process: v1Process.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 }; /** * Waits for a process to complete execution. * This is a blocking call that returns when the process reaches a terminal * state (STATE_SUCCEEDED or STATE_FAILED). * * POST /v1/{name}:wait */ export const createApiV1NameWait = async (args: CreateApiV1NameWaitArgs, options: CreateApiV1NameWaitOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/${encodeURIComponent(String(args.name))}:wait${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(v1WaitProcessResponse, await res.json()) };