import {z} from 'zod' export type QueryBankRateQueryRequest = {origins?: Array | undefined, destinations?: Array | undefined, loadingPorts?: Array | undefined, dischargePorts?: Array | undefined, effectiveDate?: string | undefined, expiryDate?: string | undefined, containerType?: ('dry' | 'reefer' | 'nor') | undefined, containerSizes?: (Array<'20ft' | '40ft' | '40ft_hc' | '45ft'>) | undefined, carrierCodes?: Array | undefined, commodityType?: string | undefined, limit?: number | undefined, offset?: number | undefined}; export type CreateApiApiV1ExternalRatesQueryArgs = {body: QueryBankRateQueryRequest}; export type CreateApiApiV1ExternalRatesQueryOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const locationInfo = z.object({code: z.string(), name: z.string().optional(), type: z.enum(["port", "city", "address", "region"])}); export const legContainerRate = z.object({containerSize: z.enum(["20ft", "40ft", "40ft_hc", "45ft"]), containerType: z.enum(["dry", "reefer", "nor", "general"]), amount: z.number(), currency: z.string()}); export const rateLeg = z.object({type: z.enum(["pre_carriage", "main", "on_carriage"]), origin: locationInfo, destination: locationInfo, mode: z.enum(["truck", "rail", "barge", "ocean"]).optional(), rates: z.array(legContainerRate).optional()}); export const combinedContainerRate = z.object({containerType: z.enum(["dry", "reefer", "nor"]), containerSize: z.enum(["20ft", "40ft", "40ft_hc", "45ft"]), amount: z.number(), currency: z.string(), breakdown: z.object({preCarriage: z.number().optional(), main: z.number().optional(), onCarriage: z.number().optional()}).optional()}); export const surchargeContainerRate = z.object({containerSize: z.enum(["20ft", "40ft", "40ft_hc", "45ft"]), containerType: z.enum(["dry", "reefer", "nor", "general", "all"]).optional(), amount: z.number(), currency: z.string()}); export const rateSurcharge = z.object({code: z.string(), name: z.string(), applicability: z.enum(["inclusive", "subject_to", "not_subject_to", "not_applicable"]), basis: z.string().optional(), amount: z.number().optional(), currency: z.string().optional(), containerRates: z.array(surchargeContainerRate).optional(), percentage: z.number().optional(), applicablePorts: z.array(z.string()).optional(), effectiveDate: z.string().optional(), expiryDate: z.string().optional()}); export const combinedRate = z.object({id: z.string(), placeOfReceipt: locationInfo.optional(), portOfLoading: locationInfo, portOfDischarge: locationInfo, placeOfDelivery: locationInfo.optional(), viaPorts: z.array(locationInfo).optional(), carrierCode: z.string(), carrierName: z.string().optional(), effectiveDate: z.string().optional(), expiryDate: z.string().optional(), commodityType: z.string().optional(), transitTime: z.number().int().optional(), legs: z.array(rateLeg).optional(), containerRates: z.array(combinedContainerRate), surcharges: z.array(rateSurcharge).optional(), sourceId: z.string(), sourceName: z.string()}); export const queryBankRateQueryResponse = z.object({rates: z.array(combinedRate).optional(), metadata: z.object({totalRates: z.number().int().optional(), sourcesSearched: z.number().int().optional(), queryTimeMs: z.number().int().optional()}).optional()}); export const createApiApiV1ExternalRatesQueryResponse = z.object({success: z.boolean().optional(), data: queryBankRateQueryResponse.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 }; /** * Query freight rates * * POST /api/v1/external/rates/query */ export const createApiApiV1ExternalRatesQuery = async (args: CreateApiApiV1ExternalRatesQueryArgs, options?: CreateApiApiV1ExternalRatesQueryOptions) => { const {baseUrl = "https://api.wove.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/external/rates/query${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(createApiApiV1ExternalRatesQueryResponse, await res.json()) };