oilpriceapi 0.3.1 → 0.5.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/README.md CHANGED
@@ -10,12 +10,14 @@ Official Node.js SDK for [Oil Price API](https://www.oilpriceapi.com) - Get real
10
10
  - ✅ **Simple** - Get started in 5 lines of code
11
11
  - 🔒 **Type-Safe** - Full TypeScript support with detailed type definitions
12
12
  - ⚡ **Fast** - Zero dependencies, uses native fetch (Node 18+)
13
- - 🎯 **Comprehensive** - Covers all API endpoints
13
+ - 🎯 **Comprehensive** - Covers all API endpoints including diesel prices & alerts
14
14
  - 🚀 **Modern** - ES Modules, async/await, Promise-based
15
15
  - 🛡️ **Robust** - Custom error classes for better error handling
16
16
  - 🔄 **Resilient** - Automatic retries with exponential backoff
17
17
  - ⏱️ **Reliable** - Request timeouts and smart error handling
18
18
  - 🐛 **Debuggable** - Built-in debug logging mode
19
+ - ⛽ **NEW v0.4.0** - Diesel prices (state averages + station-level pricing)
20
+ - 🔔 **NEW v0.5.0** - Price alerts with webhook notifications
19
21
 
20
22
  ## Installation
21
23
 
@@ -51,13 +53,12 @@ const prices = await client.getLatestPrices();
51
53
  // [
52
54
  // {
53
55
  // code: 'WTI_USD',
54
- // name: 'WTI Crude Oil',
55
- // value: 74.25,
56
+ // price: 74.25,
57
+ // formatted: '$74.25',
56
58
  // currency: 'USD',
57
- // unit: 'barrel',
58
- // timestamp: '2024-11-24T12:00:00Z',
59
+ // type: 'spot_price',
59
60
  // created_at: '2024-11-24T12:01:00Z',
60
- // updated_at: '2024-11-24T12:01:00Z'
61
+ // source: 'oilprice.investing_com'
61
62
  // },
62
63
  // // ... more prices
63
64
  // ]
@@ -68,11 +69,11 @@ const prices = await client.getLatestPrices();
68
69
  ```typescript
69
70
  // Get only WTI crude oil price
70
71
  const wti = await client.getLatestPrices({ commodity: 'WTI_USD' });
71
- console.log(`WTI: $${wti[0].value} per barrel`);
72
+ console.log(`WTI: ${wti[0].formatted} per barrel`);
72
73
 
73
74
  // Get only Brent crude price
74
75
  const brent = await client.getLatestPrices({ commodity: 'BRENT_CRUDE_USD' });
75
- console.log(`Brent: $${brent[0].value} per barrel`);
76
+ console.log(`Brent: ${brent[0].formatted} per barrel`);
76
77
  ```
77
78
 
78
79
  ### Get Historical Prices (Past Week)
@@ -98,6 +99,176 @@ const prices = await client.getHistoricalPrices({
98
99
  console.log(`Got ${prices.length} data points for 2024`);
99
100
  ```
100
101
 
102
+ ### Get Diesel Prices (New in v0.4.0)
103
+
104
+ #### Get State Average Diesel Price
105
+
106
+ ```typescript
107
+ // Get California diesel price
108
+ const caPrice = await client.diesel.getPrice('CA');
109
+ console.log(`California diesel: $${caPrice.price}/gallon`);
110
+ console.log(`Source: ${caPrice.source}`);
111
+ console.log(`Last updated: ${caPrice.updated_at}`);
112
+
113
+ // Example output:
114
+ // California diesel: $3.89/gallon
115
+ // Source: EIA
116
+ // Last updated: 2025-12-15T10:00:00Z
117
+ ```
118
+
119
+ #### Get Nearby Diesel Stations
120
+
121
+ ```typescript
122
+ // Find diesel stations near San Francisco
123
+ const result = await client.diesel.getStations({
124
+ lat: 37.7749, // San Francisco latitude
125
+ lng: -122.4194, // San Francisco longitude
126
+ radius: 8047 // 5 miles in meters (default if not specified)
127
+ });
128
+
129
+ console.log(`Regional average: $${result.regional_average.price}/gallon`);
130
+ console.log(`Found ${result.stations.length} stations within ${result.search_area.radius_miles} miles`);
131
+
132
+ // Print each station
133
+ result.stations.forEach(station => {
134
+ console.log(`\n${station.name}`);
135
+ console.log(` Address: ${station.address}`);
136
+ console.log(` Price: ${station.formatted_price}`);
137
+ console.log(` ${station.price_vs_average}`);
138
+ });
139
+
140
+ // Example output:
141
+ // Regional average: $3.89/gallon
142
+ // Found 12 stations within 5 miles
143
+ //
144
+ // Chevron Station
145
+ // Address: 123 Main St, San Francisco, CA
146
+ // Price: $3.75
147
+ // $0.14 cheaper than regional average
148
+ //
149
+ // Shell Gas
150
+ // Address: 456 Oak Ave, San Francisco, CA
151
+ // Price: $3.89
152
+ // Same as regional average
153
+ ```
154
+
155
+ #### Find Cheapest Diesel Station
156
+
157
+ ```typescript
158
+ const result = await client.diesel.getStations({
159
+ lat: 34.0522, // Los Angeles
160
+ lng: -118.2437,
161
+ radius: 5000 // ~3 miles
162
+ });
163
+
164
+ // Find the cheapest station
165
+ const cheapest = result.stations.reduce((min, station) =>
166
+ station.diesel_price < min.diesel_price ? station : min
167
+ );
168
+
169
+ console.log(`Cheapest diesel: ${cheapest.name} at ${cheapest.formatted_price}`);
170
+ console.log(`Savings: ${Math.abs(cheapest.price_delta!).toFixed(2)} per gallon vs regional average`);
171
+ ```
172
+
173
+ **Note:** Station-level diesel prices are available on paid tiers (Exploration and above). State averages are free.
174
+
175
+ ### Price Alerts (New in v0.5.0)
176
+
177
+ #### Create a Price Alert
178
+
179
+ ```typescript
180
+ // Create an alert when Brent crude exceeds $85
181
+ const alert = await client.alerts.create({
182
+ name: 'Brent High Alert',
183
+ commodity_code: 'BRENT_CRUDE_USD',
184
+ condition_operator: 'greater_than',
185
+ condition_value: 85.00,
186
+ webhook_url: 'https://your-app.com/webhooks/price-alert',
187
+ enabled: true,
188
+ cooldown_minutes: 60 // Wait 60 minutes between triggers
189
+ });
190
+
191
+ console.log(`Alert created: ${alert.name} (ID: ${alert.id})`);
192
+ ```
193
+
194
+ #### List All Alerts
195
+
196
+ ```typescript
197
+ const alerts = await client.alerts.list();
198
+
199
+ alerts.forEach(alert => {
200
+ console.log(`${alert.name}: ${alert.commodity_code} ${alert.condition_operator} ${alert.condition_value}`);
201
+ console.log(` Status: ${alert.enabled ? 'Active' : 'Disabled'}`);
202
+ console.log(` Triggers: ${alert.trigger_count}`);
203
+ console.log(` Last triggered: ${alert.last_triggered_at || 'Never'}`);
204
+ });
205
+ ```
206
+
207
+ #### Update an Alert
208
+
209
+ ```typescript
210
+ // Disable an alert
211
+ await client.alerts.update(alertId, { enabled: false });
212
+
213
+ // Change threshold and cooldown
214
+ await client.alerts.update(alertId, {
215
+ condition_value: 90.00,
216
+ cooldown_minutes: 120
217
+ });
218
+
219
+ // Update webhook URL
220
+ await client.alerts.update(alertId, {
221
+ webhook_url: 'https://new-app.com/webhook'
222
+ });
223
+ ```
224
+
225
+ #### Delete an Alert
226
+
227
+ ```typescript
228
+ await client.alerts.delete(alertId);
229
+ console.log('Alert deleted successfully');
230
+ ```
231
+
232
+ #### Test Webhook Endpoint
233
+
234
+ ```typescript
235
+ const result = await client.alerts.testWebhook('https://your-app.com/webhook');
236
+
237
+ if (result.success) {
238
+ console.log(`Webhook OK (${result.status_code}) - ${result.response_time_ms}ms`);
239
+ } else {
240
+ console.error(`Webhook failed: ${result.error}`);
241
+ }
242
+ ```
243
+
244
+ **Alert Operators:**
245
+ - `greater_than` - Trigger when price exceeds threshold
246
+ - `less_than` - Trigger when price falls below threshold
247
+ - `equals` - Trigger when price matches threshold exactly
248
+ - `greater_than_or_equal` - Trigger when price meets or exceeds threshold
249
+ - `less_than_or_equal` - Trigger when price is at or below threshold
250
+
251
+ **Webhook Payload Example:**
252
+ When an alert triggers, a POST request is sent to your webhook URL with:
253
+ ```json
254
+ {
255
+ "event": "price_alert.triggered",
256
+ "alert_id": "550e8400-e29b-41d4-a716-446655440000",
257
+ "alert_name": "Brent High Alert",
258
+ "commodity_code": "BRENT_CRUDE_USD",
259
+ "condition_operator": "greater_than",
260
+ "condition_value": 85.00,
261
+ "current_price": 86.50,
262
+ "triggered_at": "2025-12-15T14:30:00Z"
263
+ }
264
+ ```
265
+
266
+ **Limits:**
267
+ - Maximum 100 alerts per user
268
+ - Cooldown period: 0-1440 minutes (24 hours)
269
+ - Condition value: Must be between $0.01 and $1,000,000
270
+ - Webhook URL: Must use HTTPS protocol
271
+
101
272
  ### Advanced Configuration
102
273
 
103
274
  ```typescript
@@ -203,6 +374,39 @@ const { commodities } = await client.getCommodities();
203
374
  console.log(`Found ${commodities.length} commodities`);
204
375
  ```
205
376
 
377
+ **Diesel Prices:**
378
+ ```typescript
379
+ // State average (free)
380
+ const caPrice = await client.diesel.getPrice('CA');
381
+ console.log(`CA diesel: $${caPrice.price}/gal`);
382
+
383
+ // Nearby stations (paid tiers)
384
+ const stations = await client.diesel.getStations({
385
+ lat: 37.7749,
386
+ lng: -122.4194,
387
+ radius: 8047 // 5 miles
388
+ });
389
+ console.log(`Found ${stations.stations.length} stations`);
390
+ ```
391
+
392
+ **Price Alerts:**
393
+ ```typescript
394
+ // Create an alert
395
+ const alert = await client.alerts.create({
396
+ name: 'Brent High Alert',
397
+ commodity_code: 'BRENT_CRUDE_USD',
398
+ condition_operator: 'greater_than',
399
+ condition_value: 85.00,
400
+ webhook_url: 'https://your-app.com/webhook'
401
+ });
402
+
403
+ // List all alerts
404
+ const alerts = await client.alerts.list();
405
+
406
+ // Update an alert
407
+ await client.alerts.update(alert.id, { enabled: false });
408
+ ```
409
+
206
410
  **Error Handling:**
207
411
  ```typescript
208
412
  try {
@@ -274,6 +478,55 @@ Get metadata for a specific commodity by code.
274
478
 
275
479
  **Returns:** `Promise<Commodity>` - Commodity metadata object
276
480
 
481
+ ### `client.diesel`
482
+
483
+ Resource for diesel price data (state averages and station-level pricing).
484
+
485
+ ##### `diesel.getPrice(state)`
486
+
487
+ Get average diesel price for a US state from EIA data.
488
+
489
+ **Parameters:**
490
+ - `state` (string, required) - Two-letter US state code (e.g., "CA", "TX", "NY")
491
+
492
+ **Returns:** `Promise<DieselPrice>`
493
+
494
+ **Example:**
495
+ ```typescript
496
+ const caPrice = await client.diesel.getPrice('CA');
497
+ console.log(`California: $${caPrice.price}/gallon`);
498
+ ```
499
+
500
+ ##### `diesel.getStations(options)`
501
+
502
+ Get nearby diesel stations with current pricing from Google Maps data.
503
+
504
+ **Parameters:**
505
+ - `options.lat` (number, required) - Latitude (-90 to 90)
506
+ - `options.lng` (number, required) - Longitude (-180 to 180)
507
+ - `options.radius` (number, optional) - Search radius in meters (default: 8047 = 5 miles, max: 50000)
508
+
509
+ **Returns:** `Promise<DieselStationsResponse>`
510
+
511
+ **Tier Requirements:** Available on paid tiers (Exploration and above)
512
+
513
+ **Example:**
514
+ ```typescript
515
+ const result = await client.diesel.getStations({
516
+ lat: 37.7749,
517
+ lng: -122.4194,
518
+ radius: 8047 // 5 miles
519
+ });
520
+
521
+ console.log(`Found ${result.stations.length} stations`);
522
+ console.log(`Regional average: $${result.regional_average.price}/gallon`);
523
+
524
+ const cheapest = result.stations.reduce((min, s) =>
525
+ s.diesel_price < min.diesel_price ? s : min
526
+ );
527
+ console.log(`Cheapest: ${cheapest.name} at ${cheapest.formatted_price}`);
528
+ ```
529
+
277
530
  ### Types
278
531
 
279
532
  #### `Price`
@@ -291,6 +544,74 @@ interface Price {
291
544
  }
292
545
  ```
293
546
 
547
+ #### `DieselPrice`
548
+
549
+ ```typescript
550
+ interface DieselPrice {
551
+ state: string; // State code (e.g., "CA", "TX")
552
+ price: number; // Average diesel price in USD per gallon
553
+ currency: string; // Currency code (always "USD")
554
+ unit: string; // Unit of measurement (always "gallon")
555
+ granularity: string; // Level (e.g., "state", "national")
556
+ source: string; // Data source (e.g., "EIA")
557
+ updated_at: string; // ISO 8601 timestamp of last update
558
+ cached?: boolean; // Whether served from cache
559
+ }
560
+ ```
561
+
562
+ #### `DieselStation`
563
+
564
+ ```typescript
565
+ interface DieselStation {
566
+ name: string; // Station name
567
+ address: string; // Full street address
568
+ location: {
569
+ lat: number; // Latitude
570
+ lng: number; // Longitude
571
+ };
572
+ diesel_price: number; // Price at this station (USD per gallon)
573
+ formatted_price: string;// Formatted price (e.g., "$3.89")
574
+ currency: string; // Currency code (always "USD")
575
+ unit: string; // Unit (always "gallon")
576
+ price_delta?: number; // Difference from regional average
577
+ price_vs_average?: string; // Human-readable comparison
578
+ fuel_types?: string[]; // Available fuel types
579
+ last_updated?: string; // ISO 8601 timestamp
580
+ }
581
+ ```
582
+
583
+ #### `DieselStationsResponse`
584
+
585
+ ```typescript
586
+ interface DieselStationsResponse {
587
+ regional_average: {
588
+ price: number; // Regional average price
589
+ currency: string; // Currency code
590
+ unit: string; // Unit
591
+ region: string; // Region name
592
+ granularity: string; // Granularity level
593
+ source: string; // Data source
594
+ };
595
+ stations: DieselStation[]; // List of nearby stations
596
+ search_area: {
597
+ center: {
598
+ lat: number; // Search center latitude
599
+ lng: number; // Search center longitude
600
+ };
601
+ radius_meters: number;// Search radius in meters
602
+ radius_miles: number; // Search radius in miles
603
+ };
604
+ metadata: {
605
+ total_stations: number; // Number of stations found
606
+ source: string; // Data source
607
+ cached: boolean; // Whether served from cache
608
+ api_cost: number; // Cost in dollars
609
+ timestamp: string; // ISO 8601 timestamp
610
+ cache_age_hours?: number; // Cache age in hours
611
+ };
612
+ }
613
+ ```
614
+
294
615
  ### Error Classes
295
616
 
296
617
  All errors extend `OilPriceAPIError`:
@@ -305,7 +626,7 @@ All errors extend `OilPriceAPIError`:
305
626
  The API provides prices for the following commodities:
306
627
 
307
628
  - **Crude Oil**: WTI, Brent Crude
308
- - **Refined Products**: Gasoline, Diesel, Heating Oil, Jet Fuel
629
+ - **Refined Products**: Gasoline, Diesel (state averages + station-level), Heating Oil, Jet Fuel
309
630
  - **Natural Gas**: US Natural Gas, EU Natural Gas, UK Natural Gas
310
631
  - **And more...**
311
632
 
@@ -313,7 +634,7 @@ See the [full list of commodities](https://www.oilpriceapi.com/commodities) in t
313
634
 
314
635
  ## Pricing & Rate Limits
315
636
 
316
- - **Free Tier**: 1,000 requests/month
637
+ - **Free Tier**: 100 requests (lifetime)
317
638
  - **Starter**: 50,000 requests/month - $49/mo
318
639
  - **Professional**: 100,000 requests/month - $99/mo
319
640
  - **Business**: 200,000 requests/month - $199/mo
package/dist/client.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { OilPriceAPIConfig, Price, LatestPricesOptions, HistoricalPricesOptions, Commodity, CommoditiesResponse, CategoriesResponse } from './types.js';
2
+ import { DieselResource } from './resources/diesel.js';
3
+ import { AlertsResource } from './resources/alerts.js';
2
4
  /**
3
5
  * Official Node.js client for Oil Price API
4
6
  *
@@ -33,6 +35,14 @@ export declare class OilPriceAPI {
33
35
  private retryStrategy;
34
36
  private timeout;
35
37
  private debug;
38
+ /**
39
+ * Diesel prices resource (state averages + station-level pricing)
40
+ */
41
+ readonly diesel: DieselResource;
42
+ /**
43
+ * Price alerts resource (create, manage, and monitor alerts)
44
+ */
45
+ readonly alerts: AlertsResource;
36
46
  constructor(config: OilPriceAPIConfig);
37
47
  /**
38
48
  * Log debug messages if debug mode is enabled
package/dist/client.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { OilPriceAPIError, AuthenticationError, RateLimitError, NotFoundError, ServerError, TimeoutError, } from './errors.js';
2
+ import { DieselResource } from './resources/diesel.js';
3
+ import { AlertsResource } from './resources/alerts.js';
2
4
  /**
3
5
  * Official Node.js client for Oil Price API
4
6
  *
@@ -37,6 +39,9 @@ export class OilPriceAPI {
37
39
  this.retryStrategy = config.retryStrategy || 'exponential';
38
40
  this.timeout = config.timeout || 90000; // 90 seconds for slow historical queries
39
41
  this.debug = config.debug || false;
42
+ // Initialize resources
43
+ this.diesel = new DieselResource(this);
44
+ this.alerts = new AlertsResource(this);
40
45
  }
41
46
  /**
42
47
  * Log debug messages if debug mode is enabled
@@ -121,7 +126,10 @@ export class OilPriceAPI {
121
126
  headers: {
122
127
  'Authorization': `Bearer ${this.apiKey}`,
123
128
  'Content-Type': 'application/json',
124
- 'User-Agent': 'oilpriceapi-node/0.3.1',
129
+ 'User-Agent': 'oilpriceapi-node/0.5.0',
130
+ 'X-SDK-Language': 'javascript',
131
+ 'X-SDK-Version': '0.5.0',
132
+ 'X-Client-Type': 'sdk',
125
133
  },
126
134
  signal: controller.signal,
127
135
  });
package/dist/index.d.ts CHANGED
@@ -7,4 +7,6 @@
7
7
  */
8
8
  export { OilPriceAPI } from './client.js';
9
9
  export type { OilPriceAPIConfig, RetryStrategy, Price, LatestPricesOptions, HistoricalPricesOptions, HistoricalPeriod, Commodity, CommoditiesResponse, CommodityCategory, CategoriesResponse, } from './types.js';
10
+ export type { DieselPrice, DieselStation, DieselStationsResponse, GetDieselStationsOptions, } from './resources/diesel.js';
11
+ export type { PriceAlert, CreateAlertParams, UpdateAlertParams, AlertOperator, WebhookTestResponse, } from './resources/alerts.js';
10
12
  export { OilPriceAPIError, AuthenticationError, RateLimitError, NotFoundError, ServerError, TimeoutError, } from './errors.js';