import {z} from 'zod' export type CreateApiOauth2AuthV1TokenArgs = {'Cache-Control': 'no-cache', Accept: 'application/json', scope: 'machinelearning.predict' | 'machinelearning.model' | 'commercestudio.rules' | 'commercestudio.rewrites', grant_type: 'client_credentials', 'Content-Type': 'application/x-www-form-urlencoded'}; export type CreateApiOauth2AuthV1TokenOptions = {baseUrl?: string | undefined, apiKey1?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const responseAuth = z.object({token_type: z.literal("Bearer").min(1), expires_in: z.literal(3600), access_token: z.string().min(500).max(1000), scope: z.enum(["machinelearning.predict", "machinelearning.model", "commercestudio.rules", "commercestudio.rewrites"]).min(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 }; /** * Request Access Token * * POST /oauth2/{auth}/v1/token */ export const createApiOauth2AuthV1Token = async (args: CreateApiOauth2AuthV1TokenArgs, options?: CreateApiOauth2AuthV1TokenOptions) => { const {baseUrl = "https://commerce_studio_id.experiencemanager.lucidworks.com", fetch: fetchFn = fetch, apiKey1} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Cache-Control'] != null) headers.set("Cache-Control", String(args['Cache-Control'])) if (args.Accept != null) headers.set("Accept", String(args.Accept)) if (args.scope != null) query.append("scope", String(args.scope)) if (args.grant_type != null) query.append("grant_type", String(args.grant_type)) if (args['Content-Type'] != null) headers.set("Content-Type", String(args['Content-Type'])) if (apiKey1 !== undefined) headers.set('authorization', `Basic ${btoa(`${apiKey1.username}:${apiKey1.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/oauth2/${encodeURIComponent(String(args.auth))}/v1/token${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(responseAuth, await res.json()) };