iracing-data-api
Version:
Javascript client for iracing API
950 lines (926 loc) • 43.4 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
API_URL: () => API_URL,
DEFAULT_OPTIONS: () => DEFAULT_OPTIONS,
IracingDataApiException: () => IracingDataApiException,
default: () => IracingAPI
});
module.exports = __toCommonJS(src_exports);
var import_fetch_cookie = __toESM(require("fetch-cookie"), 1);
// src/consts.ts
var API_URL = "https://members-ng.iracing.com/";
var DEFAULT_OPTIONS = {
logger: false,
manageRateLimit: false,
rateLimitPadding: 5
};
// src/helpers.ts
var import_crypto = require("crypto");
var encryptPassword = (email, password) => (0, import_crypto.createHash)("sha256").update(password + email.toLowerCase()).digest("base64");
// src/logger.ts
var createLogger = (options) => {
if (options.logger) {
return (...args) => console.log(`\x1B[34m[iracing-data-api]\x1B[0m`, ...args);
} else {
return () => {
};
}
};
// src/rate-limiter.ts
var RateLimiter = class {
constructor(options) {
this.updateRateLimit = (response) => {
if (!this.isActive) return;
this.rateLimit = this._getRateLimit(response);
};
this.checkRateLimit = () => {
if (!this.isActive) return true;
if (!this.rateLimit) return true;
if (this.rateLimit.remaining > this.limitPadding) return true;
if (this.rateLimit.reset < /* @__PURE__ */ new Date()) {
this.rateLimit = void 0;
return true;
}
return false;
};
this.waitForReset = async () => {
if (!this.isActive || !this.rateLimit) return;
const timeToReset = this.rateLimit.reset.getTime() - (/* @__PURE__ */ new Date()).getTime() + 1e3;
this.logger(
`Rate limit exceeded. Waiting for reset at ${this.rateLimit.reset.toLocaleString()}...`
);
await new Promise((resolve) => setTimeout(resolve, timeToReset));
};
this._getRateLimit = (response) => {
const limit = +response.headers.get("x-ratelimit-limit");
const remaining = +response.headers.get("x-ratelimit-remaining");
const reset = new Date(
+response.headers.get("x-ratelimit-reset") * 1e3
);
return { limit, remaining, reset };
};
this.logger = createLogger(options);
if (options.manageRateLimit) {
this.isActive = true;
this.limitPadding = options.rateLimitPadding ?? DEFAULT_OPTIONS.rateLimitPadding;
} else {
this.isActive = false;
this.limitPadding = 0;
}
}
};
// src/api/api.ts
var import_humps = __toESM(require("humps"), 1);
// src/exceptions.ts
var IracingDataApiException = class extends Error {
constructor(statusCode, endpoint, message) {
super(message);
this.statusCode = statusCode;
this.endpoint = endpoint;
}
};
// src/api/api.ts
var { camelizeKeys, decamelizeKeys } = import_humps.default;
var API = class {
constructor(fetchCookie, options, rateLimiter) {
this._getData = async (endpoint, params) => {
try {
const canProceed = this.rateLimiter.checkRateLimit();
if (!canProceed) {
await this.rateLimiter.waitForReset();
}
const url = this._getUrl(endpoint, params);
this.logger(`Getting data from '${url}'`);
const response = await this.fetchCookie(url, {
cache: "no-cache",
credentials: "include"
});
this.rateLimiter.updateRateLimit(response);
const data = await response.json();
if (!data || response.status !== 200) {
throw new IracingDataApiException(response.status, url, data);
}
return await this._getLinkData(data.link);
} catch (error) {
this.logger(`Error getting data from '${endpoint}'`);
throw error;
}
};
this._getLinkData = async (link) => {
const response = await fetch(link);
const data = await response.json();
if (!data || response.status !== 200) {
throw new IracingDataApiException(response.status, link, data);
}
if (data["chunk_info"]) {
data.data = await this._getChunks(data["chunk_info"]);
}
return camelizeKeys(data);
};
this._getUrl = (endpoint, params) => {
const searchParams = params && new URLSearchParams(
decamelizeKeys(params)
).toString();
return `${API_URL}${endpoint}${searchParams ? `?${searchParams}` : ""}`;
};
this._getChunks = async (chunks) => {
const baseUrl = chunks["base_download_url"];
const urls = chunks["chunk_file_names"].map(
(chunkFileName) => `${baseUrl}${chunkFileName}`
);
const listOfChunks = await Promise.all(
urls.map(async (url) => {
const response = await fetch(url);
return response.json();
})
);
return listOfChunks.flat();
};
this.fetchCookie = fetchCookie;
this.options = options;
this.rateLimiter = rateLimiter;
this.logger = createLogger(options);
}
};
// src/api/car.ts
var CarAPI = class extends API {
constructor() {
super(...arguments);
/**
* image paths are relative to https://images-static.iracing.com/.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.assets = () => this._getData("data/car/assets");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = () => this._getData("data/car/get");
}
};
// src/api/carclass.ts
var CarclassAPI = class extends API {
constructor() {
super(...arguments);
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = () => this._getData("data/carclass/get");
}
};
// src/api/constants.ts
var ConstantsAPI = class extends API {
constructor() {
super(...arguments);
/**
* Constant; returned directly as an array of objects.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.categories = () => this._getData("data/constants/categories");
/**
* Constant; returned directly as an array of objects.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.divisions = () => this._getData("data/constants/divisions");
/**
* Constant; returned directly as an array of objects.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.eventTypes = () => this._getData("data/constants/event_types");
}
};
// src/api/driver_stats_by_category.ts
var DriverStatsByCategoryAPI = class extends API {
constructor() {
super(...arguments);
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.oval = () => this._getData("data/driver_stats_by_category/oval");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.sportsCar = () => this._getData("data/driver_stats_by_category/sports_car");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.formulaCar = () => this._getData("data/driver_stats_by_category/formula_car");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.road = () => this._getData("data/driver_stats_by_category/road");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.dirtOval = () => this._getData("data/driver_stats_by_category/dirt_oval");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.dirtRoad = () => this._getData("data/driver_stats_by_category/dirt_road");
}
};
// src/api/hosted.ts
var HostedAPI = class extends API {
constructor() {
super(...arguments);
/**
* Sessions that can be joined as a driver or spectator, and also includes non-league pending sessions for the user.
* @param {HostedCombinedSessionsParams} params - The params required by the API.
* @param {number} [params.packageId] - If set, return only sessions using this car or track package ID.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.combinedSessions = (params) => this._getData("data/hosted/combined_sessions", params);
/**
* Sessions that can be joined as a driver.
* Without spectator and non-league pending sessions for the user.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.sessions = () => this._getData("data/hosted/sessions");
}
};
// src/api/league.ts
var LeagueAPI = class extends API {
constructor() {
super(...arguments);
/**
* @param {LeagueCustLeagueSessionsParams} params - The params required by the API.
* @param {boolean} [params.mine] - If true, return only sessions created by this user.
* @param {number} [params.packageId] - If set, return only sessions using this car or track package ID.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.custLeagueSessions = (params) => this._getData("data/league/cust_league_sessions", params);
/**
* @param {LeagueDirectoryParams} params - The params required by the API.
* @param {string} [params.search] - Will search against league name, description, owner, and league ID.
* @param {string} [params.tag] - One or more tags, comma-separated.
* @param {boolean} [params.restrictToMember] - If true include only leagues for which customer is a member.
* @param {boolean} [params.restrictToRecruiting] - If true include only leagues which are recruiting.
* @param {boolean} [params.restrictToFriends] - If true include only leagues owned by a friend.
* @param {boolean} [params.restrictToWatched] - If true include only leagues owned by a watched member.
* @param {number} [params.minimumRosterCount] - If set include leagues with at least this number of members.
* @param {number} [params.maximumRosterCount] - If set include leagues with no more than this number of members.
* @param {number} [params.lowerbound] - First row of results to return. Defaults to 1.
* @param {number} [params.upperbound] - Last row of results to return. Defaults to lowerbound + 39.
* @param {string} [params.sort] - One of relevance, leaguename, displayname, rostercount. displayname is owners's name. Defaults to relevance.
* @param {string} [params.order] - One of asc or desc. Defaults to asc.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.directory = (params) => this._getData("data/league/directory", params);
/**
* @param {LeagueGetParams} params - The params required by the API.
* @param {number} params.leagueId
* @param {boolean} [params.includeLicenses] - For faster responses, only request when necessary.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = (params) => this._getData("data/league/get", params);
/**
* @param {LeagueGetPointsSystemsParams} params - The params required by the API.
* @param {number} params.leagueId
* @param {number} [params.seasonId] - If included and the season is using custom points (points_system_id:2) then the custom points option is included in the returned list. Otherwise the custom points option is not returned.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.getPointsSystems = (params) => this._getData("data/league/get_points_systems", params);
/**
* @param {LeagueMembershipParams} params - The params required by the API.
* @param {number} [params.custId] - If different from the authenticated member, the following resrictions apply: - Caller cannot be on requested customer's block list or an empty list will result; - Requested customer cannot have their online activity prefrence set to hidden or an empty list will result; - Only leagues for which the requested customer is an admin and the league roster is not private are returned.
* @param {boolean} [params.includeLeague]
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.membership = (params) => this._getData("data/league/membership", params);
/**
* @param {LeagueRosterParams} params - The params required by the API.
* @param {number} params.leagueId
* @param {boolean} [params.includeLicenses] - For faster responses, only request when necessary.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.roster = (params) => this._getData("data/league/roster", params);
/**
* @param {LeagueSeasonsParams} params - The params required by the API.
* @param {number} params.leagueId
* @param {boolean} [params.retired] - If true include seasons which are no longer active.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasons = (params) => this._getData("data/league/seasons", params);
/**
* @param {LeagueSeasonStandingsParams} params - The params required by the API.
* @param {number} params.leagueId
* @param {number} params.seasonId
* @param {number} [params.carClassId]
* @param {number} [params.carId] - If car_class_id is included then the standings are for the car in that car class, otherwise they are for the car across car classes.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonStandings = (params) => this._getData("data/league/season_standings", params);
/**
* @param {LeagueSeasonSessionsParams} params - The params required by the API.
* @param {number} params.leagueId
* @param {number} params.seasonId
* @param {boolean} [params.resultsOnly] - If true include only sessions for which results are available.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonSessions = (params) => this._getData("data/league/season_sessions", params);
}
};
// src/api/lookup.ts
var LookupAPI = class extends API {
constructor() {
super(...arguments);
/**
* Returns an earlier history if requested quarter does not have a club history.
* @param {LookupClubHistoryParams} params - The params required by the API.
* @param {number} params.seasonYear
* @param {number} params.seasonQuarter
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.clubHistory = (params) => this._getData("data/lookup/club_history", params);
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.countries = () => this._getData("data/lookup/countries");
/**
* @param {LookupDriversParams} params - The params required by the API.
* @param {string} params.searchTerm - A cust_id or partial name for which to search.
* @param {number} [params.leagueId] - Narrow the search to the roster of the given league.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.drivers = (params) => this._getData("data/lookup/drivers", params);
/**
* ?weather=weather_wind_speed_units&weather=weather_wind_speed_max&weather=weather_wind_speed_min&licenselevels=licenselevels.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = () => this._getData("data/lookup/get");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.licenses = () => this._getData("data/lookup/licenses");
}
};
// src/api/member.ts
var MemberAPI = class extends API {
constructor() {
super(...arguments);
/**
* @param {MemberAwardsParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.awards = (params) => this._getData("data/member/awards", params);
/**
* @param {MemberChartDataParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @param {number} params.categoryId - 1 - Oval; 2 - Road; 3 - Dirt oval; 4 - Dirt road
* @param {number} params.chartType - 1 - iRating; 2 - TT Rating; 3 - License/SR
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.chartData = (params) => this._getData("data/member/chart_data", params);
/**
* @param {MemberGetParams} params - The params required by the API.
* @param {number[]} params.custIds - ?cust_ids=2,3,4
* @param {boolean} [params.includeLicenses]
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = (params) => this._getData("data/member/get", params);
/**
* Always the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.info = () => this._getData("data/member/info");
/**
* Always the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.participationCredits = () => this._getData("data/member/participation_credits");
/**
* @param {MemberProfileParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.profile = (params) => this._getData("data/member/profile", params);
}
};
// src/api/results.ts
var ResultsAPI = class extends API {
constructor() {
super(...arguments);
/**
* Get the results of a subsession, if authorized to view them.
* series_logo image paths are relative to https://images-static.iracing.com/img/logos/series/.
* @param {ResultsGetParams} params - The params required by the API.
* @param {number} params.subsessionId
* @param {boolean} [params.includeLicenses]
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = (params) => this._getData("data/results/get", params);
/**
* @param {ResultsEventLogParams} params - The params required by the API.
* @param {number} params.subsessionId
* @param {number} params.simsessionNumber - The main event is 0; the preceding event is -1, and so on.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.eventLog = (params) => this._getData("data/results/event_log", params);
/**
* @param {ResultsLapChartDataParams} params - The params required by the API.
* @param {number} params.subsessionId
* @param {number} params.simsessionNumber - The main event is 0; the preceding event is -1, and so on.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.lapChartData = (params) => this._getData("data/results/lap_chart_data", params);
/**
* @param {ResultsLapDataParams} params - The params required by the API.
* @param {number} params.subsessionId
* @param {number} params.simsessionNumber - The main event is 0; the preceding event is -1, and so on.
* @param {number} [params.custId] - Required if the subsession was a single-driver event. Optional for team events. If omitted for a team event then the laps driven by all the team's drivers will be included.
* @param {number} [params.teamId] - Required if the subsession was a team event.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.lapData = (params) => this._getData("data/results/lap_data", params);
/**
* Hosted and league sessions.
* Maximum time frame of 90 days.
* Results split into one or more files with chunks of results.
* For scraping results the most effective approach is to keep track of the maximum end_time found during a search then make the subsequent call using that date/time as the finish_range_begin and skip any subsessions that are duplicated.
* Results are ordered by subsessionid which is a proxy for start time.
* Requires one of: start_range_begin, finish_range_begin.
* Requires one of: cust_id, team_id, host_cust_id, session_name.
* @param {ResultsSearchHostedParams} params - The params required by the API.
* @param {string} [params.startRangeBegin] - Session start times. ISO-8601 UTC time zero offset: "2022-04-01T15:45Z".
* @param {string} [params.startRangeEnd] - ISO-8601 UTC time zero offset: "2022-04-01T15:45Z". Exclusive. May be omitted if start_range_begin is less than 90 days in the past.
* @param {string} [params.finishRangeBegin] - Session finish times. ISO-8601 UTC time zero offset: "2022-04-01T15:45Z".
* @param {string} [params.finishRangeEnd] - ISO-8601 UTC time zero offset: "2022-04-01T15:45Z". Exclusive. May be omitted if finish_range_begin is less than 90 days in the past.
* @param {number} [params.custId] - The participant's customer ID. Ignored if team_id is supplied.
* @param {number} [params.teamId] - The team ID to search for. Takes priority over cust_id if both are supplied.
* @param {number} [params.hostCustId] - The host's customer ID.
* @param {string} [params.sessionName] - Part or all of the session's name.
* @param {number} [params.leagueId] - Include only results for the league with this ID.
* @param {number} [params.leagueSeasonId] - Include only results for the league season with this ID.
* @param {number} [params.carId] - One of the cars used by the session.
* @param {number} [params.trackId] - The ID of the track used by the session.
* @param {number[]} [params.categoryIds] - Track categories to include in the search. Defaults to all. ?category_ids=1,2,3,4
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.searchHosted = (params) => this._getData("data/results/search_hosted", params);
/**
* Official series.
* Maximum time frame of 90 days.
* Results split into one or more files with chunks of results.
* For scraping results the most effective approach is to keep track of the maximum end_time found during a search then make the subsequent call using that date/time as the finish_range_begin and skip any subsessions that are duplicated.
* Results are ordered by subsessionid which is a proxy for start time but groups together multiple splits of a series when multiple series launch sessions at the same time.
* Requires at least one of: season_year and season_quarter, start_range_begin, finish_range_begin.
* @param {ResultsSearchSeriesParams} params - The params required by the API.
* @param {number} [params.seasonYear] - Required when using season_quarter.
* @param {number} [params.seasonQuarter] - Required when using season_year.
* @param {string} [params.startRangeBegin] - Session start times. ISO-8601 UTC time zero offset: "2022-04-01T15:45Z".
* @param {string} [params.startRangeEnd] - ISO-8601 UTC time zero offset: "2022-04-01T15:45Z". Exclusive. May be omitted if start_range_begin is less than 90 days in the past.
* @param {string} [params.finishRangeBegin] - Session finish times. ISO-8601 UTC time zero offset: "2022-04-01T15:45Z".
* @param {string} [params.finishRangeEnd] - ISO-8601 UTC time zero offset: "2022-04-01T15:45Z". Exclusive. May be omitted if finish_range_begin is less than 90 days in the past.
* @param {number} [params.custId] - Include only sessions in which this customer participated. Ignored if team_id is supplied.
* @param {number} [params.teamId] - Include only sessions in which this team participated. Takes priority over cust_id if both are supplied.
* @param {number} [params.seriesId] - Include only sessions for series with this ID.
* @param {number} [params.raceWeekNum] - Include only sessions with this race week number.
* @param {boolean} [params.officialOnly] - If true, include only sessions earning championship points. Defaults to all.
* @param {number[]} [params.eventTypes] - Types of events to include in the search. Defaults to all. ?event_types=2,3,4,5
* @param {number[]} [params.categoryIds] - License categories to include in the search. Defaults to all. ?category_ids=1,2,3,4
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.searchSeries = (params) => this._getData("data/results/search_series", params);
/**
* @param {ResultsSeasonResultsParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} [params.eventType] - Retrict to one event type: 2 - Practice; 3 - Qualify; 4 - Time Trial; 5 - Race
* @param {number} [params.raceWeekNum] - The first race week of a season is 0.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonResults = (params) => this._getData("data/results/season_results", params);
}
};
// src/api/season.ts
var SeasonAPI = class extends API {
constructor() {
super(...arguments);
/**
* @param {SeasonListParams} params - The params required by the API.
* @param {number} params.seasonYear
* @param {number} params.seasonQuarter
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.list = (params) => this._getData("data/season/list", params);
/**
* @param {SeasonRaceGuideParams} params - The params required by the API.
* @param {string} [params.from] - ISO-8601 offset format. Defaults to the current time. Include sessions with start times up to 3 hours after this time. Times in the past will be rewritten to the current time.
* @param {boolean} [params.includeEndAfterFrom] - Include sessions which start before 'from' but end after.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.raceGuide = (params) => this._getData("data/season/race_guide", params);
/**
* @param {SeasonSpectatorSubsessionidsParams} params - The params required by the API.
* @param {number[]} [params.eventTypes] - Types of events to include in the search. Defaults to all. ?event_types=2,3,4,5
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.spectatorSubsessionids = (params) => this._getData("data/season/spectator_subsessionids", params);
/**
* @param {SeasonSpectatorSubsessionidsDetailParams} params - The params required by the API.
* @param {number[]} [params.eventTypes] - Types of events to include in the search. Defaults to all. ?event_types=2,3,4,5
* @param {number[]} [params.seasonIds] - Seasons to include in the search. Defaults to all. ?season_ids=513,937
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.spectatorSubsessionidsDetail = (params) => this._getData("data/season/spectator_subsessionids_detail", params);
}
};
// src/api/series.ts
var SeriesAPI = class extends API {
constructor() {
super(...arguments);
/**
* image paths are relative to https://images-static.iracing.com/.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.assets = () => this._getData("data/series/assets");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = () => this._getData("data/series/get");
/**
* Get all seasons for a series.
* Filter list by official:true for seasons with standings.
* @param {SeriesPastSeasonsParams} params - The params required by the API.
* @param {number} params.seriesId
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.pastSeasons = (params) => this._getData("data/series/past_seasons", params);
/**
* @param {SeriesSeasonsParams} params - The params required by the API.
* @param {boolean} [params.includeSeries]
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasons = (params) => this._getData("data/series/seasons", params);
/**
* To get series and seasons for which standings should be available, filter the list by official: true.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.statsSeries = () => this._getData("data/series/stats_series");
}
};
// src/api/stats.ts
var StatsAPI = class extends API {
constructor() {
super(...arguments);
/**
* @param {StatsMemberBestsParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @param {number} [params.carId] - First call should exclude car_id; use cars_driven list in return for subsequent calls.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberBests = (params) => this._getData("data/stats/member_bests", params);
/**
* @param {StatsMemberCareerParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberCareer = (params) => this._getData("data/stats/member_career", params);
/**
* Divisions are 0-based: 0 is Division 1, 10 is Rookie.
* See /data/constants/divisons for more information.
* Always for the authenticated member.
* @param {StatsMemberDivisionParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} params.eventType - The event type code for the division type: 4 - Time Trial; 5 - Race
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberDivision = (params) => this._getData("data/stats/member_division", params);
/**
* @param {StatsMemberRecapParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @param {number} [params.year] - Season year; if not supplied the current calendar year (UTC) is used.
* @param {number} [params.season] - Season (quarter) within the year; if not supplied the recap will be fore the entire year.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberRecap = (params) => this._getData("data/stats/member_recap", params);
/**
* @param {StatsMemberRecentRacesParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberRecentRaces = (params) => this._getData("data/stats/member_recent_races", params);
/**
* @param {StatsMemberSummaryParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberSummary = (params) => this._getData("data/stats/member_summary", params);
/**
* @param {StatsMemberYearlyParams} params - The params required by the API.
* @param {number} [params.custId] - Defaults to the authenticated member.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberYearly = (params) => this._getData("data/stats/member_yearly", params);
/**
* @param {StatsSeasonDriverStandingsParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} params.carClassId
* @param {number} [params.clubId] - Defaults to all (-1).
* @param {number} [params.division] - Divisions are 0-based: 0 is Division 1, 10 is Rookie. See /data/constants/divisons for more information. Defaults to all.
* @param {number} [params.raceWeekNum] - The first race week of a season is 0.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonDriverStandings = (params) => this._getData("data/stats/season_driver_standings", params);
/**
* @param {StatsSeasonSupersessionStandingsParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} params.carClassId
* @param {number} [params.clubId] - Defaults to all (-1).
* @param {number} [params.division] - Divisions are 0-based: 0 is Division 1, 10 is Rookie. See /data/constants/divisons for more information. Defaults to all.
* @param {number} [params.raceWeekNum] - The first race week of a season is 0.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonSupersessionStandings = (params) => this._getData("data/stats/season_supersession_standings", params);
/**
* @param {StatsSeasonTeamStandingsParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} params.carClassId
* @param {number} [params.raceWeekNum] - The first race week of a season is 0.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonTeamStandings = (params) => this._getData("data/stats/season_team_standings", params);
/**
* @param {StatsSeasonTtStandingsParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} params.carClassId
* @param {number} [params.clubId] - Defaults to all (-1).
* @param {number} [params.division] - Divisions are 0-based: 0 is Division 1, 10 is Rookie. See /data/constants/divisons for more information. Defaults to all.
* @param {number} [params.raceWeekNum] - The first race week of a season is 0.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonTtStandings = (params) => this._getData("data/stats/season_tt_standings", params);
/**
* @param {StatsSeasonTtResultsParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} params.carClassId
* @param {number} params.raceWeekNum - The first race week of a season is 0.
* @param {number} [params.clubId] - Defaults to all (-1).
* @param {number} [params.division] - Divisions are 0-based: 0 is Division 1, 10 is Rookie. See /data/constants/divisons for more information. Defaults to all.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonTtResults = (params) => this._getData("data/stats/season_tt_results", params);
/**
* @param {StatsSeasonQualifyResultsParams} params - The params required by the API.
* @param {number} params.seasonId
* @param {number} params.carClassId
* @param {number} params.raceWeekNum - The first race week of a season is 0.
* @param {number} [params.clubId] - Defaults to all (-1).
* @param {number} [params.division] - Divisions are 0-based: 0 is Division 1, 10 is Rookie. See /data/constants/divisons for more information. Defaults to all.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.seasonQualifyResults = (params) => this._getData("data/stats/season_qualify_results", params);
/**
* @param {StatsWorldRecordsParams} params - The params required by the API.
* @param {number} params.carId
* @param {number} params.trackId
* @param {number} [params.seasonYear] - Limit best times to a given year.
* @param {number} [params.seasonQuarter] - Limit best times to a given quarter; only applicable when year is used.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.worldRecords = (params) => this._getData("data/stats/world_records", params);
}
};
// src/api/team.ts
var TeamAPI = class extends API {
constructor() {
super(...arguments);
/**
* @param {TeamGetParams} params - The params required by the API.
* @param {number} params.teamId
* @param {boolean} [params.includeLicenses] - For faster responses, only request when necessary.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = (params) => this._getData("data/team/get", params);
}
};
// src/api/time_attack.ts
var TimeAttackAPI = class extends API {
constructor() {
super(...arguments);
/**
* Results for the authenticated member, if any.
* @param {TimeAttackMemberSeasonResultsParams} params - The params required by the API.
* @param {number} params.taCompSeasonId
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.memberSeasonResults = (params) => this._getData("data/time_attack/member_season_results", params);
}
};
// src/api/track.ts
var TrackAPI = class extends API {
constructor() {
super(...arguments);
/**
* image paths are relative to https://images-static.iracing.com/.
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.assets = () => this._getData("data/track/assets");
/**
* @returns {Promise<any>}
* @throws {Error} - Throws an exception if the API call fails.
*/
this.get = () => this._getData("data/track/get");
}
};
// src/index.ts
var IracingAPI = class {
/**
*
* @param {Options} [options]
* @param {boolean} [options.throttleToRateLimit] - If true, will throttle requests to the rate limit.
*/
constructor(options) {
/**
*
* @param email - iRacing account email
* @param password - iRacing account password
*
* @returns
*/
this.login = async (email, password) => {
const hashPassword = encryptPassword(email, password);
const response = await this.fetchCookie(`${API_URL}auth`, {
body: JSON.stringify({ email, password: hashPassword }),
cache: "no-cache",
credentials: "include",
headers: {
"Content-Type": "application/json"
},
method: "POST"
});
if (response.status !== 200) {
this.logger("Login failed...");
return {
error: response.statusText ?? "Failed to login to iracing-data-api"
};
}
this.logger("Login successful...");
return await response.json();
};
this.fetchCookie = (0, import_fetch_cookie.default)(fetch);
this.options = options ?? DEFAULT_OPTIONS;
this.rateLimiter = new RateLimiter(this.options);
this.car = new CarAPI(this.fetchCookie, this.options, this.rateLimiter);
this.carclass = new CarclassAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.constants = new ConstantsAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.driverStatsByCategory = new DriverStatsByCategoryAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.hosted = new HostedAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.league = new LeagueAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.lookup = new LookupAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.member = new MemberAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.results = new ResultsAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.season = new SeasonAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.series = new SeriesAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.stats = new StatsAPI(this.fetchCookie, this.options, this.rateLimiter);
this.team = new TeamAPI(this.fetchCookie, this.options, this.rateLimiter);
this.timeAttack = new TimeAttackAPI(
this.fetchCookie,
this.options,
this.rateLimiter
);
this.track = new TrackAPI(this.fetchCookie, this.options, this.rateLimiter);
this.logger = createLogger(this.options);
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
API_URL,
DEFAULT_OPTIONS,
IracingDataApiException
});
//# sourceMappingURL=index.cjs.map