scrapebadger 0.1.9 → 0.3.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.
@@ -1,3 +1,7 @@
1
+ import { createHmac, timingSafeEqual } from 'crypto';
2
+ import { EventEmitter } from 'events';
3
+ import WebSocket from 'ws';
4
+
1
5
  // src/internal/pagination.ts
2
6
  function createPaginatedResponse(data, cursor) {
3
7
  return {
@@ -251,6 +255,7 @@ var TweetsClient = class {
251
255
  params: {
252
256
  query,
253
257
  query_type: options.queryType ?? "Top",
258
+ count: options.count,
254
259
  cursor: options.cursor
255
260
  }
256
261
  }
@@ -1138,6 +1143,688 @@ var GeoClient = class {
1138
1143
  }
1139
1144
  };
1140
1145
 
1146
+ // src/internal/exceptions.ts
1147
+ var ScrapeBadgerError = class _ScrapeBadgerError extends Error {
1148
+ constructor(message) {
1149
+ super(message);
1150
+ this.name = "ScrapeBadgerError";
1151
+ Object.setPrototypeOf(this, _ScrapeBadgerError.prototype);
1152
+ }
1153
+ };
1154
+ var WebSocketStreamError = class _WebSocketStreamError extends ScrapeBadgerError {
1155
+ /** WebSocket close code or server error code */
1156
+ code;
1157
+ constructor(message = "WebSocket stream error", code) {
1158
+ super(message);
1159
+ this.name = "WebSocketStreamError";
1160
+ this.code = code;
1161
+ Object.setPrototypeOf(this, _WebSocketStreamError.prototype);
1162
+ }
1163
+ };
1164
+
1165
+ // src/twitter/stream.ts
1166
+ var MIN_RECONNECT_DELAY_SECONDS = 5;
1167
+ function wsUrlFromBase(baseUrl) {
1168
+ if (baseUrl.startsWith("https://")) {
1169
+ return baseUrl.replace("https://", "wss://") + "/v1/twitter/stream";
1170
+ }
1171
+ if (baseUrl.startsWith("http://")) {
1172
+ return baseUrl.replace("http://", "ws://") + "/v1/twitter/stream";
1173
+ }
1174
+ return baseUrl + "/v1/twitter/stream";
1175
+ }
1176
+ function parseEvent(raw) {
1177
+ const type = raw["type"];
1178
+ switch (type) {
1179
+ case "connected":
1180
+ return {
1181
+ type: "connected",
1182
+ connectionId: raw["connection_id"],
1183
+ apiKeyId: raw["api_key_id"]
1184
+ };
1185
+ case "ping":
1186
+ return {
1187
+ type: "ping",
1188
+ timestamp: raw["timestamp"]
1189
+ };
1190
+ case "tweet":
1191
+ return {
1192
+ type: "tweet",
1193
+ monitorId: raw["monitor_id"],
1194
+ tweetId: raw["tweet_id"],
1195
+ authorUsername: raw["author_username"],
1196
+ tweetPublishedAt: raw["tweet_published_at"],
1197
+ detectedAt: raw["detected_at"],
1198
+ latencyMs: raw["latency_ms"],
1199
+ tweet: raw["tweet"]
1200
+ };
1201
+ case "error":
1202
+ return {
1203
+ type: "error",
1204
+ code: raw["code"],
1205
+ message: raw["message"]
1206
+ };
1207
+ default:
1208
+ return {
1209
+ type: "error",
1210
+ code: 0,
1211
+ message: `Unknown event type: ${String(type)}`
1212
+ };
1213
+ }
1214
+ }
1215
+ var StreamClient = class {
1216
+ client;
1217
+ constructor(client) {
1218
+ this.client = client;
1219
+ }
1220
+ // ===========================================================================
1221
+ // Monitor CRUD
1222
+ // ===========================================================================
1223
+ /**
1224
+ * Create a new stream monitor.
1225
+ *
1226
+ * @param params - Monitor configuration.
1227
+ * @returns The created StreamMonitor.
1228
+ * @throws InsufficientCreditsError - Credit balance below tier threshold (402).
1229
+ * @throws ValidationError - Invalid username or interval (422).
1230
+ * @throws ScrapeBadgerError - Name conflict (409).
1231
+ * @throws AuthenticationError - Invalid API key (401).
1232
+ *
1233
+ * @example
1234
+ * ```typescript
1235
+ * const monitor = await client.twitter.stream.createMonitor({
1236
+ * name: "Breaking News",
1237
+ * usernames: ["cnnbrk", "bbcbreaking"],
1238
+ * pollIntervalSeconds: 5,
1239
+ * });
1240
+ * ```
1241
+ */
1242
+ async createMonitor(params) {
1243
+ const body = {
1244
+ name: params.name,
1245
+ usernames: params.usernames,
1246
+ poll_interval_seconds: params.pollIntervalSeconds
1247
+ };
1248
+ if (params.webhookUrl !== void 0) body["webhook_url"] = params.webhookUrl;
1249
+ if (params.webhookSecret !== void 0) body["webhook_secret"] = params.webhookSecret;
1250
+ return this.client.request("/v1/twitter/stream/monitors", {
1251
+ method: "POST",
1252
+ body
1253
+ });
1254
+ }
1255
+ /**
1256
+ * List stream monitors for the authenticated API key.
1257
+ *
1258
+ * @param options - Filter and pagination options.
1259
+ * @returns StreamMonitorList with pagination metadata.
1260
+ *
1261
+ * @example
1262
+ * ```typescript
1263
+ * const { monitors, total } = await client.twitter.stream.listMonitors({
1264
+ * status: "active",
1265
+ * });
1266
+ * console.log(`${total} active monitors`);
1267
+ * ```
1268
+ */
1269
+ async listMonitors(options) {
1270
+ const params = {
1271
+ page: options?.page ?? 1,
1272
+ page_size: options?.pageSize ?? 20,
1273
+ status: options?.status
1274
+ };
1275
+ return this.client.request("/v1/twitter/stream/monitors", {
1276
+ params
1277
+ });
1278
+ }
1279
+ /**
1280
+ * Get a single stream monitor by ID.
1281
+ *
1282
+ * @param monitorId - UUID of the monitor.
1283
+ * @returns The StreamMonitor.
1284
+ * @throws NotFoundError - No monitor with that ID for this API key.
1285
+ *
1286
+ * @example
1287
+ * ```typescript
1288
+ * const monitor = await client.twitter.stream.getMonitor("550e8400-...");
1289
+ * console.log(`${monitor.name}: ${monitor.status}`);
1290
+ * ```
1291
+ */
1292
+ async getMonitor(monitorId) {
1293
+ return this.client.request(`/v1/twitter/stream/monitors/${monitorId}`);
1294
+ }
1295
+ /**
1296
+ * Partially update a stream monitor.
1297
+ *
1298
+ * Only fields that are explicitly set in params are sent to the server.
1299
+ *
1300
+ * @param monitorId - UUID of the monitor.
1301
+ * @param params - Fields to update (all optional).
1302
+ * @returns The updated StreamMonitor.
1303
+ * @throws NotFoundError - Monitor not found for this API key.
1304
+ * @throws InsufficientCreditsError - When resuming with insufficient credits.
1305
+ *
1306
+ * @example
1307
+ * ```typescript
1308
+ * const monitor = await client.twitter.stream.updateMonitor("550e8400-...", {
1309
+ * pollIntervalSeconds: 60,
1310
+ * });
1311
+ * ```
1312
+ */
1313
+ async updateMonitor(monitorId, params) {
1314
+ const body = {};
1315
+ if (params.name !== void 0) body["name"] = params.name;
1316
+ if (params.usernames !== void 0) body["usernames"] = params.usernames;
1317
+ if (params.pollIntervalSeconds !== void 0)
1318
+ body["poll_interval_seconds"] = params.pollIntervalSeconds;
1319
+ if (params.status !== void 0) body["status"] = params.status;
1320
+ if (params.webhookUrl !== void 0) body["webhook_url"] = params.webhookUrl;
1321
+ if (params.webhookSecret !== void 0) body["webhook_secret"] = params.webhookSecret;
1322
+ return this.client.request(`/v1/twitter/stream/monitors/${monitorId}`, {
1323
+ method: "PATCH",
1324
+ body
1325
+ });
1326
+ }
1327
+ /**
1328
+ * Pause an active stream monitor.
1329
+ *
1330
+ * Convenience wrapper around updateMonitor({ status: "paused" }).
1331
+ *
1332
+ * @param monitorId - UUID of the monitor.
1333
+ * @returns The updated StreamMonitor with status="paused".
1334
+ */
1335
+ async pauseMonitor(monitorId) {
1336
+ return this.updateMonitor(monitorId, { status: "paused" });
1337
+ }
1338
+ /**
1339
+ * Resume a paused stream monitor.
1340
+ *
1341
+ * Convenience wrapper around updateMonitor({ status: "active" }).
1342
+ *
1343
+ * @param monitorId - UUID of the monitor.
1344
+ * @returns The updated StreamMonitor with status="active".
1345
+ * @throws InsufficientCreditsError - If credits are below the tier threshold.
1346
+ */
1347
+ async resumeMonitor(monitorId) {
1348
+ return this.updateMonitor(monitorId, { status: "active" });
1349
+ }
1350
+ /**
1351
+ * Delete a stream monitor and all its associated logs. Irreversible.
1352
+ *
1353
+ * @param monitorId - UUID of the monitor.
1354
+ * @throws NotFoundError - Monitor not found for this API key.
1355
+ *
1356
+ * @example
1357
+ * ```typescript
1358
+ * await client.twitter.stream.deleteMonitor("550e8400-...");
1359
+ * ```
1360
+ */
1361
+ async deleteMonitor(monitorId) {
1362
+ await this.client.request(`/v1/twitter/stream/monitors/${monitorId}`, {
1363
+ method: "DELETE"
1364
+ });
1365
+ }
1366
+ // ===========================================================================
1367
+ // Delivery and Billing Logs
1368
+ // ===========================================================================
1369
+ /**
1370
+ * List tweet delivery logs.
1371
+ *
1372
+ * @param options - Filter and pagination options.
1373
+ * @returns DeliveryLogList with pagination metadata.
1374
+ */
1375
+ async listDeliveryLogs(options) {
1376
+ const params = {
1377
+ page: options?.page ?? 1,
1378
+ page_size: options?.pageSize ?? 20,
1379
+ sort: options?.sort ?? "desc",
1380
+ monitor_id: options?.monitorId,
1381
+ author_username: options?.authorUsername,
1382
+ delivery_status: options?.deliveryStatus
1383
+ };
1384
+ return this.client.request("/v1/twitter/stream/logs", { params });
1385
+ }
1386
+ /**
1387
+ * List billing activity logs.
1388
+ *
1389
+ * @param options - Filter and pagination options.
1390
+ * @returns BillingLogList with pagination metadata.
1391
+ */
1392
+ async listBillingLogs(options) {
1393
+ const params = {
1394
+ page: options?.page ?? 1,
1395
+ page_size: options?.pageSize ?? 20,
1396
+ monitor_id: options?.monitorId
1397
+ };
1398
+ return this.client.request("/v1/twitter/stream/billing-logs", { params });
1399
+ }
1400
+ // ===========================================================================
1401
+ // Filter Rules CRUD
1402
+ // ===========================================================================
1403
+ /**
1404
+ * Create a new tweet filter rule.
1405
+ *
1406
+ * @param params - Filter rule configuration.
1407
+ * @returns The created FilterRuleResponse.
1408
+ * @throws ValidationError - Invalid query or interval (422).
1409
+ * @throws InsufficientCreditsError - Credit balance below tier threshold (402).
1410
+ * @throws AuthenticationError - Invalid API key (401).
1411
+ *
1412
+ * @example
1413
+ * ```typescript
1414
+ * const rule = await client.twitter.stream.createFilterRule({
1415
+ * tag: "python news",
1416
+ * query: "#python lang:en -is:retweet",
1417
+ * interval_seconds: 60,
1418
+ * });
1419
+ * console.log(`Created: ${rule.id}, tier: ${rule.pricing_tier}`);
1420
+ * ```
1421
+ */
1422
+ async createFilterRule(params) {
1423
+ const body = {
1424
+ tag: params.tag,
1425
+ query: params.query,
1426
+ interval_seconds: params.interval_seconds
1427
+ };
1428
+ if (params.webhook_url !== void 0) body["webhook_url"] = params.webhook_url;
1429
+ if (params.webhook_secret !== void 0) body["webhook_secret"] = params.webhook_secret;
1430
+ if (params.max_results_per_poll !== void 0)
1431
+ body["max_results_per_poll"] = params.max_results_per_poll;
1432
+ return this.client.request("/v1/twitter/stream/filter-rules", {
1433
+ method: "POST",
1434
+ body
1435
+ });
1436
+ }
1437
+ /**
1438
+ * List filter rules for the authenticated API key.
1439
+ *
1440
+ * @param options - Filter and pagination options.
1441
+ * @returns FilterRuleListResponse with pagination metadata.
1442
+ *
1443
+ * @example
1444
+ * ```typescript
1445
+ * const { rules, total } = await client.twitter.stream.listFilterRules({
1446
+ * status: "active",
1447
+ * });
1448
+ * console.log(`${total} active rules`);
1449
+ * ```
1450
+ */
1451
+ async listFilterRules(options) {
1452
+ const params = {
1453
+ limit: options?.limit ?? 20,
1454
+ offset: options?.offset ?? 0,
1455
+ status: options?.status
1456
+ };
1457
+ return this.client.request("/v1/twitter/stream/filter-rules", {
1458
+ params
1459
+ });
1460
+ }
1461
+ /**
1462
+ * Get a single filter rule by ID.
1463
+ *
1464
+ * @param ruleId - UUID of the filter rule.
1465
+ * @returns The FilterRuleResponse.
1466
+ * @throws NotFoundError - No rule with that ID for this API key.
1467
+ *
1468
+ * @example
1469
+ * ```typescript
1470
+ * const rule = await client.twitter.stream.getFilterRule("550e8400-...");
1471
+ * console.log(`${rule.tag}: ${rule.status}`);
1472
+ * ```
1473
+ */
1474
+ async getFilterRule(ruleId) {
1475
+ return this.client.request(`/v1/twitter/stream/filter-rules/${ruleId}`);
1476
+ }
1477
+ /**
1478
+ * Partially update a filter rule.
1479
+ *
1480
+ * Only fields that are explicitly set in params are sent to the server.
1481
+ *
1482
+ * @param ruleId - UUID of the filter rule.
1483
+ * @param params - Fields to update (all optional).
1484
+ * @returns The updated FilterRuleResponse.
1485
+ * @throws NotFoundError - Rule not found for this API key.
1486
+ * @throws ValidationError - Invalid field values (422).
1487
+ *
1488
+ * @example
1489
+ * ```typescript
1490
+ * const rule = await client.twitter.stream.updateFilterRule("550e8400-...", {
1491
+ * interval_seconds: 120,
1492
+ * });
1493
+ * ```
1494
+ */
1495
+ async updateFilterRule(ruleId, params) {
1496
+ const body = {};
1497
+ if (params.tag !== void 0) body["tag"] = params.tag;
1498
+ if (params.query !== void 0) body["query"] = params.query;
1499
+ if (params.interval_seconds !== void 0) body["interval_seconds"] = params.interval_seconds;
1500
+ if (params.status !== void 0) body["status"] = params.status;
1501
+ if (params.webhook_url !== void 0) body["webhook_url"] = params.webhook_url;
1502
+ if (params.webhook_secret !== void 0) body["webhook_secret"] = params.webhook_secret;
1503
+ if (params.max_results_per_poll !== void 0)
1504
+ body["max_results_per_poll"] = params.max_results_per_poll;
1505
+ return this.client.request(`/v1/twitter/stream/filter-rules/${ruleId}`, {
1506
+ method: "PATCH",
1507
+ body
1508
+ });
1509
+ }
1510
+ /**
1511
+ * Delete a filter rule and all its associated logs. Irreversible.
1512
+ *
1513
+ * @param ruleId - UUID of the filter rule.
1514
+ * @throws NotFoundError - Rule not found for this API key.
1515
+ *
1516
+ * @example
1517
+ * ```typescript
1518
+ * await client.twitter.stream.deleteFilterRule("550e8400-...");
1519
+ * ```
1520
+ */
1521
+ async deleteFilterRule(ruleId) {
1522
+ await this.client.request(`/v1/twitter/stream/filter-rules/${ruleId}`, {
1523
+ method: "DELETE"
1524
+ });
1525
+ }
1526
+ // ===========================================================================
1527
+ // Filter Rules Utility
1528
+ // ===========================================================================
1529
+ /**
1530
+ * Validate a Twitter search query before creating a rule.
1531
+ *
1532
+ * @param query - The Twitter search query to validate.
1533
+ * @returns FilterRuleValidateResponse with validity and sample result count.
1534
+ *
1535
+ * @example
1536
+ * ```typescript
1537
+ * const result = await client.twitter.stream.validateFilterRuleQuery(
1538
+ * "#python lang:en -is:retweet"
1539
+ * );
1540
+ * if (!result.valid) {
1541
+ * console.error("Invalid query:", result.error);
1542
+ * }
1543
+ * ```
1544
+ */
1545
+ async validateFilterRuleQuery(query) {
1546
+ return this.client.request(
1547
+ "/v1/twitter/stream/filter-rules/validate",
1548
+ { method: "POST", body: { query } }
1549
+ );
1550
+ }
1551
+ /**
1552
+ * List tweet delivery logs for a specific filter rule.
1553
+ *
1554
+ * @param ruleId - UUID of the filter rule.
1555
+ * @param options - Filter and pagination options.
1556
+ * @returns FilterRuleDeliveryLogListResponse with pagination metadata.
1557
+ *
1558
+ * @example
1559
+ * ```typescript
1560
+ * const { logs, total } = await client.twitter.stream.listFilterRuleLogs(
1561
+ * "550e8400-...",
1562
+ * { limit: 50, deliveryStatus: "webhook_delivered" }
1563
+ * );
1564
+ * ```
1565
+ */
1566
+ async listFilterRuleLogs(ruleId, options) {
1567
+ const params = {
1568
+ limit: options?.limit ?? 20,
1569
+ offset: options?.offset ?? 0,
1570
+ sort: options?.sort ?? "desc",
1571
+ delivery_status: options?.deliveryStatus
1572
+ };
1573
+ return this.client.request(
1574
+ `/v1/twitter/stream/filter-rules/${ruleId}/logs`,
1575
+ { params }
1576
+ );
1577
+ }
1578
+ /**
1579
+ * Get all available filter rule pricing tiers.
1580
+ *
1581
+ * @returns FilterRulePricingTiersResponse listing all tiers.
1582
+ *
1583
+ * @example
1584
+ * ```typescript
1585
+ * const { tiers } = await client.twitter.stream.getFilterRulePricingTiers();
1586
+ * tiers.forEach((t) => console.log(t.tier_label, t.credits_per_rule_per_day));
1587
+ * ```
1588
+ */
1589
+ async getFilterRulePricingTiers() {
1590
+ return this.client.request(
1591
+ "/v1/twitter/stream/filter-rules-pricing"
1592
+ );
1593
+ }
1594
+ // ===========================================================================
1595
+ // WebSocket Streaming -- EventEmitter style
1596
+ // ===========================================================================
1597
+ /**
1598
+ * Connect to the WebSocket stream and return an EventEmitter.
1599
+ *
1600
+ * The caller subscribes to events via `.on("tweet", handler)`.
1601
+ * The SDK handles pong replies to server pings automatically.
1602
+ * Call `.close()` on the emitter to disconnect cleanly.
1603
+ *
1604
+ * If reconnect is true, the emitter automatically reconnects after
1605
+ * disconnects (other than auth failures). A new "connected" event is
1606
+ * emitted on each reconnect.
1607
+ *
1608
+ * @param options - Connection options (reconnect, delay, maxReconnects).
1609
+ * @returns StreamEmitter -- an EventEmitter subclass.
1610
+ *
1611
+ * @example
1612
+ * ```typescript
1613
+ * const stream = client.twitter.stream.connect();
1614
+ * stream.on("connected", (e) => console.log("Connected:", e.connectionId));
1615
+ * stream.on("tweet", (event) => {
1616
+ * console.log(`@${event.authorUsername}: ${event.tweet.text}`);
1617
+ * console.log(` latency: ${event.latencyMs}ms`);
1618
+ * });
1619
+ * stream.on("error", (err) => console.error("Stream error:", err));
1620
+ * stream.on("close", () => console.log("Stream closed"));
1621
+ *
1622
+ * // Later:
1623
+ * stream.close();
1624
+ * ```
1625
+ */
1626
+ connect(options = {}) {
1627
+ const { reconnect = false, reconnectDelaySeconds = 90, maxReconnects } = options;
1628
+ const delay = Math.max(MIN_RECONNECT_DELAY_SECONDS, reconnectDelaySeconds) * 1e3;
1629
+ const wsUrl = wsUrlFromBase(this.client.config.baseUrl);
1630
+ const apiKey = this.client.config.apiKey;
1631
+ const emitter = new EventEmitter();
1632
+ let ws = null;
1633
+ let closed = false;
1634
+ let reconnectCount = 0;
1635
+ const connectOnce = () => {
1636
+ ws = new WebSocket(wsUrl, { headers: { "x-api-key": apiKey } });
1637
+ ws.on("message", (data) => {
1638
+ let raw;
1639
+ try {
1640
+ raw = JSON.parse(String(data));
1641
+ } catch {
1642
+ return;
1643
+ }
1644
+ const event = parseEvent(raw);
1645
+ if (event.type === "ping") {
1646
+ ws?.send(JSON.stringify({ type: "pong" }));
1647
+ emitter.emit("ping", event);
1648
+ return;
1649
+ }
1650
+ if (event.type === "error") {
1651
+ const code = event.code;
1652
+ const err = new WebSocketStreamError(event.message, code);
1653
+ emitter.emit("error", err);
1654
+ if (code === 4001 || code === 4003) {
1655
+ closed = true;
1656
+ ws?.close();
1657
+ }
1658
+ return;
1659
+ }
1660
+ emitter.emit(event.type, event);
1661
+ });
1662
+ ws.on("open", () => {
1663
+ });
1664
+ ws.on("close", (code, reason) => {
1665
+ if (closed) {
1666
+ emitter.emit("close");
1667
+ return;
1668
+ }
1669
+ if (!reconnect) {
1670
+ const reasonStr = reason instanceof Buffer ? reason.toString() : String(reason ?? "");
1671
+ emitter.emit(
1672
+ "error",
1673
+ new WebSocketStreamError(`WebSocket closed: ${reasonStr || String(code)}`)
1674
+ );
1675
+ emitter.emit("close");
1676
+ return;
1677
+ }
1678
+ if (maxReconnects !== void 0 && reconnectCount >= maxReconnects) {
1679
+ emitter.emit(
1680
+ "error",
1681
+ new WebSocketStreamError(`Max reconnects (${maxReconnects}) exhausted`)
1682
+ );
1683
+ emitter.emit("close");
1684
+ return;
1685
+ }
1686
+ reconnectCount++;
1687
+ setTimeout(connectOnce, delay);
1688
+ });
1689
+ ws.on("error", (err) => {
1690
+ const message = err instanceof Error ? err.message : String(err);
1691
+ emitter.emit("error", new WebSocketStreamError(message));
1692
+ });
1693
+ };
1694
+ emitter.close = () => {
1695
+ closed = true;
1696
+ ws?.close(1e3, "Client closed");
1697
+ };
1698
+ connectOnce();
1699
+ return emitter;
1700
+ }
1701
+ // ===========================================================================
1702
+ // WebSocket Streaming -- AsyncIterator style
1703
+ // ===========================================================================
1704
+ /**
1705
+ * Connect to the WebSocket stream and return an AsyncIterator.
1706
+ *
1707
+ * Iterates over StreamEvent objects. The SDK handles pong replies
1708
+ * automatically but still yields PingEvent to the caller (the caller
1709
+ * may ignore ping events).
1710
+ *
1711
+ * @param options - Connection options (reconnect, delay, maxReconnects).
1712
+ * @yields StreamEvent
1713
+ *
1714
+ * @example
1715
+ * ```typescript
1716
+ * for await (const event of client.twitter.stream.connectIter()) {
1717
+ * if (event.type === "tweet") {
1718
+ * console.log(`@${event.authorUsername}: ${event.latencyMs}ms`);
1719
+ * }
1720
+ * }
1721
+ * ```
1722
+ *
1723
+ * @example With auto-reconnect
1724
+ * ```typescript
1725
+ * for await (const event of client.twitter.stream.connectIter({
1726
+ * reconnect: true,
1727
+ * reconnectDelaySeconds: 90,
1728
+ * })) {
1729
+ * if (event.type === "tweet") {
1730
+ * // process(event);
1731
+ * }
1732
+ * }
1733
+ * ```
1734
+ */
1735
+ async *connectIter(options = {}) {
1736
+ const { reconnect = false, reconnectDelaySeconds = 90, maxReconnects } = options;
1737
+ const delay = Math.max(MIN_RECONNECT_DELAY_SECONDS, reconnectDelaySeconds) * 1e3;
1738
+ const wsUrl = wsUrlFromBase(this.client.config.baseUrl);
1739
+ const apiKey = this.client.config.apiKey;
1740
+ let reconnectCount = 0;
1741
+ while (true) {
1742
+ const events = [];
1743
+ let resolveWait = null;
1744
+ let rejectWait = null;
1745
+ let done = false;
1746
+ const ws = new WebSocket(wsUrl, { headers: { "x-api-key": apiKey } });
1747
+ const waitForEvent = () => new Promise((res, rej) => {
1748
+ resolveWait = res;
1749
+ rejectWait = rej;
1750
+ });
1751
+ ws.on("message", (data) => {
1752
+ let raw;
1753
+ try {
1754
+ raw = JSON.parse(String(data));
1755
+ } catch {
1756
+ return;
1757
+ }
1758
+ const event = parseEvent(raw);
1759
+ if (event.type === "ping") {
1760
+ ws.send(JSON.stringify({ type: "pong" }));
1761
+ }
1762
+ if (event.type === "error") {
1763
+ const code = event.code;
1764
+ if (code === 4001 || code === 4003) {
1765
+ rejectWait?.(new WebSocketStreamError(event.message, code));
1766
+ rejectWait = null;
1767
+ resolveWait = null;
1768
+ return;
1769
+ }
1770
+ }
1771
+ events.push(event);
1772
+ resolveWait?.();
1773
+ resolveWait = null;
1774
+ rejectWait = null;
1775
+ });
1776
+ ws.on("close", () => {
1777
+ done = true;
1778
+ resolveWait?.();
1779
+ resolveWait = null;
1780
+ rejectWait = null;
1781
+ });
1782
+ ws.on("error", (err) => {
1783
+ const message = err instanceof Error ? err.message : String(err);
1784
+ rejectWait?.(new WebSocketStreamError(message));
1785
+ rejectWait = null;
1786
+ resolveWait = null;
1787
+ });
1788
+ try {
1789
+ while (!done || events.length > 0) {
1790
+ if (events.length === 0) {
1791
+ await waitForEvent();
1792
+ }
1793
+ while (events.length > 0) {
1794
+ yield events.shift();
1795
+ }
1796
+ }
1797
+ } catch (err) {
1798
+ ws.close();
1799
+ throw err;
1800
+ } finally {
1801
+ ws.close();
1802
+ }
1803
+ if (!reconnect) {
1804
+ return;
1805
+ }
1806
+ if (maxReconnects !== void 0 && reconnectCount >= maxReconnects) {
1807
+ throw new WebSocketStreamError(`Max reconnects (${maxReconnects}) exhausted`);
1808
+ }
1809
+ reconnectCount++;
1810
+ await new Promise((res) => setTimeout(res, delay));
1811
+ }
1812
+ }
1813
+ };
1814
+ function verifyWebhookSignature(secret, body, signatureHeader) {
1815
+ if (!signatureHeader.startsWith("sha256=")) {
1816
+ return false;
1817
+ }
1818
+ const expectedHex = signatureHeader.slice("sha256=".length);
1819
+ const bodyBuffer = typeof body === "string" ? Buffer.from(body, "utf-8") : body;
1820
+ const actualHex = createHmac("sha256", secret).update(bodyBuffer).digest("hex");
1821
+ try {
1822
+ return timingSafeEqual(Buffer.from(expectedHex, "hex"), Buffer.from(actualHex, "hex"));
1823
+ } catch {
1824
+ return false;
1825
+ }
1826
+ }
1827
+
1141
1828
  // src/twitter/client.ts
1142
1829
  var TwitterClient = class {
1143
1830
  /** Client for tweet operations */
@@ -1152,6 +1839,8 @@ var TwitterClient = class {
1152
1839
  trends;
1153
1840
  /** Client for geo/places operations */
1154
1841
  geo;
1842
+ /** Client for real-time stream monitor management and WebSocket streaming */
1843
+ stream;
1155
1844
  /**
1156
1845
  * Create a new Twitter client.
1157
1846
  *
@@ -1164,9 +1853,10 @@ var TwitterClient = class {
1164
1853
  this.communities = new CommunitiesClient(client);
1165
1854
  this.trends = new TrendsClient(client);
1166
1855
  this.geo = new GeoClient(client);
1856
+ this.stream = new StreamClient(client);
1167
1857
  }
1168
1858
  };
1169
1859
 
1170
- export { CommunitiesClient, GeoClient, ListsClient, TrendsClient, TweetsClient, TwitterClient, UsersClient };
1860
+ export { CommunitiesClient, GeoClient, ListsClient, StreamClient, TrendsClient, TweetsClient, TwitterClient, UsersClient, verifyWebhookSignature };
1171
1861
  //# sourceMappingURL=index.mjs.map
1172
1862
  //# sourceMappingURL=index.mjs.map