import {z} from 'zod' export type ApiKeyScopeRole = 'discoverer' | 'viewer' | 'editor' | 'admin' | 'owner' | 'member' | 'executor'; export type ApiKeyScope = {resource_id: string, resource_type: string, role: ApiKeyScopeRole}; export type ApiKeyCreateRequest = {description?: (string | null) | undefined, name: string, scopes: Array, sharing_group_ids: Array}; export type CreateApiApiKeysArgs = {body: ApiKeyCreateRequest}; export type CreateApiApiKeysOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const apiKeyScopeRole = z.enum(["discoverer", "viewer", "editor", "admin", "owner", "member", "executor"]); export const apiKeyScope = z.object({resource_id: z.string(), resource_type: z.string(), role: apiKeyScopeRole}); export const apiKeyResponse = z.object({created_at: z.string().nullable().optional(), created_by: z.string(), description: z.string().nullable().optional(), id: z.string(), key_prefix: z.string(), last_used_at: z.string().nullable().optional(), name: z.string(), org_id: z.string(), revoked_at: z.string().nullable().optional(), scopes: z.array(apiKeyScope).optional(), sharing_group_ids: z.array(z.string()).optional()}); export const apiKeyCreateResponse = z.object({api_key: apiKeyResponse, key: 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 }; /** * Create API Key * * POST /api_keys */ export const createApiApiKeys = async (args: CreateApiApiKeysArgs, options: CreateApiApiKeysOptions) => { 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(/\/+$/, '')}/api_keys${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(apiKeyCreateResponse, await res.json()) };