/** * Tratok Labs API client for JavaScript: Node 18 or newer, Deno, Bun. One file, no dependencies. * Version 1.0.0, made from API description 1.5.0. https://developer.tratok.net/libraries.php * * Keep your secret on a server. Never put it in a web page or in an app that people download. * * import { TratokLabs, TratokLabsError } from './tratok-labs.mjs'; * * const labs = new TratokLabs('YOUR_APP_ID', 'YOUR_SECRET'); * try { * const found = await labs.searchCruises({ region: 'caribbean', limit: 3 }); * console.log(found.total, found.items); * } catch (e) { * if (e instanceof TratokLabsError) console.error(e.code, e.message, e.requestId); * else throw e; * } * * Every method takes one object of fields and resolves to the answer of the API. A refused call rejects * with a TratokLabsError. Field names are those of the reference: https://developer.tratok.net/docs.php * * You may use, copy and change this file in your own projects. It comes without warranty of any kind. */ export const VERSION = '1.0.0'; /** A call that was refused, or that never got an answer. */ export class TratokLabsError extends Error { constructor(message, info = {}) { super(message); this.name = 'TratokLabsError'; this.code = info.code || 'unknown'; // the short code of the API, such as invalid_credentials; 'network' or 'timeout' when no answer came this.status = info.status || 0; // the HTTP status; 0 when no answer came this.requestId = info.requestId || null; // quote this if you write to us this.retryAfter = info.retryAfter ?? null; // seconds to wait, with rate_limited this.body = info.body ?? null; // the whole answer, when there was one } } export class TratokLabs { /** * @param {string|number} appId your app ID * @param {string} secret your secret (or a test key, for the booking test mode) * @param {{baseUrl?: string, timeoutMs?: number, fetch?: Function}} [options] */ constructor(appId, secret, options = {}) { if (!appId || !secret) throw new TypeError('TratokLabs needs an app ID and a secret'); this.appId = String(appId); this.secret = String(secret); this.baseUrl = options.baseUrl || 'https://developer.tratok.net/v1/'; this.timeoutMs = options.timeoutMs || 30000; this.fetch = options.fetch || globalThis.fetch; if (typeof this.fetch !== 'function') throw new TypeError('No fetch function found: use Node 18 or newer, or pass options.fetch'); /** Facts about the last answer: status, requestId, rateLimitLimit, rateLimitRemaining, rateLimitReset, freeCallsRemaining. */ this.lastMeta = null; } /** Call any method by its name. Fields that are undefined or null are not sent. */ async call(method, fields = {}) { const body = { request: String(method), id: this.appId, secret: this.secret }; for (const [k, v] of Object.entries(fields || {})) { if (v !== undefined && v !== null) body[k] = v; } const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), this.timeoutMs); let res, text; try { res = await this.fetch.call(globalThis, this.baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'tratok-labs-js/' + VERSION }, body: JSON.stringify(body), signal: ctl.signal, }); text = await res.text(); } catch (e) { const timedOut = !!e && e.name === 'AbortError'; throw new TratokLabsError(timedOut ? 'The call timed out' : 'The call could not be made: ' + (e && e.message ? e.message : String(e)), { code: timedOut ? 'timeout' : 'network' }); } finally { clearTimeout(timer); } const num = (name) => { const v = res.headers.get(name); return v === null || v === '' || Number.isNaN(Number(v)) ? null : Number(v); }; this.lastMeta = { status: res.status, requestId: res.headers.get('x-request-id'), rateLimitLimit: num('x-ratelimit-limit'), rateLimitRemaining: num('x-ratelimit-remaining'), rateLimitReset: num('x-ratelimit-reset'), freeCallsRemaining: num('x-free-calls-remaining'), }; let data = null; try { data = JSON.parse(text); } catch (e) { data = null; } if (data === null || typeof data !== 'object') { throw new TratokLabsError('The answer was not JSON (HTTP ' + res.status + ')', { code: 'bad_answer', status: res.status, requestId: this.lastMeta.requestId, body: text }); } if (!res.ok || data.status === 'Error') { throw new TratokLabsError(data.message || 'The call was refused', { code: data.code, status: res.status, requestId: data.requestId || this.lastMeta.requestId, retryAfter: data.retryAfter, body: data, }); } return data; } // Hotels /** Fields: country. */ hotelsInCountry(fields = {}) { return this.call('hotelsInCountry', fields); } /** Fields: city. */ hotelsInCity(fields = {}) { return this.call('hotelsInCity', fields); } /** Fields: hotelId. */ getHotelInformation(fields = {}) { return this.call('getHotelInformation', fields); } /** Fields: hotelId. */ getHotelGallery(fields = {}) { return this.call('getHotelGallery', fields); } // Car rentals /** No fields. */ getListOfCarCities(fields = {}) { return this.call('getListOfCarCities', fields); } /** Fields: city. */ getListOfAllCarVenuesInCity(fields = {}) { return this.call('getListOfAllCarVenuesInCity', fields); } /** Fields: locationId. */ getListOfCarsAtVenue(fields = {}) { return this.call('getListOfCarsAtVenue', fields); } // Cruises /** Fields: q?, region?, lineId?, port?, month?, nightsMin?, nightsMax?, priceMax?, sort?, limit?, offset?. (? = optional) */ searchCruises(fields = {}) { return this.call('searchCruises', fields); } /** Fields: cruiseId. */ getCruise(fields = {}) { return this.call('getCruise', fields); } /** No fields. */ getCruiseRegions(fields = {}) { return this.call('getCruiseRegions', fields); } /** No fields. */ getCruiseLines(fields = {}) { return this.call('getCruiseLines', fields); } // Translation /** No fields. */ supportedLanguages(fields = {}) { return this.call('supportedLanguages', fields); } /** Fields: text. */ detectLanguage(fields = {}) { return this.call('detectLanguage', fields); } /** Fields: text, sourceLanguage?, targetLanguage. (? = optional) */ translate(fields = {}) { return this.call('translate', fields); } // Tara AI /** Fields: message, conversationId?, maxTokens?. (? = optional) */ taraChat(fields = {}) { return this.call('taraChat', fields); } /** Fields: conversationId. */ taraReset(fields = {}) { return this.call('taraReset', fields); } // Inventory and booking /** Fields: q?, city?, country?, nearLat?, nearLng?, radiusKm?, limit?, offset?. (? = optional) */ searchStays(fields = {}) { return this.call('searchStays', fields); } /** Fields: q?, city?, country?, nearLat?, nearLng?, radiusKm?, limit?, offset?. (? = optional) */ searchActivities(fields = {}) { return this.call('searchActivities', fields); } /** Fields: q?, city?, country?, nearLat?, nearLng?, radiusKm?, limit?, offset?. (? = optional) */ searchRestaurants(fields = {}) { return this.call('searchRestaurants', fields); } /** Fields: vertical?, listingId. (? = optional) */ getListing(fields = {}) { return this.call('getListing', fields); } /** Fields: accessToken, vertical, listingId, roomId?, packageId?, checkIn?, checkOut?, guests?, date?, participants?, time?, party?. (? = optional) */ getQuote(fields = {}) { return this.call('getQuote', fields); } /** Fields: accessToken, vertical?, listingId?, roomId?, packageId?, checkIn?, checkOut?, guests?, date?, participants?, time?, party?, quoteId, idempotencyKey, guestName?, guestPhone?, notes?. (? = optional) */ bookListing(fields = {}) { return this.call('bookListing', fields); } /** Fields: accessToken, tab?. (? = optional) */ myBookings(fields = {}) { return this.call('myBookings', fields); } /** Fields: accessToken, bookingId. */ getBooking(fields = {}) { return this.call('getBooking', fields); } /** Fields: accessToken, bookingId. */ cancelBooking(fields = {}) { return this.call('cancelBooking', fields); } } export default TratokLabs;