UNPKG

@carapis/api

Version:

Universal TypeScript/JavaScript client for CARAPIS Vehicles API - Access automotive data from 25+ global marketplaces including Cars.com, AutoScout24, Encar, Auto.ru, and more. Enterprise-grade automotive data extraction with real-time vehicle listings, p

1,833 lines (1,815 loc) 61.1 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { ApiService: () => ApiService, BaseClient: () => BaseClient, BaseVehiclesService: () => BaseVehiclesService, BrandsService: () => BrandsService, SourcesService: () => SourcesService, StatisticsService: () => StatisticsService, VehiclesAPIClient: () => VehiclesAPIClient, VehiclesSSRService: () => VehiclesSSRService, VehiclesService: () => VehiclesService, default: () => client_default }); module.exports = __toCommonJS(index_exports); // src/generated/vehicles_api/index.ts var vehicles_api_exports = {}; __export(vehicles_api_exports, { client: () => client, default: () => client, vehiclesApiImageRetrieve: () => vehiclesApiImageRetrieve, vehiclesApiV1BrandsCacheInfoRetrieve: () => vehiclesApiV1BrandsCacheInfoRetrieve, vehiclesApiV1BrandsList: () => vehiclesApiV1BrandsList, vehiclesApiV1BrandsModelsCacheInfoRetrieve: () => vehiclesApiV1BrandsModelsCacheInfoRetrieve, vehiclesApiV1BrandsModelsList: () => vehiclesApiV1BrandsModelsList, vehiclesApiV1BrandsModelsRetrieve: () => vehiclesApiV1BrandsModelsRetrieve, vehiclesApiV1BrandsModelsVehiclesCacheInfoRetrieve: () => vehiclesApiV1BrandsModelsVehiclesCacheInfoRetrieve, vehiclesApiV1BrandsModelsVehiclesList: () => vehiclesApiV1BrandsModelsVehiclesList, vehiclesApiV1BrandsModelsVehiclesRetrieve: () => vehiclesApiV1BrandsModelsVehiclesRetrieve, vehiclesApiV1BrandsRetrieve: () => vehiclesApiV1BrandsRetrieve, vehiclesApiV1BrandsVehiclesCacheInfoRetrieve: () => vehiclesApiV1BrandsVehiclesCacheInfoRetrieve, vehiclesApiV1BrandsVehiclesList: () => vehiclesApiV1BrandsVehiclesList, vehiclesApiV1BrandsVehiclesRetrieve: () => vehiclesApiV1BrandsVehiclesRetrieve, vehiclesApiV1Retrieve: () => vehiclesApiV1Retrieve, vehiclesApiV1SourcesCacheInfoRetrieve: () => vehiclesApiV1SourcesCacheInfoRetrieve, vehiclesApiV1SourcesList: () => vehiclesApiV1SourcesList, vehiclesApiV1SourcesRetrieve: () => vehiclesApiV1SourcesRetrieve, vehiclesApiV1SourcesVehiclesCacheInfoRetrieve: () => vehiclesApiV1SourcesVehiclesCacheInfoRetrieve, vehiclesApiV1SourcesVehiclesList: () => vehiclesApiV1SourcesVehiclesList, vehiclesApiV1SourcesVehiclesRetrieve: () => vehiclesApiV1SourcesVehiclesRetrieve, vehiclesApiV1StatisticsBrandComparisonRetrieve: () => vehiclesApiV1StatisticsBrandComparisonRetrieve, vehiclesApiV1StatisticsMarketOverviewRetrieve: () => vehiclesApiV1StatisticsMarketOverviewRetrieve, vehiclesApiV1StatisticsPriceTrendsRetrieve: () => vehiclesApiV1StatisticsPriceTrendsRetrieve, vehiclesApiV1StatisticsQualityInsightsRetrieve: () => vehiclesApiV1StatisticsQualityInsightsRetrieve, vehiclesApiV1UrlsTestRetrieve: () => vehiclesApiV1UrlsTestRetrieve, vehiclesApiV1VehiclesCacheInfoRetrieve: () => vehiclesApiV1VehiclesCacheInfoRetrieve, vehiclesApiV1VehiclesExportCsvRetrieve: () => vehiclesApiV1VehiclesExportCsvRetrieve, vehiclesApiV1VehiclesExportExcelRetrieve: () => vehiclesApiV1VehiclesExportExcelRetrieve, vehiclesApiV1VehiclesExportJsonRetrieve: () => vehiclesApiV1VehiclesExportJsonRetrieve, vehiclesApiV1VehiclesList: () => vehiclesApiV1VehiclesList, vehiclesApiV1VehiclesRetrieve: () => vehiclesApiV1VehiclesRetrieve, vehiclesApiV1VehiclesSimilarRetrieve: () => vehiclesApiV1VehiclesSimilarRetrieve, vehiclesApiV1VehiclesStatisticsRetrieve: () => vehiclesApiV1VehiclesStatisticsRetrieve }); // src/generated/vehicles_api/core/bodySerializer.gen.ts var jsonBodySerializer = { bodySerializer: (body) => JSON.stringify( body, (_key, value) => typeof value === "bigint" ? value.toString() : value ) }; // src/generated/vehicles_api/core/params.gen.ts var extraPrefixesMap = { $body_: "body", $headers_: "headers", $path_: "path", $query_: "query" }; var extraPrefixes = Object.entries(extraPrefixesMap); // src/generated/vehicles_api/core/auth.gen.ts var getAuthToken = async (auth, callback) => { const token = typeof callback === "function" ? await callback(auth) : callback; if (!token) { return; } if (auth.scheme === "bearer") { return `Bearer ${token}`; } if (auth.scheme === "basic") { return `Basic ${btoa(token)}`; } return token; }; // src/generated/vehicles_api/core/pathSerializer.gen.ts var separatorArrayExplode = (style) => { switch (style) { case "label": return "."; case "matrix": return ";"; case "simple": return ","; default: return "&"; } }; var separatorArrayNoExplode = (style) => { switch (style) { case "form": return ","; case "pipeDelimited": return "|"; case "spaceDelimited": return "%20"; default: return ","; } }; var separatorObjectExplode = (style) => { switch (style) { case "label": return "."; case "matrix": return ";"; case "simple": return ","; default: return "&"; } }; var serializeArrayParam = ({ allowReserved, explode, name, style, value }) => { if (!explode) { const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style)); switch (style) { case "label": return `.${joinedValues2}`; case "matrix": return `;${name}=${joinedValues2}`; case "simple": return joinedValues2; default: return `${name}=${joinedValues2}`; } } const separator = separatorArrayExplode(style); const joinedValues = value.map((v) => { if (style === "label" || style === "simple") { return allowReserved ? v : encodeURIComponent(v); } return serializePrimitiveParam({ allowReserved, name, value: v }); }).join(separator); return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues; }; var serializePrimitiveParam = ({ allowReserved, name, value }) => { if (value === void 0 || value === null) { return ""; } if (typeof value === "object") { throw new Error( "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these." ); } return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; }; var serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => { if (value instanceof Date) { return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; } if (style !== "deepObject" && !explode) { let values = []; Object.entries(value).forEach(([key, v]) => { values = [ ...values, key, allowReserved ? v : encodeURIComponent(v) ]; }); const joinedValues2 = values.join(","); switch (style) { case "form": return `${name}=${joinedValues2}`; case "label": return `.${joinedValues2}`; case "matrix": return `;${name}=${joinedValues2}`; default: return joinedValues2; } } const separator = separatorObjectExplode(style); const joinedValues = Object.entries(value).map( ([key, v]) => serializePrimitiveParam({ allowReserved, name: style === "deepObject" ? `${name}[${key}]` : key, value: v }) ).join(separator); return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues; }; // src/generated/vehicles_api/client/utils.gen.ts var PATH_PARAM_RE = /\{[^{}]+\}/g; var defaultPathSerializer = ({ path, url: _url }) => { let url = _url; const matches = _url.match(PATH_PARAM_RE); if (matches) { for (const match of matches) { let explode = false; let name = match.substring(1, match.length - 1); let style = "simple"; if (name.endsWith("*")) { explode = true; name = name.substring(0, name.length - 1); } if (name.startsWith(".")) { name = name.substring(1); style = "label"; } else if (name.startsWith(";")) { name = name.substring(1); style = "matrix"; } const value = path[name]; if (value === void 0 || value === null) { continue; } if (Array.isArray(value)) { url = url.replace( match, serializeArrayParam({ explode, name, style, value }) ); continue; } if (typeof value === "object") { url = url.replace( match, serializeObjectParam({ explode, name, style, value, valueOnly: true }) ); continue; } if (style === "matrix") { url = url.replace( match, `;${serializePrimitiveParam({ name, value })}` ); continue; } const replaceValue = encodeURIComponent( style === "label" ? `.${value}` : value ); url = url.replace(match, replaceValue); } } return url; }; var createQuerySerializer = ({ allowReserved, array, object } = {}) => { const querySerializer = (queryParams) => { const search = []; if (queryParams && typeof queryParams === "object") { for (const name in queryParams) { const value = queryParams[name]; if (value === void 0 || value === null) { continue; } if (Array.isArray(value)) { const serializedArray = serializeArrayParam({ allowReserved, explode: true, name, style: "form", value, ...array }); if (serializedArray) search.push(serializedArray); } else if (typeof value === "object") { const serializedObject = serializeObjectParam({ allowReserved, explode: true, name, style: "deepObject", value, ...object }); if (serializedObject) search.push(serializedObject); } else { const serializedPrimitive = serializePrimitiveParam({ allowReserved, name, value }); if (serializedPrimitive) search.push(serializedPrimitive); } } } return search.join("&"); }; return querySerializer; }; var getParseAs = (contentType) => { if (!contentType) { return "stream"; } const cleanContent = contentType.split(";")[0]?.trim(); if (!cleanContent) { return; } if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) { return "json"; } if (cleanContent === "multipart/form-data") { return "formData"; } if (["application/", "audio/", "image/", "video/"].some( (type) => cleanContent.startsWith(type) )) { return "blob"; } if (cleanContent.startsWith("text/")) { return "text"; } return; }; var checkForExistence = (options, name) => { if (!name) { return false; } if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) { return true; } return false; }; var setAuthParams = async ({ security, ...options }) => { for (const auth of security) { if (checkForExistence(options, auth.name)) { continue; } const token = await getAuthToken(auth, options.auth); if (!token) { continue; } const name = auth.name ?? "Authorization"; switch (auth.in) { case "query": if (!options.query) { options.query = {}; } options.query[name] = token; break; case "cookie": options.headers.append("Cookie", `${name}=${token}`); break; case "header": default: options.headers.set(name, token); break; } } }; var buildUrl = (options) => { const url = getUrl({ baseUrl: options.baseUrl, path: options.path, query: options.query, querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer), url: options.url }); return url; }; var getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => { const pathUrl = _url.startsWith("/") ? _url : `/${_url}`; let url = (baseUrl ?? "") + pathUrl; if (path) { url = defaultPathSerializer({ path, url }); } let search = query ? querySerializer(query) : ""; if (search.startsWith("?")) { search = search.substring(1); } if (search) { url += `?${search}`; } return url; }; var mergeConfigs = (a, b) => { const config = { ...a, ...b }; if (config.baseUrl?.endsWith("/")) { config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); } config.headers = mergeHeaders(a.headers, b.headers); return config; }; var mergeHeaders = (...headers) => { const mergedHeaders = new Headers(); for (const header of headers) { if (!header || typeof header !== "object") { continue; } const iterator = header instanceof Headers ? header.entries() : Object.entries(header); for (const [key, value] of iterator) { if (value === null) { mergedHeaders.delete(key); } else if (Array.isArray(value)) { for (const v of value) { mergedHeaders.append(key, v); } } else if (value !== void 0) { mergedHeaders.set( key, typeof value === "object" ? JSON.stringify(value) : value ); } } } return mergedHeaders; }; var Interceptors = class { constructor() { this._fns = []; } clear() { this._fns = []; } getInterceptorIndex(id) { if (typeof id === "number") { return this._fns[id] ? id : -1; } else { return this._fns.indexOf(id); } } exists(id) { const index = this.getInterceptorIndex(id); return !!this._fns[index]; } eject(id) { const index = this.getInterceptorIndex(id); if (this._fns[index]) { this._fns[index] = null; } } update(id, fn) { const index = this.getInterceptorIndex(id); if (this._fns[index]) { this._fns[index] = fn; return id; } else { return false; } } use(fn) { this._fns = [...this._fns, fn]; return this._fns.length - 1; } }; var createInterceptors = () => ({ error: new Interceptors(), request: new Interceptors(), response: new Interceptors() }); var defaultQuerySerializer = createQuerySerializer({ allowReserved: false, array: { explode: true, style: "form" }, object: { explode: true, style: "deepObject" } }); var defaultHeaders = { "Content-Type": "application/json" }; var createConfig = (override = {}) => ({ ...jsonBodySerializer, headers: defaultHeaders, parseAs: "auto", querySerializer: defaultQuerySerializer, ...override }); // src/generated/vehicles_api/client/client.gen.ts var createClient = (config = {}) => { let _config = mergeConfigs(createConfig(), config); const getConfig = () => ({ ..._config }); const setConfig = (config2) => { _config = mergeConfigs(_config, config2); return getConfig(); }; const interceptors = createInterceptors(); const request = async (options) => { const opts = { ..._config, ...options, fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, headers: mergeHeaders(_config.headers, options.headers), serializedBody: void 0 }; if (opts.security) { await setAuthParams({ ...opts, security: opts.security }); } if (opts.requestValidator) { await opts.requestValidator(opts); } if (opts.body && opts.bodySerializer) { opts.serializedBody = opts.bodySerializer(opts.body); } if (opts.serializedBody === void 0 || opts.serializedBody === "") { opts.headers.delete("Content-Type"); } const url = buildUrl(opts); const requestInit = { redirect: "follow", ...opts, body: opts.serializedBody }; let request2 = new Request(url, requestInit); for (const fn of interceptors.request._fns) { if (fn) { request2 = await fn(request2, opts); } } const _fetch = opts.fetch; let response = await _fetch(request2); for (const fn of interceptors.response._fns) { if (fn) { response = await fn(response, request2, opts); } } const result = { request: request2, response }; if (response.ok) { if (response.status === 204 || response.headers.get("Content-Length") === "0") { return opts.responseStyle === "data" ? {} : { data: {}, ...result }; } const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"; let data; switch (parseAs) { case "arrayBuffer": case "blob": case "formData": case "json": case "text": data = await response[parseAs](); break; case "stream": return opts.responseStyle === "data" ? response.body : { data: response.body, ...result }; } if (parseAs === "json") { if (opts.responseValidator) { await opts.responseValidator(data); } if (opts.responseTransformer) { data = await opts.responseTransformer(data); } } return opts.responseStyle === "data" ? data : { data, ...result }; } const textError = await response.text(); let jsonError; try { jsonError = JSON.parse(textError); } catch { } const error = jsonError ?? textError; let finalError = error; for (const fn of interceptors.error._fns) { if (fn) { finalError = await fn(error, response, request2, opts); } } finalError = finalError || {}; if (opts.throwOnError) { throw finalError; } return opts.responseStyle === "data" ? void 0 : { error: finalError, ...result }; }; return { buildUrl, connect: (options) => request({ ...options, method: "CONNECT" }), delete: (options) => request({ ...options, method: "DELETE" }), get: (options) => request({ ...options, method: "GET" }), getConfig, head: (options) => request({ ...options, method: "HEAD" }), interceptors, options: (options) => request({ ...options, method: "OPTIONS" }), patch: (options) => request({ ...options, method: "PATCH" }), post: (options) => request({ ...options, method: "POST" }), put: (options) => request({ ...options, method: "PUT" }), request, setConfig, trace: (options) => request({ ...options, method: "TRACE" }) }; }; // src/generated/vehicles_api/client.gen.ts var client = createClient(createConfig()); // src/generated/vehicles_api/sdk.gen.ts var vehiclesApiImageRetrieve = (options) => { return (options.client ?? client).get({ security: [ { scheme: "bearer", type: "http" }, { name: "Authorization", type: "apiKey" }, { in: "cookie", name: "sessionid", type: "apiKey" } ], url: "/api/vehicles_api/image/{image_uuid}/", ...options }); }; var vehiclesApiV1Retrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/", ...options }); }; var vehiclesApiV1BrandsList = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/brands/", ...options }); }; var vehiclesApiV1BrandsModelsList = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/models/", ...options }); }; var vehiclesApiV1BrandsModelsVehiclesList = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/models/{model_id}/vehicles/", ...options }); }; var vehiclesApiV1BrandsModelsVehiclesRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/models/{model_id}/vehicles/{id}/", ...options }); }; var vehiclesApiV1BrandsModelsVehiclesCacheInfoRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/models/{model_id}/vehicles/cache-info/", ...options }); }; var vehiclesApiV1BrandsModelsRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/models/{id}/", ...options }); }; var vehiclesApiV1BrandsModelsCacheInfoRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/models/cache-info/", ...options }); }; var vehiclesApiV1BrandsVehiclesList = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/vehicles/", ...options }); }; var vehiclesApiV1BrandsVehiclesRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/vehicles/{id}/", ...options }); }; var vehiclesApiV1BrandsVehiclesCacheInfoRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{brand_id}/vehicles/cache-info/", ...options }); }; var vehiclesApiV1BrandsRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/brands/{id}/", ...options }); }; var vehiclesApiV1BrandsCacheInfoRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/brands/cache-info/", ...options }); }; var vehiclesApiV1SourcesList = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/sources/", ...options }); }; var vehiclesApiV1SourcesRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/sources/{id}/", ...options }); }; var vehiclesApiV1SourcesVehiclesList = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/sources/{source_id}/vehicles/", ...options }); }; var vehiclesApiV1SourcesVehiclesRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/sources/{source_id}/vehicles/{id}/", ...options }); }; var vehiclesApiV1SourcesVehiclesCacheInfoRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/sources/{source_id}/vehicles/cache-info/", ...options }); }; var vehiclesApiV1SourcesCacheInfoRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/sources/cache-info/", ...options }); }; var vehiclesApiV1StatisticsBrandComparisonRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/statistics/brand_comparison/", ...options }); }; var vehiclesApiV1StatisticsMarketOverviewRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/statistics/market_overview/", ...options }); }; var vehiclesApiV1StatisticsPriceTrendsRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/statistics/price_trends/", ...options }); }; var vehiclesApiV1StatisticsQualityInsightsRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/statistics/quality_insights/", ...options }); }; var vehiclesApiV1UrlsTestRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/urls-test/", ...options }); }; var vehiclesApiV1VehiclesList = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/", ...options }); }; var vehiclesApiV1VehiclesRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/{id}/", ...options }); }; var vehiclesApiV1VehiclesSimilarRetrieve = (options) => { return (options.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/{id}/similar/", ...options }); }; var vehiclesApiV1VehiclesCacheInfoRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/cache-info/", ...options }); }; var vehiclesApiV1VehiclesExportCsvRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/export_csv/", ...options }); }; var vehiclesApiV1VehiclesExportExcelRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/export_excel/", ...options }); }; var vehiclesApiV1VehiclesExportJsonRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/export_json/", ...options }); }; var vehiclesApiV1VehiclesStatisticsRetrieve = (options) => { return (options?.client ?? client).get({ url: "/api/vehicles_api/v1/vehicles/statistics/", ...options }); }; // src/services/BaseClient.ts var BaseClient = class { /** * API client instance */ static get api() { return client_default.getApi(); } /** * Handle API response and validate data */ static validateResponse(response, errorMessage) { if (!response.data) { throw new Error(errorMessage); } return response.data; } /** * Handle API errors with consistent logging */ static handleError(error, operation) { const errorMessage = error instanceof Error ? error.message : "Unknown error"; console.error(`${operation} failed:`, error); throw new Error(`${operation} failed: ${errorMessage}`); } /** * Execute API call with error handling */ static async executeApiCall(apiCall, operation, errorMessage) { try { const response = await apiCall(); return this.validateResponse(response, errorMessage || `Failed to ${operation}`); } catch (error) { this.handleError(error, operation); } } /** * Execute API call without response validation (for delete operations) */ static async executeApiCallNoResponse(apiCall, operation) { try { await apiCall(); } catch (error) { this.handleError(error, operation); } } /** * Get authentication status */ static isAuthenticated() { return this.api.isAuthenticated(); } /** * Get current API URL */ static getApiUrl() { return this.api.getApiUrl(); } /** * Set custom headers for API requests */ static setHeaders(headers) { this.api.setHeaders(headers); } /** * Set API key for authentication */ static setApiKey(apiKey) { this.api.setApiKey(apiKey); } /** * Clear custom headers */ static clearHeaders() { this.api.clearHeaders(); } }; // src/services/api_v1/BaseVehiclesService.ts var BaseVehiclesService = class extends BaseClient { /** * Handle paginated response with metadata */ static validatePaginatedResponse(response, errorMessage) { return this.validateResponse(response, errorMessage); } /** * Build query parameters for filtering */ static buildQueryParams(params = {}) { const cleanParams = {}; Object.entries(params).forEach(([key, value]) => { if (value !== void 0 && value !== null && value !== "") { cleanParams[key] = value; } }); return cleanParams; } /** * Handle search parameters with proper encoding */ static buildSearchParams(search, additionalParams) { const params = this.buildQueryParams(additionalParams || {}); if (search && search.trim()) { params.search = search.trim(); } return params; } /** * Handle pagination parameters */ static buildPaginationParams(page, pageSize, ordering, additionalParams) { const params = this.buildQueryParams(additionalParams || {}); if (page && page > 0) { params.page = page; } if (pageSize && pageSize > 0) { params.page_size = Math.min(pageSize, 100); } if (ordering) { params.ordering = ordering; } return params; } /** * Handle filter parameters for vehicles */ static buildVehicleFilters(filters = {}) { return this.buildQueryParams(filters); } /** * Execute vehicles API call with proper error handling */ static async executeVehiclesApiCall(apiCall, operation, errorMessage) { return this.executeApiCall(apiCall, operation, errorMessage); } /** * Get vehicles API client */ static get vehiclesApi() { return this.api.vehiclesApi; } }; // src/services/api_v1/VehiclesService.ts var VehiclesService = class extends BaseVehiclesService { // =============================== // Main Vehicle Operations // =============================== /** * Get paginated list of vehicles with advanced filtering */ static async getVehicles(params) { const query = this.buildQueryParams(params); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesList({ query }), "get vehicles list" ); } /** * Get vehicle by ID with complete details */ static async getVehicle(id) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesRetrieve({ path: { id } }), "get vehicle details" ); } /** * Find similar vehicles */ static async getSimilarVehicles(id, options) { const query = this.buildQueryParams(options); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesSimilarRetrieve({ path: { id }, query }), "get similar vehicles" ); } // =============================== // Statistics & Analytics // =============================== /** * Get vehicle statistics for filtered dataset */ static async getVehicleStatistics() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesStatisticsRetrieve(), "get vehicle statistics" ); } // =============================== // Export Operations // =============================== /** * Export vehicles to CSV */ static async exportToCsv() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesExportCsvRetrieve(), "export vehicles to CSV" ); } /** * Export vehicles to Excel */ static async exportToExcel() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesExportExcelRetrieve(), "export vehicles to Excel" ); } /** * Export vehicles to JSON */ static async exportToJson() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesExportJsonRetrieve(), "export vehicles to JSON" ); } // =============================== // Cache Management // =============================== /** * Get cache information */ static async getCacheInfo() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1VehiclesCacheInfoRetrieve(), "get cache information" ); } // =============================== // Utility Methods // =============================== /** * Search vehicles with text query */ static async searchVehicles(searchQuery, filters) { return this.getVehicles({ search: searchQuery, ...filters }); } /** * Get vehicles by brand */ static async getVehiclesByBrand(brandCode, additionalFilters) { return this.getVehicles({ brand: brandCode, ...additionalFilters }); } /** * Get vehicles by source */ static async getVehiclesBySource(sourceCode, additionalFilters) { return this.getVehicles({ source: sourceCode, ...additionalFilters }); } /** * Get high quality vehicles (A grades only) */ static async getHighQualityVehicles(additionalFilters) { return this.getVehicles({ high_quality: true, ...additionalFilters }); } /** * Get low risk vehicles */ static async getLowRiskVehicles(additionalFilters) { return this.getVehicles({ low_risk: true, ...additionalFilters }); } /** * Get vehicles with photos */ static async getVehiclesWithPhotos(additionalFilters) { return this.getVehicles({ has_photos: true, ...additionalFilters }); } /** * Get vehicles in price range */ static async getVehiclesInPriceRange(minPrice, maxPrice, additionalFilters) { return this.getVehicles({ price_min: minPrice, price_max: maxPrice, ...additionalFilters }); } /** * Get vehicles by year range */ static async getVehiclesByYearRange(minYear, maxYear, additionalFilters) { return this.getVehicles({ year_min: minYear, year_max: maxYear, ...additionalFilters }); } }; // src/services/api_v1/BrandsService.ts var BrandsService = class extends BaseVehiclesService { // =============================== // Brand Operations // =============================== /** * Get all vehicle brands with filtering */ static async getBrands(params) { const query = this.buildQueryParams(params); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsList({ query }), "get brands list" ); } /** * Get brand by ID */ static async getBrand(id) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsRetrieve({ path: { id } }), "get brand details" ); } /** * Search brands by name or code */ static async searchBrands(searchQuery, additionalFilters) { return this.getBrands({ search: searchQuery, ...additionalFilters }); } /** * Get brands by country */ static async getBrandsByCountry(country, additionalFilters) { return this.getBrands({ country_origin: country, ...additionalFilters }); } /** * Get active brands only */ static async getActiveBrands(additionalFilters) { return this.getBrands({ is_active: true, ...additionalFilters }); } /** * Get brands with vehicles */ static async getBrandsWithVehicles(additionalFilters) { return this.getBrands({ has_vehicles: true, ...additionalFilters }); } // =============================== // Brand Models Operations // =============================== /** * Get models for specific brand */ static async getBrandModels(brandId, params) { const query = this.buildQueryParams(params); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsModelsList({ path: { brand_id: brandId }, query }), "get brand models" ); } /** * Get specific model details */ static async getBrandModel(brandId, modelId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsModelsRetrieve({ path: { brand_id: brandId, id: modelId } }), "get brand model details" ); } /** * Search models within a brand */ static async searchBrandModels(brandId, searchQuery, additionalParams) { return this.getBrandModels(brandId, { search: searchQuery, ...additionalParams }); } // =============================== // Brand Vehicles Operations // =============================== /** * Get vehicles from specific brand */ static async getBrandVehicles(brandId, params) { const query = this.buildQueryParams(params); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsVehiclesList({ path: { brand_id: brandId }, query }), "get brand vehicles" ); } /** * Get specific vehicle from brand */ static async getBrandVehicle(brandId, vehicleId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsVehiclesRetrieve({ path: { brand_id: brandId, id: vehicleId } }), "get brand vehicle details" ); } /** * Get vehicles from specific brand and model */ static async getBrandModelVehicles(brandId, modelId, params) { const query = this.buildQueryParams(params); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsModelsVehiclesList({ path: { brand_id: brandId, model_id: modelId }, query }), "get brand model vehicles" ); } /** * Get specific vehicle from brand and model */ static async getBrandModelVehicle(brandId, modelId, vehicleId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsModelsVehiclesRetrieve({ path: { brand_id: brandId, model_id: modelId, id: vehicleId } }), "get brand model vehicle details" ); } // =============================== // Cache Management // =============================== /** * Get brands cache info */ static async getBrandsCacheInfo() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsCacheInfoRetrieve(), "get brands cache info" ); } /** * Get brand models cache info */ static async getBrandModelsCacheInfo(brandId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsModelsCacheInfoRetrieve({ path: { brand_id: brandId } }), "get brand models cache info" ); } /** * Get brand vehicles cache info */ static async getBrandVehiclesCacheInfo(brandId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsVehiclesCacheInfoRetrieve({ path: { brand_id: brandId } }), "get brand vehicles cache info" ); } /** * Get brand model vehicles cache info */ static async getBrandModelVehiclesCacheInfo(brandId, modelId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1BrandsModelsVehiclesCacheInfoRetrieve({ path: { brand_id: brandId, model_id: modelId } }), "get brand model vehicles cache info" ); } // =============================== // Utility Methods // =============================== /** * Get popular brands (with most vehicles) */ static async getPopularBrands(limit) { return this.getBrands({ has_vehicles: true, page_size: limit || 20 // Note: API doesn't seem to support ordering by vehicle count // This would need to be implemented on the backend }); } /** * Get brand by code */ static async getBrandByCode(code) { return this.getBrands({ code, page_size: 1 }); } /** * Get all models for a brand (without pagination) */ static async getAllBrandModels(brandId) { const result = await this.getBrandModels(brandId, { page_size: 100 }); return result.results || []; } }; // src/services/api_v1/SourcesService.ts var SourcesService = class extends BaseVehiclesService { // =============================== // Source Operations // =============================== /** * Get all data sources with filtering */ static async getSources(params) { const query = this.buildQueryParams(params); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1SourcesList({ query }), "get sources list" ); } /** * Get source by ID */ static async getSource(id) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1SourcesRetrieve({ path: { id } }), "get source details" ); } /** * Search sources by name or code */ static async searchSources(searchQuery, additionalFilters) { return this.getSources({ search: searchQuery, ...additionalFilters }); } /** * Get sources by country */ static async getSourcesByCountry(country, additionalFilters) { return this.getSources({ country, ...additionalFilters }); } /** * Get active sources only */ static async getActiveSources(additionalFilters) { return this.getSources({ is_active: true, ...additionalFilters }); } /** * Get sources with vehicles */ static async getSourcesWithVehicles(additionalFilters) { return this.getSources({ has_vehicles: true, ...additionalFilters }); } /** * Get sources by currency */ static async getSourcesByCurrency(currency, additionalFilters) { return this.getSources({ currency, ...additionalFilters }); } // =============================== // Source Vehicles Operations // =============================== /** * Get vehicles from specific source */ static async getSourceVehicles(sourceId, params) { const query = this.buildQueryParams(params); return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1SourcesVehiclesList({ path: { source_id: sourceId }, query }), "get source vehicles" ); } /** * Get specific vehicle from source */ static async getSourceVehicle(sourceId, vehicleId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1SourcesVehiclesRetrieve({ path: { source_id: sourceId, id: vehicleId } }), "get source vehicle details" ); } // =============================== // Cache Management // =============================== /** * Get sources cache info */ static async getSourcesCacheInfo() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1SourcesCacheInfoRetrieve(), "get sources cache info" ); } /** * Get source vehicles cache info */ static async getSourceVehiclesCacheInfo(sourceId) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1SourcesVehiclesCacheInfoRetrieve({ path: { source_id: sourceId } }), "get source vehicles cache info" ); } // =============================== // Utility Methods // =============================== /** * Get source by code */ static async getSourceByCode(code) { return this.getSources({ code, page_size: 1 }); } /** * Get popular sources (with most vehicles) */ static async getPopularSources(limit) { return this.getSources({ has_vehicles: true, page_size: limit || 20 }); } }; // src/services/api_v1/StatisticsService.ts var StatisticsService = class extends BaseVehiclesService { // =============================== // Market Analytics // =============================== /** * Get market overview statistics */ static async getMarketOverview() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1StatisticsMarketOverviewRetrieve(), "get market overview" ); } /** * Get price trend analysis */ static async getPriceTrends() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1StatisticsPriceTrendsRetrieve(), "get price trends" ); } /** * Get brand comparison statistics */ static async getBrandComparison() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1StatisticsBrandComparisonRetrieve(), "get brand comparison" ); } /** * Get quality insights and investment grade analysis */ static async getQualityInsights() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1StatisticsQualityInsightsRetrieve(), "get quality insights" ); } // =============================== // Utility Methods // =============================== /** * Get all statistics at once */ static async getAllStatistics() { const [marketOverview, priceTrends, brandComparison, qualityInsights] = await Promise.all([ this.getMarketOverview(), this.getPriceTrends(), this.getBrandComparison(), this.getQualityInsights() ]); return { marketOverview, priceTrends, brandComparison, qualityInsights }; } }; // src/services/api_v1/ApiService.ts var ApiService = class extends BaseVehiclesService { // =============================== // API Information // =============================== /** * Get API information and features */ static async getApiInfo() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1Retrieve(), "get API information" ); } /** * Test all API URLs and their status */ static async testAllUrls() { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiV1UrlsTestRetrieve(), "test all API URLs" ); } // =============================== // Image Proxy // =============================== /** * Get image by UUID through proxy */ static async getImage(imageUuid) { return this.executeVehiclesApiCall( () => this.vehiclesApi.vehiclesApiImageRetrieve({ path: { image_uuid: imageUuid } }), "get image through proxy" ); } // =============================== // Utility Methods // =============================== /** * Check API health and availability */ static async checkHealth() { try { const apiInfo = await this.getApiInfo(); return { status: "healthy", apiInfo, timestamp: (/* @__PURE__ */ new Date()).toISOString() }; } catch (error) { return { status: "unhealthy", error: error instanceof Error ? error.message : "Unknown error", timestamp: (/* @__PURE__ */ new Date()).toISOString() }; } } /** * Get API capabilities and features */ static async getCapabilities() { const apiInfo = await this.getApiInfo(); return { features: apiInfo.features || [], endpoints: apiInfo.endpoints || {}, rateLimits: apiInfo.rate_limits || {}, dataSources: apiInfo.data_sources || [] }; } }; // src/client.ts var TOKEN_KEY = "auth_token"; var REFRESH_TOKEN_KEY = "refresh_token"; function makeEndpoints(endpoints, client2) { const result = {}; Object.keys(endpoints).forEach((key) => { const fn = endpoints[key]; if (typeof fn === "function") { result[key] = (options = {}) => fn({ ...options, client: client2 }); } }); return result; } var API = class { constructor(apiUrl) { this.customHeaders = {}; this.apiUrl = apiUrl; this._initClients(); } _makeConfig() { const token = this.getToken(); const headers = { ...this.customHeaders }; if (token) { headers["Authorization"] = `Bearer ${token}`; } return { baseUrl: this.apiUrl, headers: Object.keys(headers).length > 0 ? headers : void 0 }; } _initClients() { const config = this._makeConfig(); this.vehiclesApi = makeEndpoints( vehicles_api_exports, createClient(createConfig(config)) ); } setHeaders(headers) { this.customHeaders = { ...this.customHeaders, ...headers }; this._initClients(); } setApiKey(apiKey) { this.setHeaders({ "X-API-Key": apiKey }); } clearHeaders() { this.customHeaders = {}; this._initClients(); } getHeaders() { return { ...this.customHeaders }; } getToken() { if (typeof window === "undefined") return null; return localStorage.getItem(TOKEN_KEY); } getRefreshToken() { if (typeof window === "undefined") return null; return localStorage.getItem(REFRESH_TOKEN_KEY); } setToken(token, refreshToken) { if (typeof window === "undefined") return; localStorage.setItem(TOKEN_KEY, token); if (refreshToken) { localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken); } this._initClients(); } clearTokens() { if (typeof window === "undefined") return; localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(REFRESH_TOKEN_KEY); this._initClients(); } isAuthenticated() { return !!this.getToken(); } setApiUrl(url) { this.apiUrl = url; this._initClients(); } getApiUrl() { return this.apiUrl; } }; var VehiclesAPIClient = class { constructor(baseUrl = "https://api.carapis.com") { // Services this.vehicles = VehiclesService; this.brands = BrandsService; this.sources = SourcesService; this.statistics = StatisticsService; this.api_service = ApiService; this.api = new API(baseUrl); } /** * Set API key for authentication */ setApiKey(apiKey) { this.api.setApiKey(apiKey); } /** * Set custom headers */ setHeaders(headers) { this.api.setHeaders(headers); } /** * Get current API URL */ getApiUrl() { return this.api.getApiUrl(); } /** * Check if authenticated */ isAuthenticated() { return this.api.isAuthenticated(); } /** * Clear custom headers */ clearHeaders() { this.api.clearHeaders(); } /** * Get