import {z} from 'zod' export type ApiCredentialCreateRequest = {name?: string | undefined, scopes: Array<'public:read' | 'companies:read' | 'people:read' | 'tenders:read' | 'legal:read' | 'integrations:read' | 'exports:read' | 'account:read'>, expires_at?: (string | null) | undefined}; export type CreateApiApiV1UserApiCredentialsArgs = {'X-CSRF-Token': string, 'Idempotency-Key': string, body: ApiCredentialCreateRequest}; export type CreateApiApiV1UserApiCredentialsOptions = {baseUrl?: string | undefined, cookieAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const apiCredential = z.object({id: z.number().int().gte(1), name: z.string().max(80), prefix: z.string(), last4: z.string().min(4).max(4), hint: z.string(), scopes: z.array(z.enum(["public:read", "companies:read", "people:read", "tenders:read", "legal:read", "integrations:read", "exports:read", "account:read"])), status: z.enum(["active", "expired", "revoked"]), created_at: z.string(), expires_at: z.string().nullable().optional(), revoked_at: z.string().nullable().optional(), last_used_at: z.string().nullable().optional(), rotated_from_id: z.number().int().nullable().optional(), legacy_migrated: z.boolean().optional()}); export const apiCredentialOneTimeResponse = z.object({ok: z.literal(true), credential: apiCredential, token: z.string(), token_visible_once: z.literal(true), replaced_credential_id: z.number().int().optional(), idempotency_replayed: z.boolean(), idempotency_expires_at: z.number().int().gte(1)}); 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 an API credential * * POST /api/v1/user/api-credentials */ export const createApiApiV1UserApiCredentials = async (args: CreateApiApiV1UserApiCredentialsArgs, options?: CreateApiApiV1UserApiCredentialsOptions) => { const {baseUrl = "https://openmercantil.es", fetch: fetchFn = fetch, cookieAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-CSRF-Token'] != null) headers.set("X-CSRF-Token", String(args['X-CSRF-Token'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (cookieAuth !== undefined) cookies.push("ob_sess=" + encodeURIComponent(cookieAuth)) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/user/api-credentials${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(apiCredentialOneTimeResponse, await res.json()) };