dataandapis 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,411 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+
10
+ // src/errors.ts
11
+ var DataAndApisError = class extends Error {
12
+ constructor(message, options) {
13
+ super(message);
14
+ this.name = new.target.name;
15
+ if (options && "cause" in options) this.cause = options.cause;
16
+ Object.setPrototypeOf(this, new.target.prototype);
17
+ }
18
+ };
19
+ var ApiError = class extends DataAndApisError {
20
+ constructor(message, details) {
21
+ super(message);
22
+ this.status = details.status;
23
+ this.api = details.api;
24
+ this.method = details.method;
25
+ this.url = details.url;
26
+ this.body = details.body;
27
+ this.tokensRemaining = details.tokensRemaining;
28
+ }
29
+ };
30
+ var AuthenticationError = class extends ApiError {
31
+ };
32
+ var PaymentRequiredError = class extends ApiError {
33
+ get paymentUrl() {
34
+ const url = this.body?.payment_url;
35
+ return typeof url === "string" ? url : void 0;
36
+ }
37
+ };
38
+ var QuotaExceededError = class extends ApiError {
39
+ };
40
+ var ConnectionError = class extends DataAndApisError {
41
+ };
42
+ var TimeoutError = class extends DataAndApisError {
43
+ };
44
+
45
+ // src/generated/endpoints.ts
46
+ var APIS = {
47
+ airQuality: ["air-quality", "https://api-air-quality.dataandapis.com", { dataSources: "GET /v1/sources", nearbyStations: "GET /v1/stations", nearestReadings: "GET /v1/air-quality", pollutantParameters: "GET /v1/parameters", stationDetail: "GET /v1/stations/{id}" }],
48
+ aircraft: ["aircraft", "https://api-aircraft.dataandapis.com", { aircraftManufacturers: "GET /v1/aircraft/manufacturers", engineTypes: "GET /v1/aircraft/engine-types", getAircraft: "GET /v1/aircraft/{idOrSlug}", listAircraft: "GET /v1/aircraft", lookupByDesignator: "GET /v1/aircraft/designator/{code}", randomAircraft: "GET /v1/aircraft/random" }],
49
+ aircraftRegistrations: ["aircraft-registrations", "https://api-aircraft-registrations.dataandapis.com", { dataSources: "GET /v1/sources", getAircraftByTailNumber: "GET /v1/aircraft/{n_number}", lookupByModeSHex: "GET /v1/aircraft/hex/{code}", randomAircraft: "GET /v1/aircraft/random", registrationStatistics: "GET /v1/stats", searchAircraft: "GET /v1/aircraft", searchAircraftModels: "GET /v1/models" }],
50
+ airlines: ["airlines", "https://api-airlines.dataandapis.com", { dataSources: "GET /v1/sources", getAirline: "GET /v1/airlines/{qid}", lookupByIataCode: "GET /v1/airlines/iata/{code}", lookupByIcaoCode: "GET /v1/airlines/icao/{code}", searchAirlines: "GET /v1/airlines" }],
51
+ airportStatus: ["airport-status", "https://api-airport-status.dataandapis.com", { affectedAirports: "GET /v1/airport-status/delays", airportStatus: "GET /v1/airport-status/{code}", dataSources: "GET /v1/sources", nationalStatus: "GET /v1/airport-status" }],
52
+ airports: ["airports", "https://api-airports.dataandapis.com", { getAirport: "GET /v1/airports/{code}", nearbyAirports: "GET /v1/airports/nearby", searchAirports: "GET /v1/airports/search" }],
53
+ animals: ["animals", "https://api-animals.dataandapis.com", { animalClasses: "GET /v1/animals/classes", conservationStatuses: "GET /v1/animals/statuses", getAnimal: "GET /v1/animals/{slug}", listAnimals: "GET /v1/animals", randomAnimals: "GET /v1/animals/random" }],
54
+ anime: ["anime", "https://anime.dataandapis.com", { anime: "GET /v1/anime", getAnimeById: "GET /v1/anime/{id}" }],
55
+ artworks: ["artworks", "https://api-artworks.dataandapis.com", { artists: "GET /v1/artworks/artists", artworkDetail: "GET /v1/artworks/{id}", dataSources: "GET /v1/sources", departments: "GET /v1/artworks/departments", randomArtwork: "GET /v1/artworks/random", searchArtworks: "GET /v1/artworks" }],
56
+ astronomy: ["astronomy", "https://api-astronomy.dataandapis.com", { moonPhaseTimes: "GET /v1/moon", multiDayAlmanac: "GET /v1/almanac", sunTimesPosition: "GET /v1/sun" }],
57
+ attractions: ["attractions", "https://api-attractions.dataandapis.com", { attractionsNearAPoint: "GET /v1/attractions/nearby", dataSources: "GET /v1/sources", getAttraction: "GET /v1/attractions/{qid}", randomAttraction: "GET /v1/attractions/random", searchAttractions: "GET /v1/attractions" }],
58
+ babyNames: ["baby-names", "https://api-baby-names.dataandapis.com", { getName: "GET /v1/names/{name}", nameTrend: "GET /v1/names/trend/{name}", randomName: "GET /v1/names/random", topNames: "GET /v1/names/top" }],
59
+ banks: ["banks", "https://api-banks.dataandapis.com", { bankBranches: "GET /v1/banks/{cert}/branches", bankFailures: "GET /v1/failures", dataSources: "GET /v1/sources", failureStatistics: "GET /v1/failures/stats", getBank: "GET /v1/banks/{cert}", largestBanks: "GET /v1/banks/largest", searchBanks: "GET /v1/banks", searchBranches: "GET /v1/branches" }],
60
+ barcodeGenerator: ["barcode-generator", "https://api-barcode.dataandapis.com", { generateBarcode: "GET /v1/barcode", listSymbologies: "GET /v1/symbologies" }],
61
+ barcodeLookup: ["barcode-lookup", "https://api-barcode-lookup.dataandapis.com", { catalogueStats: "GET /v1/products/stats", dataSources: "GET /v1/sources", lookupByBarcode: "GET /v1/products/{barcode}", randomProducts: "GET /v1/products/random", searchProducts: "GET /v1/products", topBrands: "GET /v1/brands" }],
62
+ bibleMultiTranslation: ["bible-multi-translation", "https://api-bible.dataandapis.com", { getSingleVerse: "GET /v1/versions/{versionCode}/books/{bookCode}/chapters/{chapter}/verses/{verse}", getTranslationDetails: "GET /v1/versions/{code}", listBibleBooks: "GET /v1/books", listBibleTranslations: "GET /v1/versions" }],
63
+ binCardValidator: ["bin-card-validator", "https://api-bin-lookup.dataandapis.com", { lookupBin: "GET /v1/bin/{bin}", validateCard: "GET /v1/validate" }],
64
+ books: ["books", "https://api-books.dataandapis.com", { bookDetail: "GET /v1/books/{id}", dataSources: "GET /v1/sources", randomBook: "GET /v1/books/random", searchBooks: "GET /v1/books" }],
65
+ buoys: ["buoys", "https://api-buoys.dataandapis.com", { buoyDetail: "GET /v1/buoys/{id}", dataSources: "GET /v1/sources", latestObservations: "GET /v1/buoys/observations", nearestBuoys: "GET /v1/buoys/nearest", searchStations: "GET /v1/buoys/stations" }],
66
+ businessPatterns: ["business-patterns", "https://api-business-patterns.dataandapis.com", { countyProfile: "GET /v1/counties/{fips}", dataSources: "GET /v1/sources", nationalStatistics: "GET /v1/national", searchCounties: "GET /v1/counties", searchIndustries: "GET /v1/industries", stateProfile: "GET /v1/states/{state}", stateRankings: "GET /v1/states", zipBusinessProfile: "GET /v1/zips/{zip}" }],
67
+ caloriesBurned: ["calories-burned", "https://api-calories.dataandapis.com", { activityDetail: "GET /v1/activities/{id}", caloriesBurned: "GET /v1/calories-burned", dataSources: "GET /v1/sources", listActivities: "GET /v1/activities", listCategories: "GET /v1/categories" }],
68
+ cars: ["cars", "https://api-cars.dataandapis.com", { getVehicle: "GET /v1/vehicles/{id}", listVehicles: "GET /v1/vehicles", randomVehicles: "GET /v1/vehicles/random", vehicleMakes: "GET /v1/vehicles/makes", vehicleModels: "GET /v1/vehicles/models" }],
69
+ cats: ["cats", "https://api-cats.dataandapis.com", { breedOrigins: "GET /v1/breeds/origins", getBreed: "GET /v1/breeds/{slug}", listBreeds: "GET /v1/breeds", randomBreeds: "GET /v1/breeds/random" }],
70
+ climateNormals: ["climate-normals", "https://api-climate-normals.dataandapis.com", { climateAtCoordinates: "GET /v1/climate", climateRankings: "GET /v1/rankings", dataSources: "GET /v1/sources", getStationNormals: "GET /v1/stations/{id}", searchStations: "GET /v1/stations" }],
71
+ cocktails: ["cocktails", "https://api-cocktails.dataandapis.com", { getCocktail: "GET /v1/cocktails/{slug}", listCocktails: "GET /v1/cocktails", listIngredients: "GET /v1/cocktails/ingredients", randomCocktail: "GET /v1/cocktails/random" }],
72
+ colors: ["colors", "https://api-colors.dataandapis.com", { convertColor: "GET /v1/colors/convert", dataSources: "GET /v1/sources", generatePalette: "GET /v1/colors/palette", nameAColor: "GET /v1/colors/name", randomColor: "GET /v1/colors/random", searchColors: "GET /v1/colors", wcagContrast: "GET /v1/colors/contrast" }],
73
+ companies: ["companies", "https://api-companies.dataandapis.com", { companyIndustries: "GET /v1/companies/industries", dataSources: "GET /v1/sources", enrichByDomain: "GET /v1/companies/domain/{domain}", getCompany: "GET /v1/companies/{id}", randomCompanies: "GET /v1/companies/random", searchCompanies: "GET /v1/companies" }],
74
+ companyFinancials: ["company-financials", "https://api-company-financials.dataandapis.com", { companyProfile: "GET /v1/company/{ticker}", companySearch: "GET /v1/search", dataSources: "GET /v1/sources", keyFinancials: "GET /v1/financials/{ticker}", rawConcept: "GET /v1/concept/{ticker}/{concept}", reportedConcepts: "GET /v1/concepts/{ticker}" }],
75
+ continentsCountriesAndCities: ["continents-countries-and-cities", "https://continents-countries-and-cities.dataandapis.com", { cities: "GET /v1/cities", continents: "GET /v1/continents", countries: "GET /v1/countries", dataSources: "GET /v1/sources", getCityById: "GET /v1/cities/{id}", getContinentById: "GET /v1/continents/{id}", getCountryById: "GET /v1/countries/{id}", nearbyCities: "GET /v1/cities/nearby" }],
76
+ countryFlags: ["country-flags", "https://api-country-flags.dataandapis.com", { getFlagByCode: "GET /v1/flags/{code}", listFlags: "GET /v1/flags" }],
77
+ countryIndicators: ["country-indicators", "https://api-country-indicators.dataandapis.com", { countryProfile: "GET /v1/country/{code}", countryRankings: "GET /v1/rankings", dataSources: "GET /v1/sources", indicatorCatalog: "GET /v1/indicators", indicatorSeries: "GET /v1/data", listCountries: "GET /v1/countries" }],
78
+ cryptoPrices: ["crypto-prices", "https://api-crypto.dataandapis.com", { batchPrices: "GET /v1/prices", convert: "GET /v1/convert", dataSources: "GET /v1/sources", listCurrencies: "GET /v1/currencies", pairSpotPrice: "GET /v1/price/{pair}", priceHistory: "GET /v1/history/{pair}", tradingPairs: "GET /v1/pairs" }],
79
+ currencyRates: ["currency-rates", "https://api-currency.dataandapis.com", { convert: "GET /v1/convert", dataSources: "GET /v1/sources", listCurrencies: "GET /v1/currencies", rateHistory: "GET /v1/history", rateTable: "GET /v1/rates" }],
80
+ dayInHistory: ["day-in-history", "https://api-day-in-history.dataandapis.com", { dataSources: "GET /v1/sources", onThisDay: "GET /v1/onthisday" }],
81
+ demographics: ["demographics", "https://api-demographics.dataandapis.com", { countyDemographics: "GET /v1/demographics/county/{fips}", dataSources: "GET /v1/sources", getByGeoId: "GET /v1/demographics/{geo_id}", nationalDemographics: "GET /v1/demographics/us", rankings: "GET /v1/rankings", searchGeographies: "GET /v1/search", stateDemographics: "GET /v1/demographics/state/{code}", zipDemographics: "GET /v1/demographics/zip/{zip}" }],
82
+ dictionary: ["dictionary", "https://api-dictionary.dataandapis.com", { defineWord: "GET /v1/define/{word}" }],
83
+ disposableEmailChecker: ["disposable-email-checker", "https://api-disposable-email.dataandapis.com", { checkDisposable: "GET /v1/check" }],
84
+ dnsWhoisLookup: ["dns-whois-lookup", "https://api-dns-whois.dataandapis.com", { dnsLookup: "GET /v1/dns", whoisLookup: "GET /v1/whois" }],
85
+ dogs: ["dogs", "https://api-dogs.dataandapis.com", { breedGroups: "GET /v1/breeds/groups", getBreed: "GET /v1/breeds/{slug}", listBreeds: "GET /v1/breeds", randomBreeds: "GET /v1/breeds/random" }],
86
+ drugs: ["drugs", "https://api-drugs.dataandapis.com", { dataSources: "GET /v1/sources", deaSchedules: "GET /v1/drugs/schedules", dosageForms: "GET /v1/drugs/forms", getDrugByNdc: "GET /v1/drugs/{ndc}", randomDrugs: "GET /v1/drugs/random", searchDrugs: "GET /v1/drugs", searchRecalls: "GET /v1/recalls" }],
87
+ earthquakes: ["earthquakes", "https://api-earthquakes.dataandapis.com", { dataSources: "GET /v1/sources", earthquakesNearAPoint: "GET /v1/earthquakes/nearby", getEarthquake: "GET /v1/earthquakes/{id}", largestEarthquakes: "GET /v1/earthquakes/largest", searchEarthquakes: "GET /v1/earthquakes" }],
88
+ elements: ["elements", "https://api-elements.dataandapis.com", { dataSources: "GET /v1/sources", elementLookup: "GET /v1/elements/{key}", listElements: "GET /v1/elements", randomElement: "GET /v1/elements/random" }],
89
+ emailValidation: ["email-validation", "https://api-email-validation.dataandapis.com", { validateEmail: "GET /v1/validate" }],
90
+ emissionFactors: ["emission-factors", "https://api-emission-factors.dataandapis.com", { calculateEmissions: "GET /v1/calculate", calculateEmissionsBatch: "POST /v1/calculate", factorCategories: "GET /v1/factors/categories", factorSets: "GET /v1/factors/sets", factorUnits: "GET /v1/factors/units", getFactor: "GET /v1/factors/{slug}", globalWarmingPotentials: "GET /v1/factors/gwp", listFactors: "GET /v1/factors", randomFactor: "GET /v1/factors/random", sourceFreshness: "GET /v1/factors/updates" }],
91
+ emoji: ["emoji", "https://api-emoji.dataandapis.com", { dataSources: "GET /v1/sources", emojiGroups: "GET /v1/emoji/groups", emojiLookup: "GET /v1/emoji/{key}", randomEmoji: "GET /v1/emoji/random", searchEmoji: "GET /v1/emoji" }],
92
+ evChargers: ["ev-chargers", "https://api-ev-chargers.dataandapis.com", { chargingNetworks: "GET /v1/stations/networks", getStation: "GET /v1/stations/{id}", listStations: "GET /v1/stations", nearbyStations: "GET /v1/stations/nearby", randomStations: "GET /v1/stations/random", stationsByState: "GET /v1/stations/states" }],
93
+ federalContracts: ["federal-contracts", "https://api-federal-contracts.dataandapis.com", { agencies: "GET /v1/opportunities/agencies", closingSoon: "GET /v1/opportunities/closing", dataSources: "GET /v1/sources", expiringAwards: "GET /v1/awards/expiring", getOpportunityByNoticeId: "GET /v1/opportunities/{notice_id}", searchAwards: "GET /v1/awards", searchOpportunities: "GET /v1/opportunities", topRecipients: "GET /v1/awards/recipients" }],
94
+ federalRegister: ["federal-register", "https://api-federal-register.dataandapis.com", { agencies: "GET /v1/federal-register/agencies", dataSources: "GET /v1/sources", documentDetail: "GET /v1/federal-register/documents/{number}", executiveOrders: "GET /v1/federal-register/executive-orders", searchDocuments: "GET /v1/federal-register/documents" }],
95
+ foodNutritionInformation: ["food-nutrition-information", "https://food-nutrition-information.dataandapis.com", { getFood: "GET /v1/food/{id}", searchFoods: "GET /v1/foods/search" }],
96
+ foodRecalls: ["food-recalls", "https://api-food-recalls.dataandapis.com", { dataSources: "GET /v1/sources", recallLookup: "GET /v1/food-recalls/{number}", recallStats: "GET /v1/food-recalls/stats", searchRecalls: "GET /v1/food-recalls" }],
97
+ fuelStations: ["fuel-stations", "https://api-fuel-stations.dataandapis.com", { dataSources: "GET /v1/sources", fuelsRollup: "GET /v1/stations/fuels", getStationById: "GET /v1/stations/{id}", nearbyStations: "GET /v1/stations/nearby", randomStations: "GET /v1/stations/random", searchStations: "GET /v1/stations", statesRollup: "GET /v1/stations/states" }],
98
+ geocoding: ["geocoding", "https://api-geocoding.dataandapis.com", { dataSources: "GET /v1/sources", forwardGeocode: "GET /v1/geocode", placeDetail: "GET /v1/place/{id}", reverseGeocode: "GET /v1/reverse" }],
99
+ grants: ["grants", "https://api-grants.dataandapis.com", { dataSources: "GET /v1/sources", grantAgencies: "GET /v1/grants/agencies", grantLookup: "GET /v1/grants/{id}", searchGrants: "GET /v1/grants" }],
100
+ healthcareProviders: ["healthcare-providers", "https://api-healthcare-providers.dataandapis.com", { dataSources: "GET /v1/sources", getProviderByNpi: "GET /v1/providers/{npi}", getTaxonomyCode: "GET /v1/taxonomies/{code}", randomProviders: "GET /v1/providers/random", searchProviders: "GET /v1/providers", searchTaxonomies: "GET /v1/taxonomies" }],
101
+ hearthstone: ["hearthstone", "https://hearthstone.dataandapis.com", { getCardById: "GET /v1/cards/{slug}", getCards: "GET /v1/cards" }],
102
+ horoscopeZodiac: ["horoscope-zodiac", "https://api-horoscope.dataandapis.com", { dailyHoroscope: "GET /v1/horoscope/{sign}", listSigns: "GET /v1/signs", signByDate: "GET /v1/sign" }],
103
+ hospitals: ["hospitals", "https://api-hospitals.dataandapis.com", { getHospital: "GET /v1/hospitals/{ccn}", hospitalsByState: "GET /v1/hospitals/states", hospitalTypes: "GET /v1/hospitals/types", listHospitals: "GET /v1/hospitals", nearbyHospitals: "GET /v1/hospitals/nearby", randomHospitals: "GET /v1/hospitals/random" }],
104
+ htmlRender: ["html-render", "https://html-render.dataandapis.com", { convertHtml: "POST /v1/convert" }],
105
+ hurricanes: ["hurricanes", "https://api-hurricanes.dataandapis.com", { dataSources: "GET /v1/sources", getStormTrack: "GET /v1/storms/{id}", searchStorms: "GET /v1/storms", seasonStatistics: "GET /v1/storms/stats", stormsNearAPoint: "GET /v1/storms/nearby" }],
106
+ ibanSwiftValidator: ["iban-swift-validator", "https://api-iban-swift.dataandapis.com", { validateIban: "GET /v1/iban", validateSwiftBic: "GET /v1/swift" }],
107
+ imageToText: ["image-to-text", "https://api-image-to-text.dataandapis.com", { describeImage: "GET /v1/describe", describeImagePost: "POST /v1/describe" }],
108
+ inflation: ["inflation", "https://api-inflation.dataandapis.com", { annualInflationHistory: "GET /v1/inflation/history", cpiSeriesCatalog: "GET /v1/cpi/series", cpiValues: "GET /v1/cpi", dataSources: "GET /v1/sources", inflationCalculator: "GET /v1/inflation/calculator", inflationRate: "GET /v1/inflation/rate" }],
109
+ ipIntelligence: ["ip-intelligence", "https://api-ip-intelligence.dataandapis.com", { dataSources: "GET /v1/sources", getAutonomousSystem: "GET /v1/asns/{asn}", hostingProviders: "GET /v1/providers", lookupCallerIp: "GET /v1/ip/me", lookupIp: "GET /v1/ip/{address}", lookupIpBatch: "POST /v1/ip", searchAutonomousSystems: "GET /v1/asns" }],
110
+ jokes: ["jokes", "https://api-jokes.dataandapis.com", { getJoke: "GET /v1/jokes/{id}", listCategories: "GET /v1/jokes/categories", listJokes: "GET /v1/jokes", randomJoke: "GET /v1/jokes/random" }],
111
+ languageDetection: ["language-detection", "https://api-language-detection.dataandapis.com", { detectLanguage: "GET /v1/detect", detectLanguagePost: "POST /v1/detect" }],
112
+ logos: ["logos", "https://api-logos.dataandapis.com", { getLogoImage: "GET /v1/logos/{domain}/image", getLogosByQuery: "GET /v1/logos", getLogosForDomain: "GET /v1/logos/{domain}" }],
113
+ loremIpsum: ["lorem-ipsum", "https://lorem-ipsum.dataandapis.com", { paragraph: "GET /v1/paragraph", sentence: "GET /v1/sentence", word: "GET /v1/word" }],
114
+ lottery: ["lottery", "https://api-lottery.dataandapis.com", { getDraw: "GET /v1/draws/{id}", getProvider: "GET /v1/providers/{slug}", latestDraws: "GET /v1/draws/latest", listDrawsByProvider: "GET /v1/providers/{slug}/draws", listProviders: "GET /v1/providers" }],
115
+ mangaManhuaManhwa: ["manga-manhua-manhwa", "https://manga-manhua-manhwa.dataandapis.com", { getMangaById: "GET /v1/manga/{id}", manga: "GET /v1/manga" }],
116
+ mobileDevices: ["mobile-devices", "https://cellphone-and-tablet.dataandapis.com", { getBrands: "GET /v1/brands", getDevices: "GET /v1/devices" }],
117
+ mortgageLoanCalculator: ["mortgage-loan-calculator", "https://api-mortgage-calculator.dataandapis.com", { mortgageCalculator: "GET /v1/mortgage" }],
118
+ motorcycles: ["motorcycles", "https://api-motorcycles.dataandapis.com", { getMotorcycle: "GET /v1/motorcycles/{idOrSlug}", listMotorcycles: "GET /v1/motorcycles", motorcycleBrands: "GET /v1/motorcycles/brands", motorcycleCategories: "GET /v1/motorcycles/categories", motorcycleImage: "GET /v1/motorcycles/{idOrSlug}/image", randomMotorcycles: "GET /v1/motorcycles/random" }],
119
+ movies: ["movies", "https://api-movies.dataandapis.com", { dataSources: "GET /v1/sources", getTitle: "GET /v1/titles/{qid}", lookupByImdbId: "GET /v1/titles/imdb/{id}", randomTitle: "GET /v1/titles/random", searchTitles: "GET /v1/titles" }],
120
+ nameIntelligence: ["name-intelligence", "https://api-name-intelligence.dataandapis.com", { batchInferGender: "POST /v1/gender", dataSources: "GET /v1/sources", getNameStatistics: "GET /v1/names/{name}", getSurname: "GET /v1/surnames/{name}", inferGender: "GET /v1/gender/{name}", searchFirstNames: "GET /v1/names", searchSurnames: "GET /v1/surnames" }],
121
+ nonprofits: ["nonprofits", "https://api-nonprofits.dataandapis.com", { dataSources: "GET /v1/sources", nonprofitCategories: "GET /v1/nonprofits/categories", nonprofitsByState: "GET /v1/nonprofits/states", randomNonprofits: "GET /v1/nonprofits/random", searchNonprofits: "GET /v1/nonprofits", verifyNonprofit: "GET /v1/nonprofits/{ein}" }],
122
+ notablePeople: ["notable-people", "https://api-notable-people.dataandapis.com", { bornOnDate: "GET /v1/people/born-on", dataSources: "GET /v1/sources", diedOnDate: "GET /v1/people/died-on", getPersonByQid: "GET /v1/people/{qid}", randomPeople: "GET /v1/people/random", searchPeople: "GET /v1/people" }],
123
+ novel: ["novel", "https://novel.dataandapis.com", { getNovelById: "GET /v1/novels/{id}", novel: "GET /v1/novels" }],
124
+ objectDetection: ["object-detection", "https://api-object-detection.dataandapis.com", { detectObjects: "GET /v1/detect", detectObjectsPost: "POST /v1/detect" }],
125
+ occupations: ["occupations", "https://api-occupations.dataandapis.com", { alternateTitles: "GET /v1/occupations/{code}/titles", dataSources: "GET /v1/sources", jobZones: "GET /v1/occupations/job-zones", occupationProfile: "GET /v1/occupations/{code}", searchOccupations: "GET /v1/occupations", technologyLookup: "GET /v1/occupations/technology" }],
126
+ passwordGenerator: ["password-generator", "https://password-generator.dataandapis.com", { generatePassword: "GET /v1/generate-password" }],
127
+ phoneValidation: ["phone-validation", "https://api-phone-validation.dataandapis.com", { validatePhone: "GET /v1/phone" }],
128
+ pokemonUnite: ["pokemon-unite", "https://pokemon-unite.dataandapis.com", { getPokemonDataByName: "GET /v1/pokemon/{name}", listAllPokemons: "GET /v1/pokemon" }],
129
+ population: ["population", "https://api-population.dataandapis.com", { dataSources: "GET /v1/sources", rankings: "GET /v1/population/rankings", searchLocations: "GET /v1/population/locations", timeSeries: "GET /v1/population", yearSnapshot: "GET /v1/population/{country}/{year}" }],
130
+ powerPlants: ["power-plants", "https://api-power-plants.dataandapis.com", { capacityStats: "GET /v1/power-plants/stats", dataSources: "GET /v1/sources", nearestPlants: "GET /v1/power-plants/nearest", plantDetail: "GET /v1/power-plants/{id}", searchPlants: "GET /v1/power-plants" }],
131
+ productRecalls: ["product-recalls", "https://api-product-recalls.dataandapis.com", { checkBarcode: "GET /v1/recalls/upc/{upc}", dataSources: "GET /v1/sources", getRecall: "GET /v1/recalls/{id}", latestRecalls: "GET /v1/recalls/latest", recallStatistics: "GET /v1/recalls/stats", searchRecalls: "GET /v1/recalls" }],
132
+ profanityFilter: ["profanity-filter", "https://api-profanity-filter.dataandapis.com", { checkText: "GET /v1/check", checkTextPost: "POST /v1/check" }],
133
+ publicHolidays: ["public-holidays", "https://public-holidays.dataandapis.com", { countryHolidaysByYear: "GET /v1/holidays/{country}/{year}", dataSources: "GET /v1/sources", isItAHoliday: "GET /v1/holidays/today", longWeekends: "GET /v1/holidays/long-weekends/{country}/{year}", nextHolidays: "GET /v1/holidays/next", supportedCountries: "GET /v1/countries" }],
134
+ qrCodeGenerator: ["qr-code-generator", "https://api-qrcode.dataandapis.com", { generateQrCode: "GET /v1/qrcode", generateQrCodeBase64: "GET /v1/qrcode/base64" }],
135
+ quotes: ["quotes", "https://quotes.dataandapis.com", { getQuoteById: "GET /v1/quotes/{id}", getRandomQuote: "GET /v1/random" }],
136
+ randomImage: ["random-image", "https://api-random-image.dataandapis.com", { placeholderImage: "GET /v1/image", randomImage: "GET /v1/image/random" }],
137
+ randomUser: ["random-user", "https://api-random-user.dataandapis.com", { generateRandomUsers: "GET /v1/user", listNationalities: "GET /v1/user/nationalities" }],
138
+ recipes: ["recipes", "https://api-recipes.dataandapis.com", { getRecipe: "GET /v1/recipes/{slug}", listCuisines: "GET /v1/recipes/cuisines", listRecipes: "GET /v1/recipes", randomRecipe: "GET /v1/recipes/random" }],
139
+ riddles: ["riddles", "https://api-riddles.dataandapis.com", { getRiddle: "GET /v1/riddles/{id}", listCategories: "GET /v1/riddles/categories", listRiddles: "GET /v1/riddles", randomRiddle: "GET /v1/riddles/random" }],
140
+ rivers: ["rivers", "https://api-rivers.dataandapis.com", { dataSources: "GET /v1/sources", gaugeDetail: "GET /v1/rivers/sites/{id}", liveConditions: "GET /v1/rivers/conditions", nearestGauges: "GET /v1/rivers/nearest", searchGauges: "GET /v1/rivers/sites" }],
141
+ salaryBenchmarks: ["salary-benchmarks", "https://api-salary-benchmarks.dataandapis.com", { dataSources: "GET /v1/sources", nationalBenchmark: "GET /v1/wages/national/{soc}", searchAreas: "GET /v1/areas", searchOccupations: "GET /v1/occupations", searchWages: "GET /v1/wages" }],
142
+ salesTaxVat: ["sales-tax-vat", "https://api-sales-tax.dataandapis.com", { calculateTax: "GET /v1/calculate", dataSources: "GET /v1/sources", listVatRates: "GET /v1/vat", usSalesTax: "GET /v1/sales-tax/us/{state}", usSalesTaxAllStates: "GET /v1/sales-tax/us", vatByCountry: "GET /v1/vat/{country}" }],
143
+ sanctions: ["sanctions", "https://api-sanctions.dataandapis.com", { browseEntities: "GET /v1/entities", entityPrograms: "GET /v1/entities/programs", getEntity: "GET /v1/entities/{id}", screenName: "GET /v1/screen", screenNamesBatch: "POST /v1/screen", sourceLists: "GET /v1/lists" }],
144
+ seaports: ["seaports", "https://api-seaports.dataandapis.com", { dataSources: "GET /v1/sources", nearestPorts: "GET /v1/seaports/nearest", portDetail: "GET /v1/seaports/{key}", portsByCountry: "GET /v1/seaports/stats", searchPorts: "GET /v1/seaports" }],
145
+ sentimentAnalysis: ["sentiment-analysis", "https://api-sentiment.dataandapis.com", { analyzeSentiment: "GET /v1/sentiment", analyzeSentimentPost: "POST /v1/sentiment" }],
146
+ spaceLaunches: ["space-launches", "https://api-space-launches.dataandapis.com", { dataSources: "GET /v1/sources", launchDetail: "GET /v1/launches/{tag}", launchStats: "GET /v1/launches/stats", nextLaunch: "GET /v1/launches/next", searchLaunches: "GET /v1/launches", upcomingLaunches: "GET /v1/launches/upcoming" }],
147
+ spellCheck: ["spell-check", "https://api-spell-check.dataandapis.com", { checkTextPost: "POST /v1/check", checkWord: "GET /v1/check" }],
148
+ sslChecker: ["ssl-checker-api", "https://ssl-checker-api.dataandapis.com", { checksSslCertificate: "GET /v1/check" }],
149
+ stockTickers: ["stock-tickers", "https://api-stock-tickers.dataandapis.com", { dataSources: "GET /v1/sources", getTicker: "GET /v1/tickers/{symbol}", listingStatistics: "GET /v1/tickers/stats", searchTickers: "GET /v1/tickers" }],
150
+ tariffCodes: ["tariff-codes", "https://api-tariff-codes.dataandapis.com", { dataSources: "GET /v1/sources", htsChapters: "GET /v1/tariffs/chapters", searchTariffs: "GET /v1/tariffs", tariffLookup: "GET /v1/tariffs/{code}" }],
151
+ techStack: ["tech-stack", "https://api-tech-stack.dataandapis.com", { detectStack: "GET /v1/stack/{target}", detectStackBatch: "POST /v1/stack", technologyCatalogue: "GET /v1/technologies" }],
152
+ textEmbeddings: ["text-embeddings", "https://api-embeddings.dataandapis.com", { embedText: "GET /v1/embeddings", embedTextPost: "POST /v1/embeddings" }],
153
+ thesaurus: ["thesaurus", "https://api-thesaurus.dataandapis.com", { fullThesaurus: "GET /v1/thesaurus/{word}", getAntonyms: "GET /v1/antonyms/{word}", getSynonyms: "GET /v1/synonyms/{word}" }],
154
+ tides: ["tides", "https://api-tides.dataandapis.com", { dataSources: "GET /v1/sources", nearestStations: "GET /v1/tides/nearest", searchStations: "GET /v1/tides/stations", stationDetail: "GET /v1/tides/stations/{id}", tidePredictions: "GET /v1/tides/predictions", waterTemperature: "GET /v1/tides/water" }],
155
+ timezoneWorldTime: ["timezone-world-time", "https://api-timezone.dataandapis.com", { getCurrentTime: "GET /v1/time", getTimeByTimezone: "GET /v1/time/{timezone}", listTimezones: "GET /v1/timezones" }],
156
+ tradingCalendar: ["trading-calendar", "https://api-trading-calendar.dataandapis.com", { marketHolidays: "GET /v1/holidays", marketStatus: "GET /v1/status", nextTradingDay: "GET /v1/next", tradingDaysInRange: "GET /v1/trading-days" }],
157
+ trafficFatalities: ["traffic-fatalities", "https://api-traffic-fatalities.dataandapis.com", { crashesNearAPoint: "GET /v1/crashes/nearby", crashStatistics: "GET /v1/crashes/stats", dataSources: "GET /v1/sources", getCrash: "GET /v1/crashes/{year}/{st_case}", searchCrashes: "GET /v1/crashes" }],
158
+ translation: ["translation", "https://api-translation.dataandapis.com", { translate: "GET /v1/translate", translatePost: "POST /v1/translate" }],
159
+ travelAdvisories: ["travel-advisories", "https://api-travel-advisories.dataandapis.com", { dataSources: "GET /v1/sources", getAdvisoryForDestination: "GET /v1/advisories/{country}", listAdvisories: "GET /v1/advisories" }],
160
+ trending: ["trending", "https://api-trending.dataandapis.com", { articleInterest: "GET /v1/trending/article", dataSources: "GET /v1/sources", trendingArticles: "GET /v1/trending" }],
161
+ trivia: ["trivia", "https://api-trivia.dataandapis.com", { getTriviaById: "GET /v1/trivia/{id}", listCategories: "GET /v1/trivia/categories", listTrivia: "GET /v1/trivia", randomTrivia: "GET /v1/trivia/random" }],
162
+ unitConverter: ["unit-converter", "https://unit-converter.dataandapis.com", { getUnitInfo: "GET /v1/info", transformUnits: "GET /v1/converter" }],
163
+ universities: ["universities", "https://api-universities.dataandapis.com", { dataSources: "GET /v1/sources", getInstitution: "GET /v1/universities/{unitid}", searchUsInstitutions: "GET /v1/universities", statesRollup: "GET /v1/universities/states", worldUniversities: "GET /v1/world" }],
164
+ urlMetadata: ["url-metadata", "https://api-url-metadata.dataandapis.com", { getMetadata: "GET /v1/metadata" }],
165
+ usLawyers: ["us-lawyers", "https://api-us-lawyers.dataandapis.com", { getState: "GET /v1/states/{code}", listStates: "GET /v1/states", searchAttorneys: "GET /v1/states/{code}/search" }],
166
+ userAgentParser: ["user-agent-parser", "https://api-user-agent.dataandapis.com", { parseUserAgent: "GET /v1/parse" }],
167
+ vat: ["vat", "https://api-vat.dataandapis.com", { checkFormat: "GET /v1/vat/format", dataSources: "GET /v1/sources", supportedCountries: "GET /v1/vat/countries", validateVatNumber: "GET /v1/vat/validate" }],
168
+ vehicleRecalls: ["vehicle-recalls", "https://api-vehicle-recalls.dataandapis.com", { dataSources: "GET /v1/sources", getComplaint: "GET /v1/complaints/{odino}", getRecallCampaign: "GET /v1/recalls/{nhtsa_id}", latestRecalls: "GET /v1/recalls/latest", recallComponents: "GET /v1/recalls/components", searchComplaints: "GET /v1/complaints", searchRecalls: "GET /v1/recalls", vehicleSafetyProfile: "GET /v1/complaints/stats" }],
169
+ videoGames: ["video-games", "https://api-video-games.dataandapis.com", { dataSources: "GET /v1/sources", getGame: "GET /v1/games/{qid}", lookupBySteamAppId: "GET /v1/games/steam/{appid}", randomGame: "GET /v1/games/random", searchGames: "GET /v1/games" }],
170
+ vinDecoder: ["vin-decoder", "https://vin-decoder.dataandapis.com", { decodeVin: "GET /v1/decode" }],
171
+ watches: ["watches", "https://api-watches.dataandapis.com", { dataSources: "GET /v1/sources", getBrand: "GET /v1/brands/{name}", getCaliberBySlug: "GET /v1/calibers/{slug}", movementTypes: "GET /v1/calibers/types", randomCalibers: "GET /v1/calibers/random", searchBrands: "GET /v1/brands", searchCalibers: "GET /v1/calibers" }],
172
+ weather: ["weather", "https://api-weather.dataandapis.com", { dataSources: "GET /v1/sources", getForecast: "GET /v1/weather" }],
173
+ wildfires: ["wildfires", "https://api-wildfires.dataandapis.com", { currentWildfires: "GET /v1/wildfires", dataSources: "GET /v1/sources", nationalStats: "GET /v1/wildfires/stats", wildfiresNearMe: "GET /v1/wildfires/nearest" }],
174
+ zipPostalCode: ["zip-postal-code", "https://api-postal-code.dataandapis.com", { postalCodeLookup: "GET /v1/postal-code", searchByPlace: "GET /v1/search" }]
175
+ };
176
+
177
+ // src/version.ts
178
+ var VERSION = "0.1.0";
179
+
180
+ // src/client.ts
181
+ var DEFAULT_TIMEOUT = 3e4;
182
+ var DEFAULT_MAX_RETRIES = 2;
183
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 502, 503, 504]);
184
+ var MAX_RETRY_WAIT = 1e4;
185
+ var HOST = "dataandapis.com";
186
+ var BASE_URLS = {};
187
+ for (const name of Object.keys(APIS)) {
188
+ const [slug, baseUrl] = APIS[name];
189
+ BASE_URLS[slug] = baseUrl;
190
+ BASE_URLS[name] = baseUrl;
191
+ }
192
+ function envApiKey() {
193
+ try {
194
+ const env = globalThis.process?.env;
195
+ return env?.DATAANDAPIS_API_KEY || void 0;
196
+ } catch {
197
+ return void 0;
198
+ }
199
+ }
200
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
201
+ function isAbort(err) {
202
+ return typeof err === "object" && err !== null && err.name === "AbortError";
203
+ }
204
+ async function parseBody(res) {
205
+ if (res.status === 204 || res.status === 205) return void 0;
206
+ const type = (res.headers.get("content-type") || "").toLowerCase();
207
+ if (type.includes("json")) {
208
+ const text = await res.text();
209
+ if (!text) return void 0;
210
+ try {
211
+ return JSON.parse(text);
212
+ } catch {
213
+ return text;
214
+ }
215
+ }
216
+ if (type.startsWith("text/") || type.startsWith("application/xml")) return res.text();
217
+ return res.blob();
218
+ }
219
+ function errorMessage(status, body, fallback) {
220
+ if (body && typeof body === "object") {
221
+ const b = body;
222
+ if (typeof b.message === "string" && b.message) return b.message;
223
+ if (typeof b.error === "string" && b.error) return b.error;
224
+ }
225
+ if (typeof body === "string" && body && body.length < 300) return body;
226
+ return fallback || `Request failed with status ${status}`;
227
+ }
228
+ var _apiKey, _timeout, _maxRetries, _headers, _fetch, _onResponse, _DataAndApis_instances, buildApi_fn, send_fn;
229
+ var DataAndApis = class {
230
+ constructor(options = {}) {
231
+ __privateAdd(this, _DataAndApis_instances);
232
+ __privateAdd(this, _apiKey);
233
+ __privateAdd(this, _timeout);
234
+ __privateAdd(this, _maxRetries);
235
+ __privateAdd(this, _headers);
236
+ __privateAdd(this, _fetch);
237
+ __privateAdd(this, _onResponse);
238
+ const apiKey = options.apiKey ?? envApiKey();
239
+ if (!apiKey) {
240
+ throw new DataAndApisError(
241
+ "Missing API key. Pass { apiKey } or set the DATAANDAPIS_API_KEY environment variable. Create a free key at https://dataandapis.com/sign-up"
242
+ );
243
+ }
244
+ __privateSet(this, _apiKey, apiKey);
245
+ __privateSet(this, _timeout, options.timeout ?? DEFAULT_TIMEOUT);
246
+ __privateSet(this, _maxRetries, options.maxRetries ?? DEFAULT_MAX_RETRIES);
247
+ __privateSet(this, _headers, { ...options.headers });
248
+ __privateSet(this, _fetch, options.fetch);
249
+ __privateSet(this, _onResponse, options.onResponse);
250
+ for (const name of Object.keys(APIS)) {
251
+ let cached;
252
+ Object.defineProperty(this, name, {
253
+ enumerable: true,
254
+ get: () => cached ?? (cached = __privateMethod(this, _DataAndApis_instances, buildApi_fn).call(this, name))
255
+ });
256
+ }
257
+ }
258
+ /**
259
+ * Call any endpoint by path. Use it for endpoints newer than this version of the SDK.
260
+ *
261
+ * ```ts
262
+ * const data = await client.request("vat", "/v1/vat/validate", { query: { vat: "IE6388047V" } });
263
+ * ```
264
+ *
265
+ * @param api The API's catalog slug (`"ip-intelligence"`), its name on the client (`"ipIntelligence"`) or its base URL.
266
+ * @param path Path on that API, starting with `/v1/`.
267
+ */
268
+ request(api, path, options = {}) {
269
+ let base = BASE_URLS[api];
270
+ let slug = api;
271
+ if (!base) {
272
+ if (!/^https:\/\//i.test(api)) {
273
+ throw new DataAndApisError(`Unknown API "${api}". Use a slug from https://dataandapis.com/apis or the API's https:// base URL.`);
274
+ }
275
+ base = api.replace(/\/+$/, "");
276
+ slug = new URL(base).hostname.split(".")[0].replace(/^api-/, "");
277
+ } else if (APIS[api]) {
278
+ slug = APIS[api][0];
279
+ }
280
+ return __privateMethod(this, _DataAndApis_instances, send_fn).call(this, slug, (options.method || "GET").toUpperCase(), base + (path.startsWith("/") ? path : `/${path}`), options.query, options.body, options);
281
+ }
282
+ };
283
+ _apiKey = new WeakMap();
284
+ _timeout = new WeakMap();
285
+ _maxRetries = new WeakMap();
286
+ _headers = new WeakMap();
287
+ _fetch = new WeakMap();
288
+ _onResponse = new WeakMap();
289
+ _DataAndApis_instances = new WeakSet();
290
+ buildApi_fn = function(name) {
291
+ const [slug, baseUrl, operations] = APIS[name];
292
+ const api = {};
293
+ for (const op of Object.keys(operations)) {
294
+ const space = operations[op].indexOf(" ");
295
+ const method = operations[op].slice(0, space);
296
+ const template = operations[op].slice(space + 1);
297
+ api[op] = async (params, options) => {
298
+ const rest = { ...params };
299
+ const body = rest.body;
300
+ if (method !== "GET") delete rest.body;
301
+ const path = template.replace(/\{(\w+)\}/g, (_, key) => {
302
+ const value = rest[key];
303
+ if (value === void 0 || value === null || value === "") {
304
+ throw new DataAndApisError(`Missing "${key}" for ${name}.${op}(): it is part of the path ${template}`);
305
+ }
306
+ delete rest[key];
307
+ return encodeURIComponent(String(value)).replace(/%2F/gi, "/");
308
+ });
309
+ const query = { ...rest, ...options?.query };
310
+ return __privateMethod(this, _DataAndApis_instances, send_fn).call(this, slug, method, baseUrl + path, query, method === "GET" ? void 0 : body, options);
311
+ };
312
+ }
313
+ return api;
314
+ };
315
+ send_fn = async function(slug, method, target, query, body, options) {
316
+ const url = new URL(target);
317
+ if (url.protocol !== "https:" || url.hostname !== HOST && !url.hostname.endsWith(`.${HOST}`)) {
318
+ throw new DataAndApisError(`Refusing to send the API key to ${url.origin}: only https://*.${HOST} is allowed.`);
319
+ }
320
+ if (query) {
321
+ for (const key of Object.keys(query)) {
322
+ const value = query[key];
323
+ if (value !== void 0 && value !== null) url.searchParams.set(key, String(value));
324
+ }
325
+ }
326
+ const doFetch = __privateGet(this, _fetch) ?? globalThis.fetch;
327
+ if (typeof doFetch !== "function") {
328
+ throw new DataAndApisError("No fetch available. Use Node.js 18 or later, or pass a fetch implementation as { fetch }.");
329
+ }
330
+ const headers = {
331
+ Accept: "application/json",
332
+ "User-Agent": `dataandapis-js/${VERSION}`,
333
+ ...__privateGet(this, _headers),
334
+ ...options?.headers,
335
+ "X-Api-Key": __privateGet(this, _apiKey)
336
+ };
337
+ let payload;
338
+ if (body !== void 0 && body !== null) {
339
+ payload = typeof body === "string" ? body : JSON.stringify(body);
340
+ if (!Object.keys(headers).some((h) => h.toLowerCase() === "content-type")) headers["Content-Type"] = "application/json";
341
+ }
342
+ const timeout = options?.timeout ?? __privateGet(this, _timeout);
343
+ const maxRetries = method === "GET" ? Math.max(0, options?.maxRetries ?? __privateGet(this, _maxRetries)) : 0;
344
+ const href = url.toString();
345
+ for (let attempt = 1; ; attempt++) {
346
+ const canRetry = attempt <= maxRetries;
347
+ const controller = new AbortController();
348
+ let timedOut = false;
349
+ const timer = timeout > 0 ? setTimeout(() => {
350
+ timedOut = true;
351
+ controller.abort();
352
+ }, timeout) : void 0;
353
+ const outer = options?.signal;
354
+ const onAbort = () => controller.abort(outer.reason);
355
+ if (outer) {
356
+ if (outer.aborted) onAbort();
357
+ else outer.addEventListener("abort", onAbort, { once: true });
358
+ }
359
+ const started = Date.now();
360
+ let res;
361
+ let data;
362
+ try {
363
+ res = await doFetch(href, { method, headers, body: payload, signal: controller.signal });
364
+ const remaining = res.headers.get("ratelimit-requests-remaining");
365
+ const tokensRemaining = remaining !== null && remaining !== "" && !Number.isNaN(Number(remaining)) ? Number(remaining) : void 0;
366
+ if (__privateGet(this, _onResponse)) {
367
+ try {
368
+ __privateGet(this, _onResponse).call(this, { api: slug, method, url: href, status: res.status, ok: res.ok, durationMs: Date.now() - started, tokensRemaining, attempt });
369
+ } catch {
370
+ }
371
+ }
372
+ if (!res.ok && canRetry && RETRY_STATUSES.has(res.status)) {
373
+ try {
374
+ await res.arrayBuffer();
375
+ } catch {
376
+ }
377
+ const retryAfter = Number(res.headers.get("retry-after"));
378
+ await sleep(retryAfter > 0 ? Math.min(retryAfter * 1e3, MAX_RETRY_WAIT) : backoff(attempt));
379
+ continue;
380
+ }
381
+ data = await parseBody(res);
382
+ if (!res.ok) {
383
+ const details = { status: res.status, api: slug, method, url: href, body: data, tokensRemaining };
384
+ const message = errorMessage(res.status, data, res.statusText);
385
+ if (res.status === 401) throw new AuthenticationError(message, details);
386
+ if (res.status === 402) throw new PaymentRequiredError(message, details);
387
+ if (res.status === 429) throw new QuotaExceededError(message, details);
388
+ throw new ApiError(message, details);
389
+ }
390
+ return data;
391
+ } catch (err) {
392
+ if (err instanceof DataAndApisError) throw err;
393
+ if (outer?.aborted && !timedOut) throw err;
394
+ if (canRetry) {
395
+ await sleep(backoff(attempt));
396
+ continue;
397
+ }
398
+ if (timedOut) throw new TimeoutError(`${method} ${href} timed out after ${timeout} ms`, { cause: err });
399
+ if (isAbort(err)) throw err;
400
+ throw new ConnectionError(`${method} ${href} failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
401
+ } finally {
402
+ if (timer !== void 0) clearTimeout(timer);
403
+ if (outer) outer.removeEventListener("abort", onAbort);
404
+ }
405
+ }
406
+ };
407
+ function backoff(attempt) {
408
+ return Math.min(500 * 2 ** (attempt - 1), MAX_RETRY_WAIT) * (0.75 + Math.random() * 0.5);
409
+ }
410
+
411
+ export { ApiError, AuthenticationError, ConnectionError, DataAndApis, DataAndApisError, PaymentRequiredError, QuotaExceededError, TimeoutError, VERSION };
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "dataandapis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Official JavaScript and TypeScript client for Data and APIs: 128 REST data APIs (VAT validation, barcode lookup, IP intelligence, sanctions screening, company data and more) behind one API key.",
5
+ "keywords": [
6
+ "dataandapis",
7
+ "data-and-apis",
8
+ "api",
9
+ "api-client",
10
+ "sdk",
11
+ "rest",
12
+ "typescript",
13
+ "data",
14
+ "vat-validation",
15
+ "vies",
16
+ "barcode-lookup",
17
+ "ip-geolocation",
18
+ "ip-intelligence",
19
+ "sanctions-screening",
20
+ "company-enrichment",
21
+ "geocoding",
22
+ "public-holidays",
23
+ "currency-rates"
24
+ ],
25
+ "homepage": "https://dataandapis.com/?ref=npm",
26
+ "bugs": {
27
+ "url": "https://dataandapis.com/contact"
28
+ },
29
+ "license": "MIT",
30
+ "author": "Data and APIs (https://dataandapis.com)",
31
+ "type": "module",
32
+ "main": "./dist/index.cjs",
33
+ "module": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "exports": {
36
+ ".": {
37
+ "import": {
38
+ "types": "./dist/index.d.ts",
39
+ "default": "./dist/index.js"
40
+ },
41
+ "require": {
42
+ "types": "./dist/index.d.cts",
43
+ "default": "./dist/index.cjs"
44
+ }
45
+ },
46
+ "./package.json": "./package.json"
47
+ },
48
+ "files": [
49
+ "dist",
50
+ "CHANGELOG.md"
51
+ ],
52
+ "sideEffects": false,
53
+ "engines": {
54
+ "node": ">=18"
55
+ },
56
+ "scripts": {
57
+ "sync": "node scripts/sync-catalog.mjs",
58
+ "generate": "node scripts/generate.mjs",
59
+ "build": "npm run generate && tsup",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "npm run build && node --test test/*.test.mjs && node test/types/check.mjs",
62
+ "lint:package": "publint && attw --pack .",
63
+ "prepublishOnly": "npm run typecheck && npm test && npm run lint:package"
64
+ },
65
+ "devDependencies": {
66
+ "@arethetypeswrong/cli": "^0.18.2",
67
+ "@types/node": "^22.20.5",
68
+ "publint": "^0.3.12",
69
+ "tsup": "^8.5.0",
70
+ "typescript": "^5.9.2"
71
+ }
72
+ }