import {z} from 'zod' export type CreateApiShipCommercialInvoiceArgs = {body: {origin: {name: string, company?: string | undefined, email?: string | undefined, phone_code?: string | undefined, phone: string, street: string, number?: string | undefined, district?: string | undefined, city: string, state: string, country: string, postalCode: string, reference?: string | undefined, address_id?: number | undefined, identificationNumber?: string | undefined, category?: number | undefined, taxId?: string | undefined}, destination: {name: string, company?: string | undefined, email?: string | undefined, phone_code?: string | undefined, phone: string, street: string, number?: string | undefined, district?: string | undefined, city: string, state: string, country: string, postalCode: string, reference?: string | undefined, address_id?: number | undefined, identificationNumber?: string | undefined, category?: number | undefined, taxId?: string | undefined}, shipment: {carrier: string, trackingNumber: string, orderReference?: string | undefined}, packages: Array<{amount: number, declaredValue: number, totalWeight: number, weightUnit?: ('KG' | 'LB') | undefined, cost: number, cubicMeters: number, currency?: string | undefined, items: Array<{description: string, productCode: string, countryOfManufacture?: string | undefined, quantity: number, price: number}>}>, customsSettings: {dutiesPaymentEntity: 'sender' | 'recipient' | 'envia_guaranteed', exportReason?: ('sale' | 'gift' | 'sample' | 'return' | 'personal_effects') | undefined, itn?: string | undefined}, settings?: ({currency?: string | undefined, printSize?: ('PAPER_4X6' | 'STOCK_4X6' | 'PAPER_LETTER') | undefined}) | undefined}}; export type CreateApiShipCommercialInvoiceOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiShipCommercialInvoiceResponse = z.object({meta: z.string().optional(), data: z.object({carrier: z.string().optional(), trackingNumber: z.string().optional(), billOfLading: z.string().optional()}).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 }; /** * Create a Commercial Invoice * * POST /ship/commercial-invoice */ export const createApiShipCommercialInvoice = async (args: CreateApiShipCommercialInvoiceArgs, options?: CreateApiShipCommercialInvoiceOptions) => { const {baseUrl = "https://api-test.envia.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(/\/+$/, '')}/ship/commercial-invoice${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(createApiShipCommercialInvoiceResponse, await res.json()) };