import {z} from 'zod' export type Metadata = {[key: string]: unknown}; export type Upload = {contentType: 'image/vnd.climate.thermal.geotiff' | 'image/vnd.climate.ndvi.geotiff' | 'image/vnd.climate.rgb.geotiff' | 'image/vnd.climate.rgb-nir.geotiff' | 'image/vnd.climate.rgb-cir.geotiff' | 'image/vnd.climate.waterstress.geotiff' | 'image/vnd.climate.elevation.geotiff' | 'image/vnd.climate.raw.geotiff' | 'application/vnd.climate.field.geojson' | 'application/vnd.climate.rx.planting.shp' | 'application/vnd.climate.prescription.zones.shp' | 'application/vnd.climate.modus.xml' | 'application/vnd.climate.as-applied.zip' | 'application/vnd.climate.as-planted.zip' | 'application/vnd.climate.as-harvested.zip', md5: string, length: number, metadata?: Metadata | undefined}; export type CreateApiV4UploadsArgs = {'X-Recipient-Email'?: string | undefined, body: Upload}; export type CreateApiV4UploadsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const createdUpload = 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 }; /** * Initiate a new upload * * POST /v4/uploads * * Also accepts auth: oauth2_authorization_code */ export const createApiV4Uploads = async (args: CreateApiV4UploadsArgs, options?: CreateApiV4UploadsOptions) => { const {baseUrl = "https://platform.climate.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Recipient-Email'] != null) headers.set("X-Recipient-Email", String(args['X-Recipient-Email'])) if (apiKey !== undefined) headers.set("X-Api-Key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v4/uploads${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(createdUpload, await res.json()) };