UNPKG

setlistfm-ts

Version:

A TypeScript client for the setlist.fm API

1,403 lines (1,377 loc) 43.1 kB
import { PaginationParams as PaginationParams$1, Artist as Artist$1, Setlist as Setlist$2, Country as Country$2 } from '@shared/types'; import { Venue as Venue$2 } from '@endpoints/venues/types'; import { City as City$2 } from '@endpoints/cities/types'; import { z } from 'zod'; /** * @file types.ts * @description Type definitions specific to artist endpoints. * @author tkozzer * @module artists */ /** * Parameters for searching artists via GET /1.0/search/artists. */ type SearchArtistsParams = PaginationParams$1 & { /** The artist's name */ artistName?: string; /** The artist's Musicbrainz Identifier (mbid) */ artistMbid?: string; /** The artist's Ticketmaster Identifier (deprecated) */ artistTmid?: number; /** The sort of the result, either sortName (default) or relevance */ sort?: "sortName" | "relevance"; }; /** * Represents a paginated response containing artists from the search endpoint. */ type Artists = { /** Array of artist objects */ artist: Artist$1[]; /** Total number of matching artists */ total: number; /** Current page number (starts at 1) */ page: number; /** Number of items per page */ itemsPerPage: number; }; /** * Represents a paginated response containing setlists for an artist. */ type Setlists$1 = { /** Array of setlist objects */ setlist: Setlist$2[]; /** Total number of setlists */ total: number; /** Current page number (starts at 1) */ page: number; /** Number of items per page */ itemsPerPage: number; }; /** * @file types.ts * @description TypeScript type definitions for cities, countries, and coordinates from the setlist.fm API. * @author tkozzer * @module cities */ /** * Represents the coordinates of a point on the globe. Mostly used for cities. */ type Coords = { /** The longitude part of the coordinates (range: -180 to 180) */ long: number; /** The latitude part of the coordinates (range: -90 to 90) */ lat: number; }; /** * Represents a country with its code and name. */ type Country$1 = { /** Two-letter country code (e.g., "US", "DE") */ code: string; /** Full name of the country (e.g., "United States", "Germany") */ name: string; }; /** * Represents a city where venues are located. Most of the original city data was taken from GeoNames.org. */ type City$1 = { /** Unique identifier for the city (GeoNames ID) */ id: string; /** The city's name, depending on the language (e.g., "München" or "Munich") */ name: string; /** The code of the city's state. Can be two-digit numeric code or string (e.g., "CA", "02") */ stateCode: string; /** The name of the city's state (e.g., "Bavaria", "California") */ state: string; /** The city's coordinates, usually of the city centre */ coords: Coords; /** The city's country */ country: Country$1; }; /** * Represents a paginated result consisting of a list of cities. */ type Cities = { /** Result list of cities */ cities: City$1[]; /** The total amount of items matching the query */ total: number; /** The current page (starts at 1) */ page: number; /** The amount of items you get per page */ itemsPerPage: number; }; /** * Query parameters for searching cities. */ type SearchCitiesParams = { /** The city's country */ country?: string; /** Name of the city */ name?: string; /** The number of the result page you'd like to have (default: 1) */ p?: number; /** State the city lies in */ state?: string; /** State code the city lies in */ stateCode?: string; }; /** * @file types.ts * @description TypeScript type definitions for countries from the setlist.fm API. * @author tkozzer * @module countries */ /** * Represents a paginated result consisting of a list of countries. * This is the response format for the GET /1.0/search/countries endpoint. */ type Countries = { /** Result list of countries */ country: Country$2[]; /** The total amount of countries available */ total: number; /** The current page (starts at 1) */ page: number; /** The amount of items you get per page */ itemsPerPage: number; }; /** * @file types.ts * @description Type definitions specific to setlists endpoints. * @author tkozzer * @module setlists */ /** * Represents a tour a setlist was part of. */ type Tour$1 = { /** The name of the tour */ name: string; }; /** * Represents a song in a setlist with performance details. */ type Song$1 = { /** The name of the song */ name: string; /** A different artist than the performing one that joined the stage for this song */ with?: Artist$1; /** The original artist of this song, if different to the performing artist */ cover?: Artist$1; /** Special incidents or additional information about the way the song was performed */ info?: string; /** Whether the song came from tape rather than being performed live */ tape?: boolean; }; /** * Represents a set in a setlist (e.g., main set, encore). */ type Set$1 = { /** The description/name of the set (e.g., "Acoustic set" or "Paul McCartney solo") */ name?: string; /** If the set is an encore, this is the number of the encore, starting with 1 */ encore?: number; /** This set's songs */ song: Song$1[]; }; /** * Represents a complete setlist from the setlist.fm API. */ type Setlist$1 = { /** The setlist's artist */ artist: Artist$1; /** The setlist's venue */ venue: Venue$2; /** The setlist's tour */ tour?: Tour$1; /** All sets of this setlist wrapped in sets object */ sets: { set: Set$1[]; }; /** Additional information on the concert */ info?: string; /** The attribution URL to which you must link wherever you use data from this setlist */ url: string; /** Unique identifier for the setlist */ id: string; /** Unique identifier of the setlist version */ versionId: string; /** Date of the concert in the format "dd-MM-yyyy" */ eventDate: string; /** Date, time, and time zone of the last update in format "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" */ lastUpdated: string; }; /** * Represents a paginated response containing setlists. */ type Setlists = { /** Array of setlist objects */ setlist: Setlist$1[]; /** Total number of setlists matching the query */ total: number; /** Current page number (starts at 1) */ page: number; /** Number of items per page */ itemsPerPage: number; }; /** * Parameters for searching setlists via GET /1.0/search/setlists. */ type SearchSetlistsParams = PaginationParams$1 & { /** The artist's Musicbrainz Identifier (mbid) */ artistMbid?: string; /** The artist's name */ artistName?: string; /** The artist's Ticketmaster Identifier (deprecated) */ artistTmid?: number; /** The city's geoId */ cityId?: string; /** The name of the city */ cityName?: string; /** The country code */ countryCode?: string; /** The date of the event (format dd-MM-yyyy) */ date?: string; /** The event's Last.fm Event ID (deprecated) */ lastFm?: number; /** The date and time (UTC) when this setlist was last updated (format yyyyMMddHHmmss) */ lastUpdated?: string; /** The state */ state?: string; /** The state code */ stateCode?: string; /** The tour name */ tourName?: string; /** The venue id */ venueId?: string; /** The name of the venue */ venueName?: string; /** The year of the event */ year?: number; }; /** * @file types.ts * @description TypeScript type definitions for venues from the setlist.fm API. * @author tkozzer * @module venues */ /** * Represents a venue where concerts take place. Venues usually consist of a venue name * and a city, but some venues may not have a city attached yet. */ type Venue$1 = { /** The city in which the venue is located (may be omitted if not available) */ city?: City$2; /** The attribution URL to the venue on setlist.fm */ url: string; /** Unique identifier for the venue */ id: string; /** The name of the venue, usually without city and country (e.g., "Madison Square Garden") */ name: string; }; /** * Represents a paginated result consisting of a list of venues. */ type Venues = { /** Result list of venues */ venue: Venue$1[]; /** The total amount of items matching the query */ total: number; /** The current page (starts at 1) */ page: number; /** The amount of items you get per page */ itemsPerPage: number; }; /** * Query parameters for searching venues. */ type SearchVenuesParams = { /** The city's geoId */ cityId?: string; /** Name of the city where the venue is located */ cityName?: string; /** The city's country (ISO 3166-1 alpha-2 code) */ country?: string; /** Name of the venue */ name?: string; /** The number of the result page you'd like to have (default: 1) */ p?: number; /** The city's state */ state?: string; /** The city's state code */ stateCode?: string; }; /** * @file types.ts * @description Core type definitions for the setlist.fm API. * @author tkozzer * @module types */ /** * Represents a MusicBrainz identifier. */ type MBID = string; /** * Represents a GeoNames identifier for cities. */ type GeoId = string; /** * Represents a setlist.fm user identifier. */ type UserId = string; /** * Represents a venue identifier. */ type VenueId = string; /** * Represents a setlist identifier. */ type SetlistId = string; /** * Represents a setlist version identifier. */ type VersionId = string; /** * Represents coordinates for geographical locations. */ type Coordinates = { /** Latitude in decimal degrees */ lat: number; /** Longitude in decimal degrees */ long: number; }; /** * Represents a country in the setlist.fm API. */ type Country = { /** ISO 3166-1 alpha-2 country code */ code: string; /** Localized name of the country */ name: string; }; /** * Represents a city in the setlist.fm API. */ type City = { /** GeoNames identifier */ id: GeoId; /** Name of the city */ name: string; /** State or province (if applicable) */ state?: string; /** State code (if applicable) */ stateCode?: string; /** Country information */ country: Country; /** Geographical coordinates */ coords: Coordinates; }; /** * Represents an artist in the setlist.fm API. */ type Artist = { /** MusicBrainz identifier */ mbid: MBID; /** Artist name */ name: string; /** Sort name for the artist (e.g., "Beatles, The" or "Springsteen, Bruce") */ sortName: string; /** Disambiguation string to distinguish between artists with same names */ disambiguation?: string; /** URL to the artist's setlists on setlist.fm */ url?: string; }; /** * Represents a venue in the setlist.fm API. */ type Venue = { /** Venue identifier */ id: VenueId; /** Venue name */ name: string; /** City where the venue is located */ city: City; /** URL to setlist.fm page */ url?: string; }; /** * Represents a tour in the setlist.fm API. */ type Tour = { /** Tour name */ name: string; }; /** * Represents a song in a setlist. */ type Song = { /** Song name */ name: string; /** Artist who originally performed the song (for covers) */ cover?: Artist; /** Additional info about the song */ info?: string; /** Whether this is a tape/recording */ tape?: boolean; }; /** * Represents a set in a setlist (e.g., main set, encore). */ type Set = { /** Name of the set (e.g., "Encore", "Set 1") */ name?: string; /** Songs in this set */ song: Song[]; /** Whether this is an encore */ encore?: boolean; }; /** * Represents a complete setlist. */ type Setlist = { /** Setlist identifier */ id: SetlistId; /** Version identifier */ versionId: VersionId; /** Date of the event (YYYY-MM-DD format) */ eventDate: string; /** Last update timestamp */ lastUpdated: string; /** Artist who performed */ artist: Artist; /** Venue where the performance took place */ venue: Venue; /** Tour information (if applicable) */ tour?: Tour; /** Sets in the setlist */ sets: { /** Array of sets */ set: Set[]; }; /** Additional info about the setlist */ info?: string; /** URL to setlist.fm page */ url?: string; }; /** * Represents a setlist.fm user. */ type User = { /** User identifier */ userId: UserId; /** Username */ username: string; /** Full name */ fullname?: string; /** Last FM username */ lastFm?: string; /** MySpace username */ mySpace?: string; /** Twitter username */ twitter?: string; /** Flickr username */ flickr?: string; /** Website URL */ website?: string; /** About text */ about?: string; /** URL to setlist.fm page */ url?: string; }; /** * Common pagination parameters for API requests. */ type PaginationParams = { /** Page number (1-based) */ p?: number; }; /** * Represents a paginated response from the API. */ type PaginatedResponse<T> = { /** Current page number */ page: number; /** Total number of items */ total: number; /** Items per page */ itemsPerPage: number; /** The data items */ data: T; }; /** * @file client.types.ts * @description Type definitions for the SetlistFM client public interface. * @author tkozzer * @module client */ /** * Public interface for the SetlistFM client. * * This interface defines all the methods available to users of the SDK, * providing type-safe access to all setlist.fm API endpoints. */ type SetlistFMClientPublic = { /** * Searches for artists based on provided criteria. * * @param {SearchArtistsParams} params - Search parameters for finding artists. * @returns {Promise<Artists>} A promise that resolves to a paginated list of artists. */ searchArtists: (params: SearchArtistsParams) => Promise<Artists>; /** * Gets detailed information about a specific artist. * * @param {string} mbid - MusicBrainz ID of the artist. * @returns {Promise<Artist>} A promise that resolves to the artist details. */ getArtist: (mbid: string) => Promise<Artist>; /** * Gets setlists for a specific artist. * * @param {string} mbid - MusicBrainz ID of the artist. * @param {number} [page] - Page number for pagination (optional). * @returns {Promise<ArtistSetlists>} A promise that resolves to a paginated list of setlists. */ getArtistSetlists: (mbid: string, page?: number) => Promise<Setlists$1>; /** * Gets a specific setlist by its ID. * * @param {string} id - The setlist ID. * @returns {Promise<Setlist>} A promise that resolves to the setlist details. */ getSetlist: (id: string) => Promise<Setlist$1>; /** * Searches for setlists based on provided criteria. * * @param {SearchSetlistsParams} params - Search parameters for finding setlists. * @returns {Promise<Setlists>} A promise that resolves to a paginated list of setlists. */ searchSetlists: (params: SearchSetlistsParams) => Promise<Setlists>; /** * Gets detailed information about a specific venue. * * @param {string} id - The venue ID. * @returns {Promise<Venue>} A promise that resolves to the venue details. */ getVenue: (id: string) => Promise<Venue$1>; /** * Searches for venues based on provided criteria. * * @param {SearchVenuesParams} params - Search parameters for finding venues. * @returns {Promise<Venues>} A promise that resolves to a paginated list of venues. */ searchVenues: (params: SearchVenuesParams) => Promise<Venues>; /** * Gets setlists for a specific venue. * * @param {string} id - The venue ID. * @returns {Promise<ArtistSetlists>} A promise that resolves to a paginated list of setlists. */ getVenueSetlists: (id: string) => Promise<Setlists$1>; /** * Searches for cities based on provided criteria. * * @param {SearchCitiesParams} params - Search parameters for finding cities. * @returns {Promise<Cities>} A promise that resolves to a paginated list of cities. */ searchCities: (params: SearchCitiesParams) => Promise<Cities>; /** * Gets a city by its GeoNames ID. * * @param {string} geoId - The GeoNames ID of the city. * @returns {Promise<City>} A promise that resolves to the city details. */ getCityByGeoId: (geoId: string) => Promise<City$1>; /** * Gets a list of all available countries. * * @returns {Promise<Countries>} A promise that resolves to a paginated list of countries. */ searchCountries: () => Promise<Countries>; /** * Updates the language for subsequent API requests. * * @param {string} language - Language code for internationalization. */ setLanguage: (language: string) => void; /** * Gets the base URL being used for API requests. * * @returns {string} The base URL of the setlist.fm API. */ getBaseUrl: () => string; /** * Gets the underlying HTTP client for advanced usage. * * @returns {HttpClient} The HTTP client instance. */ getHttpClient: () => any; /** * Gets the current rate limit status. * * @returns {object} Rate limit status information. */ getRateLimitStatus: () => any; }; /** * @file rateLimiter.ts * @description Rate limiting utilities for managing API request throttling. * @author tkozzer * @module rateLimiter */ /** * Rate limit profile configurations for setlist.fm API. */ declare enum RateLimitProfile { /** Standard profile: 2 requests/second, 1440 requests/day */ STANDARD = "standard", /** Premium profile: 16 requests/second, 50,000 requests/day */ PREMIUM = "premium", /** No rate limiting (advanced users) */ DISABLED = "disabled" } /** * Rate limit configuration. */ type RateLimitConfig = { /** Rate limit profile to use */ profile: RateLimitProfile; /** Requests per second (overrides profile if specified) */ requestsPerSecond?: number; /** Requests per day (overrides profile if specified) */ requestsPerDay?: number; /** Whether to queue requests when rate limited */ queueRequests?: boolean; /** Maximum queue size for requests */ maxQueueSize?: number; /** Callback for when rate limit is approached */ onRateLimitApproached?: (remaining: number, resetTime: number) => void; /** Callback for when rate limit is exceeded */ onRateLimitExceeded?: (retryAfter: number) => void; }; /** * Rate limit status information. */ type RateLimitStatus = { /** Current rate limit profile */ profile: RateLimitProfile; /** Whether a request can be made immediately */ canMakeRequest: boolean; /** Requests made in current second */ requestsThisSecond: number; /** Maximum requests per second */ secondLimit?: number; /** Requests made in current day */ requestsThisDay: number; /** Maximum requests per day */ dayLimit?: number; /** Current queue size */ queueSize: number; /** Milliseconds until next request can be made */ retryAfter?: number; }; /** * Gets the predefined rate limit settings for a profile. * * @param {RateLimitProfile} profile - The rate limit profile. * @returns {Pick<RateLimitConfig, 'requestsPerSecond' | 'requestsPerDay'>} Rate limit settings. */ declare function getProfileSettings(profile: RateLimitProfile): Pick<RateLimitConfig, "requestsPerSecond" | "requestsPerDay">; /** * Rate limiter for managing API request throttling. */ declare class RateLimiter { private readonly config; private readonly state; constructor(config: RateLimitConfig); /** * Checks if a request can be made immediately. * * @returns {boolean} True if request can be made immediately. */ canMakeRequest(): boolean; /** * Records a request being made. */ recordRequest(): void; /** * Waits for the next available request slot. * * @returns {Promise<void>} Promise that resolves when request can be made. */ waitForNextSlot(): Promise<void>; /** * Gets the time until the next request can be made. * * @returns {number} Milliseconds until next request slot. */ getRetryAfter(): number; /** * Gets the next reset time for rate limits. * * @returns {number} Timestamp when rate limits reset. */ getNextResetTime(): number; /** * Gets current rate limit status. * * @returns {RateLimitStatus} Current rate limit status. */ getStatus(): RateLimitStatus; /** * Updates the time windows and resets counters if needed. */ private updateWindows; /** * Processes the request queue when slots become available. */ private processQueue; } /** * @file http.ts * @description HTTP client utilities for making requests to the setlist.fm API. * @author tkozzer * @module http */ /** Base URL for the setlist.fm API */ declare const API_BASE_URL = "https://api.setlist.fm/rest/1.0"; /** Default timeout for API requests in milliseconds */ declare const DEFAULT_TIMEOUT = 10000; /** * Configuration options for the HTTP client. */ type HttpClientConfig = { /** API key for authentication */ apiKey: string; /** User agent string for identifying your application */ userAgent: string; /** Request timeout in milliseconds */ timeout?: number; /** Language code for internationalization (e.g., 'en', 'es', 'fr') */ language?: string; /** Rate limiting configuration (required) */ rateLimit: RateLimitConfig; }; /** * Error thrown when API requests fail. */ declare class SetlistFMError extends Error { statusCode?: number | undefined; response?: any | undefined; constructor(message: string, statusCode?: number | undefined, response?: any | undefined); } /** * HTTP client for the setlist.fm API with built-in authentication, error handling, and rate limiting. */ declare class HttpClient { private readonly client; private readonly rateLimiter; constructor(config: HttpClientConfig); /** * Sets up response interceptor for error handling. */ private setupResponseInterceptor; /** * Makes a GET request to the specified endpoint. * * @param {string} endpoint - The API endpoint to request (without base URL). * @param {Record<string, any>} params - Query parameters to include in the request. * @returns {Promise<T>} A promise that resolves to the response data. * @throws {SetlistFMError} If the request fails or returns an error response. * * @example * ```ts * const data = await httpClient.get('/artist/1234-abcd', { p: 1 }); * ``` */ get<T = any>(endpoint: string, params?: Record<string, any>): Promise<T>; /** * Updates the language for subsequent requests. * * @param {string} language - Language code (e.g., 'en', 'es', 'fr'). */ setLanguage(language: string): void; /** * Gets the current base URL being used by the client. * * @returns {string} The base URL. */ getBaseUrl(): string; /** * Gets the rate limiter instance. * * @returns {RateLimiter} The rate limiter instance. */ getRateLimiter(): RateLimiter; /** * Gets the current rate limit status. * * @returns {object} Rate limit status. */ getRateLimitStatus(): ReturnType<RateLimiter["getStatus"]>; } /** * @file client.ts * @description Main SetlistFM client for accessing the setlist.fm API. * @author tkozzer * @module client */ /** * Configuration options for the SetlistFM client. */ type SetlistFMClientConfig = { /** API key for authentication with setlist.fm */ apiKey: string; /** User agent string for identifying your application */ userAgent: string; /** Request timeout in milliseconds */ timeout?: number; /** Language code for internationalization (e.g., 'en', 'es', 'fr', 'de', 'pt', 'tr', 'it', 'pl') */ language?: string; /** Rate limiting configuration (defaults to STANDARD profile if not provided) */ rateLimit?: RateLimitConfig; }; /** * Main client for interacting with the setlist.fm API. * * Provides access to all API endpoints through organized modules for artists, * setlists, venues, cities, countries, and users. * * Rate limiting is enabled by default using the STANDARD profile (2 req/sec, 1440 req/day). * To use a different profile or disable rate limiting, explicitly set the rateLimit configuration. */ declare class SetlistFMClient implements SetlistFMClientPublic { private readonly httpClient; constructor(config: SetlistFMClientConfig); /** * Updates the language for subsequent API requests. * * @param {string} language - Language code for internationalization. * * @example * ```ts * client.setLanguage('es'); // Switch to Spanish * ``` */ setLanguage(language: string): void; /** * Gets the base URL being used for API requests. * * @returns {string} The base URL of the setlist.fm API. */ getBaseUrl(): string; /** * Gets the underlying HTTP client for advanced usage. * * @returns {HttpClient} The HTTP client instance. */ getHttpClient(): HttpClient; /** * Gets the current rate limit status. * * @returns {object} Rate limit status information. */ getRateLimitStatus(): ReturnType<HttpClient["getRateLimitStatus"]>; /** * Searches for artists based on provided criteria. * * @param {SearchArtistsParams} params - Search parameters for finding artists. * @returns {Promise<Artists>} A promise that resolves to a paginated list of artists. */ searchArtists(params: SearchArtistsParams): Promise<Artists>; /** * Gets detailed information about a specific artist. * * @param {string} mbid - MusicBrainz ID of the artist. * @returns {Promise<Artist>} A promise that resolves to the artist details. */ getArtist(mbid: string): Promise<Artist>; /** * Gets setlists for a specific artist. * * @param {string} mbid - MusicBrainz ID of the artist. * @param {number} [page] - Page number for pagination (optional). * @returns {Promise<ArtistSetlists>} A promise that resolves to a paginated list of setlists. */ getArtistSetlists(mbid: string, page?: number): Promise<Setlists$1>; /** * Gets a specific setlist by its ID. * * @param {string} id - The setlist ID. * @returns {Promise<Setlist>} A promise that resolves to the setlist details. */ getSetlist(id: string): Promise<Setlist$1>; /** * Searches for setlists based on provided criteria. * * @param {SearchSetlistsParams} params - Search parameters for finding setlists. * @returns {Promise<Setlists>} A promise that resolves to a paginated list of setlists. */ searchSetlists(params: SearchSetlistsParams): Promise<Setlists>; /** * Gets detailed information about a specific venue. * * @param {string} id - The venue ID. * @returns {Promise<Venue>} A promise that resolves to the venue details. */ getVenue(id: string): Promise<Venue$1>; /** * Searches for venues based on provided criteria. * * @param {SearchVenuesParams} params - Search parameters for finding venues. * @returns {Promise<Venues>} A promise that resolves to a paginated list of venues. */ searchVenues(params: SearchVenuesParams): Promise<Venues>; /** * Gets setlists for a specific venue. * * @param {string} id - The venue ID. * @returns {Promise<ArtistSetlists>} A promise that resolves to a paginated list of setlists. */ getVenueSetlists(id: string): Promise<Setlists$1>; /** * Searches for cities based on provided criteria. * * @param {SearchCitiesParams} params - Search parameters for finding cities. * @returns {Promise<Cities>} A promise that resolves to a paginated list of cities. */ searchCities(params: SearchCitiesParams): Promise<Cities>; /** * Gets a city by its GeoNames ID. * * @param {string} geoId - The GeoNames ID of the city. * @returns {Promise<City>} A promise that resolves to the city details. */ getCityByGeoId(geoId: string): Promise<City$1>; /** * Gets a list of all available countries. * * @returns {Promise<Countries>} A promise that resolves to a paginated list of countries. */ searchCountries(): Promise<Countries>; } /** * Creates a new SetlistFM client instance. * * Rate limiting is enabled by default using the STANDARD profile (2 req/sec, 1440 req/day). * To use a different profile, explicitly provide a rateLimit configuration. * * @param {SetlistFMClientConfig} config - Configuration options for the client. * @returns {SetlistFMClientPublic} A new SetlistFM client instance with public API. * @throws {Error} If required configuration is missing or invalid. * * @example * ```ts * // Default rate limiting (STANDARD profile) * const client = createSetlistFMClient({ * apiKey: 'your-api-key-here', * userAgent: 'your-app-name (your-email@example.com)', * }); * * // Premium rate limiting * const premiumClient = createSetlistFMClient({ * apiKey: 'your-api-key-here', * userAgent: 'your-app-name (your-email@example.com)', * rateLimit: { profile: RateLimitProfile.PREMIUM } * }); * * // Disable rate limiting * const noLimitClient = createSetlistFMClient({ * apiKey: 'your-api-key-here', * userAgent: 'your-app-name (your-email@example.com)', * rateLimit: { profile: RateLimitProfile.DISABLED } * }); * ``` */ declare function createSetlistFMClient(config: SetlistFMClientConfig): SetlistFMClientPublic; /** * @file error.ts * @description Error handling utilities for the setlist.fm API. * @author tkozzer * @module error */ /** * Base error class for setlist.fm API errors. */ declare class SetlistFMAPIError extends Error { readonly statusCode?: number | undefined; readonly endpoint?: string | undefined; readonly response?: any | undefined; constructor(message: string, statusCode?: number | undefined, endpoint?: string | undefined, response?: any | undefined); } /** * Error thrown when authentication fails (invalid API key). */ declare class AuthenticationError extends SetlistFMAPIError { constructor(message?: string); } /** * Error thrown when a resource is not found (404). */ declare class NotFoundError extends SetlistFMAPIError { constructor(resource: string, identifier: string); } /** * Error thrown when rate limits are exceeded (429). */ declare class RateLimitError extends SetlistFMAPIError { constructor(message?: string); } /** * Error thrown when validation fails (400). */ declare class ValidationError extends SetlistFMAPIError { readonly field?: string | undefined; constructor(message: string, field?: string | undefined); } /** * Error thrown when the server encounters an internal error (500). */ declare class ServerError extends SetlistFMAPIError { constructor(message?: string); } /** * Creates an appropriate error instance based on the HTTP status code. * * @param {number} statusCode - HTTP status code. * @param {string} message - Error message. * @param {string} endpoint - API endpoint that caused the error. * @param {any} response - Raw response data. * @returns {SetlistFMAPIError} An appropriate error instance. */ declare function createErrorFromResponse(statusCode: number, message: string, endpoint?: string, response?: any): SetlistFMAPIError; /** * @file metadata.ts * @description Metadata utilities for setlist.fm API responses. * @author tkozzer * @module metadata */ /** * API response metadata. */ type ResponseMetadata = { /** Timestamp when the response was generated */ timestamp: string; /** API version used */ apiVersion: string; /** Request ID for debugging */ requestId?: string; }; /** * Library version and build information. */ type LibraryInfo = { /** Library version */ version: string; /** Library name */ name: string; /** Build timestamp */ buildTime?: string; /** Git commit hash */ commit?: string; }; /** * Creates response metadata from HTTP headers and other sources. * * @param {Record<string, string>} headers - HTTP response headers. * @param {string} apiVersion - API version used for the request. * @returns {ResponseMetadata} Response metadata object. */ declare function createResponseMetadata(headers: Record<string, string>, apiVersion?: string): ResponseMetadata; /** * Gets library information. * * @returns {LibraryInfo} Library version and build information. */ declare function getLibraryInfo(): LibraryInfo; /** * @file pagination.ts * @description Pagination utilities for setlist.fm API responses. * @author tkozzer * @module pagination */ /** * Extended pagination parameters with additional options. */ type ExtendedPaginationParams = PaginationParams & { /** Maximum number of pages to fetch (for auto-pagination) */ maxPages?: number; /** Delay between requests in milliseconds (for auto-pagination) */ delay?: number; }; /** * Metadata about pagination state. */ type PaginationInfo = { /** Current page number */ currentPage: number; /** Total number of items across all pages */ totalItems: number; /** Items per page */ itemsPerPage: number; /** Total number of pages */ totalPages: number; /** Whether there are more pages available */ hasNextPage: boolean; /** Whether there are previous pages */ hasPrevPage: boolean; }; /** * Extracts pagination information from an API response. * * @param {PaginatedResponse<any>} response - The paginated API response. * @returns {PaginationInfo} Pagination metadata. */ declare function extractPaginationInfo(response: PaginatedResponse<any>): PaginationInfo; /** * Creates pagination parameters for the next page. * * @param {PaginationInfo} info - Current pagination info. * @returns {PaginationParams | null} Parameters for next page, or null if no next page. */ declare function getNextPageParams(info: PaginationInfo): PaginationParams | null; /** * Creates pagination parameters for the previous page. * * @param {PaginationInfo} info - Current pagination info. * @returns {PaginationParams | null} Parameters for previous page, or null if no previous page. */ declare function getPrevPageParams(info: PaginationInfo): PaginationParams | null; /** * Utility function to create a delay between requests. * * @param {number} ms - Milliseconds to delay. * @returns {Promise<void>} Promise that resolves after the delay. */ declare function delay(ms: number): Promise<void>; /** * Validates pagination parameters. * * @param {PaginationParams} params - Pagination parameters to validate. * @throws {Error} If parameters are invalid. */ declare function validatePaginationParams(params: PaginationParams): void; /** * @file validation.ts * @description Shared validation schemas using Zod for the setlist.fm API. * @author tkozzer * @module validation */ /** * Schema for MusicBrainz MBID validation. * MBIDs are UUIDs in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx */ declare const MbidSchema: z.ZodString; /** * Schema for pagination parameters. */ declare const PaginationSchema: z.ZodObject<{ /** Page number (1-based) */ p: z.ZodOptional<z.ZodNumber>; }, "strip", z.ZodTypeAny, { p?: number | undefined; }, { p?: number | undefined; }>; /** * Schema for extended pagination with items per page. */ declare const ExtendedPaginationSchema: z.ZodObject<{ /** Page number (1-based) */ p: z.ZodOptional<z.ZodNumber>; } & { /** Number of items per page */ itemsPerPage: z.ZodOptional<z.ZodNumber>; }, "strip", z.ZodTypeAny, { p?: number | undefined; itemsPerPage?: number | undefined; }, { p?: number | undefined; itemsPerPage?: number | undefined; }>; /** * Schema for language codes (ISO 639-1). */ declare const LanguageSchema: z.ZodString; /** * Schema for sort order options. */ declare const SortOrderSchema: z.ZodEnum<["asc", "desc"]>; /** * Schema for date strings in YYYY-MM-DD format. */ declare const DateSchema: z.ZodEffects<z.ZodString, string, string>; /** * Schema for date range parameters. */ declare const DateRangeSchema: z.ZodEffects<z.ZodObject<{ /** Start date */ from: z.ZodOptional<z.ZodEffects<z.ZodString, string, string>>; /** End date */ to: z.ZodOptional<z.ZodEffects<z.ZodString, string, string>>; }, "strip", z.ZodTypeAny, { from?: string | undefined; to?: string | undefined; }, { from?: string | undefined; to?: string | undefined; }>, { from?: string | undefined; to?: string | undefined; }, { from?: string | undefined; to?: string | undefined; }>; /** * Schema for basic string validation with trimming. */ declare const NonEmptyStringSchema: z.ZodString; /** * Schema for optional string that can be empty. */ declare const OptionalStringSchema: z.ZodOptional<z.ZodString>; /** * Schema for URL validation. */ declare const UrlSchema: z.ZodOptional<z.ZodString>; /** * Validates and parses data using a Zod schema. * * @param {z.ZodSchema<T>} schema - The Zod schema to validate against. * @param {unknown} data - The data to validate. * @param {string} context - Context for error messages (e.g., "MBID parameter"). * @returns {T} The validated and parsed data. * @throws {ValidationError} If validation fails. * * @example * ```ts * const validMbid = validateWithSchema(MbidSchema, userInput, "artist MBID"); * ``` */ declare function validateWithSchema<T>(schema: z.ZodSchema<T>, data: unknown, context: string): T; /** * Safely validates data and returns either the parsed result or an error. * * @param {z.ZodSchema<T>} schema - The Zod schema to validate against. * @param {unknown} data - The data to validate. * @returns {{ success: true; data: T } | { success: false; error: z.ZodError }} Validation result. */ declare function safeValidate<T>(schema: z.ZodSchema<T>, data: unknown): { success: true; data: T; } | { success: false; error: z.ZodError; }; /** * @file logger.ts * @description Simple logging utility for development and debugging. * @author tkozzer * @module logger */ /** Log levels for the logger */ declare enum LogLevel { /** No logging output */ SILENT = -1, ERROR = 0, WARN = 1, INFO = 2, DEBUG = 3 } /** * Configuration options for the logger. */ type LoggerConfig = { /** Minimum log level to output */ level: LogLevel; /** Whether to include timestamps in log output */ includeTimestamp?: boolean; /** Whether to include file and line location in log output */ includeLocation?: boolean; /** Custom prefix for log messages */ prefix?: string; }; /** * Simple logger for debugging and development. */ declare class Logger { private readonly config; constructor(config: LoggerConfig); /** * Logs an error message. * * @param {string} message - The message to log. * @param {...any} args - Additional arguments to log. */ error(message: string, ...args: any[]): void; /** * Logs a warning message. * * @param {string} message - The message to log. * @param {...any} args - Additional arguments to log. */ warn(message: string, ...args: any[]): void; /** * Logs an info message. * * @param {string} message - The message to log. * @param {...any} args - Additional arguments to log. */ info(message: string, ...args: any[]): void; /** * Logs a debug message. * * @param {string} message - The message to log. * @param {...any} args - Additional arguments to log. */ debug(message: string, ...args: any[]): void; /** * Extracts the caller's file and line information from the stack trace. * * @returns {string | null} The caller location or null if not available. */ private getCallerLocation; /** * Internal logging method that formats and outputs messages. * * @param {string} level - The log level string. * @param {string} message - The message to log. * @param {...any} args - Additional arguments to log. */ private log; } /** * Creates a new logger instance. * * @param {LoggerConfig} config - Configuration for the logger. * @returns {Logger} A new logger instance. * * @example * ```ts * const logger = createLogger({ * level: LogLevel.INFO, * includeTimestamp: true, * includeLocation: true * }); * logger.info('Client initialized'); * // Output: [2023-01-01T12:00:00.000Z] [client.ts:15] [SetlistFM] [INFO] Client initialized * ``` */ declare function createLogger(config: LoggerConfig): Logger; /** * Creates a silent logger that produces no output. * * @returns {Logger} A silent logger instance. * * @example * ```ts * const logger = createSilentLogger(); * logger.error('This will not be logged'); * ``` */ declare function createSilentLogger(): Logger; /** Default logger instance for the library */ declare const defaultLogger: Logger; export { API_BASE_URL, AuthenticationError, DEFAULT_TIMEOUT, DateRangeSchema, DateSchema, ExtendedPaginationSchema, HttpClient, LanguageSchema, LogLevel, Logger, MbidSchema, NonEmptyStringSchema, NotFoundError, OptionalStringSchema, PaginationSchema, RateLimitError, RateLimitProfile, RateLimiter, ServerError, SetlistFMAPIError, SetlistFMClient, SetlistFMError, SortOrderSchema, UrlSchema, ValidationError, createErrorFromResponse, createLogger, createResponseMetadata, createSetlistFMClient, createSilentLogger, defaultLogger, delay, extractPaginationInfo, getLibraryInfo, getNextPageParams, getPrevPageParams, getProfileSettings, safeValidate, validatePaginationParams, validateWithSchema }; export type { Artist, City, Coordinates, Country, ExtendedPaginationParams, GeoId, HttpClientConfig, LibraryInfo, LoggerConfig, MBID, PaginatedResponse, PaginationInfo, PaginationParams, RateLimitConfig, RateLimitStatus, ResponseMetadata, Set, Setlist, SetlistFMClientConfig, SetlistId, Song, Tour, User, UserId, Venue, VenueId, VersionId };