@shaivpidadi/trends-js 0.0.0-beta.6 → 0.0.0-beta.7

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.
@@ -0,0 +1,3 @@
1
+ import { GoogleTrendsEndpoints } from './types/enums';
2
+ import { GoogleTrendsMapper } from './types';
3
+ export declare const GOOGLE_TRENDS_MAPPER: Record<GoogleTrendsEndpoints, GoogleTrendsMapper>;
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GOOGLE_TRENDS_MAPPER = void 0;
4
+ const enums_1 = require("./types/enums");
4
5
  const GOOGLE_TRENDS_BASE_URL = 'trends.google.com';
5
6
  exports.GOOGLE_TRENDS_MAPPER = {
6
- ["dailyTrends" /* GoogleTrendsEndpoints.dailyTrends */]: {
7
+ [enums_1.GoogleTrendsEndpoints.dailyTrends]: {
7
8
  path: '/_/TrendsUi/data/batchexecute',
8
9
  method: 'POST',
9
10
  host: GOOGLE_TRENDS_BASE_URL,
@@ -12,7 +13,7 @@ exports.GOOGLE_TRENDS_MAPPER = {
12
13
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
13
14
  },
14
15
  },
15
- ["autocomplete" /* GoogleTrendsEndpoints.autocomplete */]: {
16
+ [enums_1.GoogleTrendsEndpoints.autocomplete]: {
16
17
  path: '/trends/api/autocomplete',
17
18
  method: 'GET',
18
19
  host: GOOGLE_TRENDS_BASE_URL,
@@ -21,14 +22,14 @@ exports.GOOGLE_TRENDS_MAPPER = {
21
22
  accept: 'application/json, text/plain, */*',
22
23
  },
23
24
  },
24
- ["explore" /* GoogleTrendsEndpoints.explore */]: {
25
+ [enums_1.GoogleTrendsEndpoints.explore]: {
25
26
  path: '/trends/api/explore',
26
27
  method: 'POST',
27
28
  host: GOOGLE_TRENDS_BASE_URL,
28
29
  url: `https://${GOOGLE_TRENDS_BASE_URL}/trends/api/explore`,
29
30
  headers: {},
30
31
  },
31
- ["interestByRegion" /* GoogleTrendsEndpoints.interestByRegion */]: {
32
+ [enums_1.GoogleTrendsEndpoints.interestByRegion]: {
32
33
  path: '/trends/api/widgetdata/comparedgeo',
33
34
  method: 'GET',
34
35
  host: GOOGLE_TRENDS_BASE_URL,
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GoogleTrendsApi = void 0;
4
+ const enums_1 = require("../types/enums");
5
+ const request_1 = require("./request");
6
+ const format_1 = require("./format");
7
+ const constants_1 = require("../constants");
8
+ const GoogleTrendsError_1 = require("../errors/GoogleTrendsError");
9
+ class GoogleTrendsApi {
10
+ /**
11
+ * Get autocomplete suggestions for a keyword
12
+ * @param keyword - The keyword to get suggestions for
13
+ * @param hl - Language code (default: 'en-US')
14
+ * @returns Promise with array of suggestion strings
15
+ */
16
+ async autocomplete(keyword, hl = 'en-US') {
17
+ if (!keyword) {
18
+ return { data: [] };
19
+ }
20
+ const options = {
21
+ ...constants_1.GOOGLE_TRENDS_MAPPER[enums_1.GoogleTrendsEndpoints.autocomplete],
22
+ qs: {
23
+ hl,
24
+ tz: '240',
25
+ },
26
+ };
27
+ try {
28
+ const response = await (0, request_1.request)(`${options.url}/${encodeURIComponent(keyword)}`, options);
29
+ const text = await response.text();
30
+ // Remove the first 5 characters (JSONP wrapper) and parse
31
+ const data = JSON.parse(text.slice(5));
32
+ return { data: data.default.topics.map((topic) => topic.title) };
33
+ }
34
+ catch (error) {
35
+ if (error instanceof Error) {
36
+ return { error: new GoogleTrendsError_1.NetworkError(error.message) };
37
+ }
38
+ return { error: new GoogleTrendsError_1.UnknownError() };
39
+ }
40
+ }
41
+ /**
42
+ * Get daily trending topics
43
+ * @param options - Options for daily trends request
44
+ * @returns Promise with trending topics data
45
+ */
46
+ async dailyTrends({ geo = 'US', lang = 'en' }) {
47
+ const defaultOptions = constants_1.GOOGLE_TRENDS_MAPPER[enums_1.GoogleTrendsEndpoints.dailyTrends];
48
+ const options = {
49
+ ...defaultOptions,
50
+ body: new URLSearchParams({
51
+ 'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"${lang}\\",24,1]",null,"generic"]]]`,
52
+ }).toString(),
53
+ contentType: 'form'
54
+ };
55
+ try {
56
+ const response = await (0, request_1.request)(options.url, options);
57
+ const text = await response.text();
58
+ const trendingTopics = (0, format_1.extractJsonFromResponse)(text);
59
+ if (!trendingTopics) {
60
+ return { error: new GoogleTrendsError_1.ParseError() };
61
+ }
62
+ return { data: trendingTopics };
63
+ }
64
+ catch (error) {
65
+ if (error instanceof Error) {
66
+ return { error: new GoogleTrendsError_1.NetworkError(error.message) };
67
+ }
68
+ return { error: new GoogleTrendsError_1.UnknownError() };
69
+ }
70
+ }
71
+ /**
72
+ * Get real-time trending topics
73
+ * @param options - Options for real-time trends request
74
+ * @returns Promise with trending topics data
75
+ */
76
+ async realTimeTrends({ geo = 'US', trendingHours = 4 }) {
77
+ const defaultOptions = constants_1.GOOGLE_TRENDS_MAPPER[enums_1.GoogleTrendsEndpoints.dailyTrends];
78
+ const options = {
79
+ ...defaultOptions,
80
+ body: new URLSearchParams({
81
+ 'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"en\\",${trendingHours},1]",null,"generic"]]]`,
82
+ }).toString(),
83
+ contentType: 'form'
84
+ };
85
+ try {
86
+ const response = await (0, request_1.request)(options.url, options);
87
+ const text = await response.text();
88
+ const trendingTopics = (0, format_1.extractJsonFromResponse)(text);
89
+ if (!trendingTopics) {
90
+ return { error: new GoogleTrendsError_1.ParseError() };
91
+ }
92
+ return { data: trendingTopics };
93
+ }
94
+ catch (error) {
95
+ if (error instanceof Error) {
96
+ return { error: new GoogleTrendsError_1.NetworkError(error.message) };
97
+ }
98
+ return { error: new GoogleTrendsError_1.UnknownError() };
99
+ }
100
+ }
101
+ async explore({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
102
+ const options = {
103
+ ...constants_1.GOOGLE_TRENDS_MAPPER[enums_1.GoogleTrendsEndpoints.explore],
104
+ qs: {
105
+ hl,
106
+ tz: '240',
107
+ req: JSON.stringify({
108
+ comparisonItem: [
109
+ {
110
+ keyword,
111
+ geo,
112
+ time,
113
+ },
114
+ ],
115
+ category,
116
+ property,
117
+ }),
118
+ },
119
+ contentType: 'form'
120
+ };
121
+ try {
122
+ const response = await (0, request_1.request)(options.url, options);
123
+ const text = await response.text();
124
+ // Remove the first 5 characters (JSONP wrapper) and parse
125
+ const data = JSON.parse(text.slice(5));
126
+ return data;
127
+ }
128
+ catch (error) {
129
+ console.error('Explore request failed:', error);
130
+ return { widgets: [] };
131
+ }
132
+ }
133
+ //
134
+ async interestByRegion({ keyword, startTime = new Date('2004-01-01'), endTime = new Date(), geo = 'US', resolution = 'REGION', hl = 'en-US', timezone = new Date().getTimezoneOffset(), category = 0 }) {
135
+ const formatDate = (date) => {
136
+ return date.toISOString().split('T')[0];
137
+ };
138
+ const formatTrendsDate = (date) => {
139
+ const pad = (n) => n.toString().padStart(2, '0');
140
+ const yyyy = date.getFullYear();
141
+ const mm = pad(date.getMonth() + 1);
142
+ const dd = pad(date.getDate());
143
+ const hh = pad(date.getHours());
144
+ const min = pad(date.getMinutes());
145
+ const ss = pad(date.getSeconds());
146
+ return `${yyyy}-${mm}-${dd}T${hh}\\:${min}\\:${ss}`;
147
+ };
148
+ const getDateRangeParam = (date) => {
149
+ const yesterday = new Date(date);
150
+ yesterday.setDate(date.getDate() - 1);
151
+ const formattedStart = formatTrendsDate(yesterday);
152
+ const formattedEnd = formatTrendsDate(date);
153
+ return `${formattedStart} ${formattedEnd}`;
154
+ };
155
+ const exploreResponse = await this.explore({
156
+ keyword: Array.isArray(keyword) ? keyword[0] : keyword,
157
+ geo: Array.isArray(geo) ? geo[0] : geo,
158
+ time: `${getDateRangeParam(startTime)} ${getDateRangeParam(endTime)}`,
159
+ category,
160
+ hl
161
+ });
162
+ const widget = exploreResponse.widgets.find(w => w.id === 'GEO_MAP');
163
+ if (!widget) {
164
+ return { default: { geoMapData: [] } };
165
+ }
166
+ const options = {
167
+ ...constants_1.GOOGLE_TRENDS_MAPPER[enums_1.GoogleTrendsEndpoints.interestByRegion],
168
+ qs: {
169
+ hl,
170
+ tz: timezone.toString(),
171
+ req: JSON.stringify({
172
+ geo: {
173
+ country: Array.isArray(geo) ? geo[0] : geo
174
+ },
175
+ comparisonItem: [{
176
+ time: `${formatDate(startTime)} ${formatDate(endTime)}`,
177
+ complexKeywordsRestriction: {
178
+ keyword: [{
179
+ type: 'BROAD',
180
+ value: Array.isArray(keyword) ? keyword[0] : keyword
181
+ }]
182
+ }
183
+ }],
184
+ resolution,
185
+ locale: hl,
186
+ requestOptions: {
187
+ property: '',
188
+ backend: 'CM',
189
+ category
190
+ },
191
+ userConfig: {
192
+ userType: 'USER_TYPE_LEGIT_USER'
193
+ }
194
+ }),
195
+ token: widget.token
196
+ }
197
+ };
198
+ try {
199
+ const response = await (0, request_1.request)(options.url, options);
200
+ const text = await response.text();
201
+ // Remove the first 5 characters (JSONP wrapper) and parse
202
+ const data = JSON.parse(text.slice(5));
203
+ return data;
204
+ }
205
+ catch (error) {
206
+ return { default: { geoMapData: [] } };
207
+ }
208
+ }
209
+ }
210
+ exports.GoogleTrendsApi = GoogleTrendsApi;
211
+ exports.default = new GoogleTrendsApi();
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -29,7 +20,7 @@ function rereq(options, body) {
29
20
  req.end();
30
21
  });
31
22
  }
32
- const request = (url, options) => __awaiter(void 0, void 0, void 0, function* () {
23
+ const request = async (url, options) => {
33
24
  const parsedUrl = new URL(url);
34
25
  const method = options.method || 'POST';
35
26
  // Prepare body
@@ -49,20 +40,25 @@ const request = (url, options) => __awaiter(void 0, void 0, void 0, function* ()
49
40
  port: parsedUrl.port || 443,
50
41
  path: `${parsedUrl.pathname}${options.qs ? '?' + querystring_1.default.stringify(options.qs) : ''}`,
51
42
  method,
52
- headers: Object.assign(Object.assign(Object.assign(Object.assign({}, (options.headers || {})), (contentType === 'form'
53
- ? { 'Content-Type': 'application/x-www-form-urlencoded' }
54
- : { 'Content-Type': 'application/json' })), (bodyString ? { 'Content-Length': Buffer.byteLength(bodyString).toString() } : {})), (cookieVal ? { cookie: cookieVal } : {}))
43
+ headers: {
44
+ ...(options.headers || {}),
45
+ ...(contentType === 'form'
46
+ ? { 'Content-Type': 'application/x-www-form-urlencoded' }
47
+ : { 'Content-Type': 'application/json' }),
48
+ ...(bodyString ? { 'Content-Length': Buffer.byteLength(bodyString).toString() } : {}),
49
+ ...(cookieVal ? { cookie: cookieVal } : {})
50
+ }
55
51
  };
56
- const response = yield new Promise((resolve, reject) => {
52
+ const response = await new Promise((resolve, reject) => {
57
53
  const req = https_1.default.request(requestOptions, (res) => {
58
54
  let chunk = '';
59
55
  res.on('data', (data) => { chunk += data; });
60
- res.on('end', () => __awaiter(void 0, void 0, void 0, function* () {
56
+ res.on('end', async () => {
61
57
  if (res.statusCode === 429 && res.headers['set-cookie']) {
62
58
  cookieVal = res.headers['set-cookie'][0].split(';')[0];
63
59
  requestOptions.headers['cookie'] = cookieVal;
64
60
  try {
65
- const retryResponse = yield rereq(requestOptions, bodyString);
61
+ const retryResponse = await rereq(requestOptions, bodyString);
66
62
  resolve(retryResponse);
67
63
  }
68
64
  catch (err) {
@@ -72,7 +68,7 @@ const request = (url, options) => __awaiter(void 0, void 0, void 0, function* ()
72
68
  else {
73
69
  resolve(chunk);
74
70
  }
75
- }));
71
+ });
76
72
  });
77
73
  req.on('error', reject);
78
74
  if (bodyString)
@@ -82,5 +78,5 @@ const request = (url, options) => __awaiter(void 0, void 0, void 0, function* ()
82
78
  return {
83
79
  text: () => Promise.resolve(response)
84
80
  };
85
- });
81
+ };
86
82
  exports.request = request;
@@ -0,0 +1,9 @@
1
+ export declare const dailyTrends: ({ geo, lang }: import("./types").DailyTrendingTopicsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
2
+ export declare const realTimeTrends: ({ geo, trendingHours }: import("./types").RealTimeTrendsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
3
+ export declare const autocomplete: (keyword: string, hl?: string) => Promise<import("./types").GoogleTrendsResponse<string[]>>;
4
+ declare const _default: {
5
+ dailyTrends: ({ geo, lang }: import("./types").DailyTrendingTopicsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
6
+ realTimeTrends: ({ geo, trendingHours }: import("./types").RealTimeTrendsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
7
+ autocomplete: (keyword: string, hl?: string) => Promise<import("./types").GoogleTrendsResponse<string[]>>;
8
+ };
9
+ export default _default;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.autocomplete = exports.realTimeTrends = exports.dailyTrends = void 0;
4
+ const googleTrendsAPI_1 = require("./helpers/googleTrendsAPI");
5
+ const api = new googleTrendsAPI_1.GoogleTrendsApi();
6
+ exports.dailyTrends = api.dailyTrends.bind(api);
7
+ exports.realTimeTrends = api.realTimeTrends.bind(api);
8
+ exports.autocomplete = api.autocomplete.bind(api);
9
+ // Default export for CommonJS compatibility
10
+ exports.default = {
11
+ dailyTrends: exports.dailyTrends,
12
+ realTimeTrends: exports.realTimeTrends,
13
+ autocomplete: exports.autocomplete
14
+ };
@@ -0,0 +1,12 @@
1
+ export declare enum GoogleTrendsEndpoints {
2
+ dailyTrends = "dailyTrends",
3
+ autocomplete = "autocomplete",
4
+ explore = "explore",
5
+ interestByRegion = "interestByRegion"
6
+ }
7
+ export declare enum GoogleTrendsTrendingHours {
8
+ fourHrs = 4,
9
+ oneDay = 24,
10
+ twoDays = 48,
11
+ sevenDays = 168
12
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GoogleTrendsTrendingHours = exports.GoogleTrendsEndpoints = void 0;
4
+ var GoogleTrendsEndpoints;
5
+ (function (GoogleTrendsEndpoints) {
6
+ GoogleTrendsEndpoints["dailyTrends"] = "dailyTrends";
7
+ GoogleTrendsEndpoints["autocomplete"] = "autocomplete";
8
+ GoogleTrendsEndpoints["explore"] = "explore";
9
+ GoogleTrendsEndpoints["interestByRegion"] = "interestByRegion";
10
+ })(GoogleTrendsEndpoints = exports.GoogleTrendsEndpoints || (exports.GoogleTrendsEndpoints = {}));
11
+ var GoogleTrendsTrendingHours;
12
+ (function (GoogleTrendsTrendingHours) {
13
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["fourHrs"] = 4] = "fourHrs";
14
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["oneDay"] = 24] = "oneDay";
15
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["twoDays"] = 48] = "twoDays";
16
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["sevenDays"] = 168] = "sevenDays";
17
+ })(GoogleTrendsTrendingHours = exports.GoogleTrendsTrendingHours || (exports.GoogleTrendsTrendingHours = {}));
@@ -0,0 +1,3 @@
1
+ import { GoogleTrendsEndpoints } from './types/enums';
2
+ import { GoogleTrendsMapper } from './types';
3
+ export declare const GOOGLE_TRENDS_MAPPER: Record<GoogleTrendsEndpoints, GoogleTrendsMapper>;
@@ -0,0 +1,36 @@
1
+ import { GoogleTrendsEndpoints } from './types/enums';
2
+ const GOOGLE_TRENDS_BASE_URL = 'trends.google.com';
3
+ export const GOOGLE_TRENDS_MAPPER = {
4
+ [GoogleTrendsEndpoints.dailyTrends]: {
5
+ path: '/_/TrendsUi/data/batchexecute',
6
+ method: 'POST',
7
+ host: GOOGLE_TRENDS_BASE_URL,
8
+ url: `https://${GOOGLE_TRENDS_BASE_URL}/_/TrendsUi/data/batchexecute`,
9
+ headers: {
10
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
11
+ },
12
+ },
13
+ [GoogleTrendsEndpoints.autocomplete]: {
14
+ path: '/trends/api/autocomplete',
15
+ method: 'GET',
16
+ host: GOOGLE_TRENDS_BASE_URL,
17
+ url: `https://${GOOGLE_TRENDS_BASE_URL}/trends/api/autocomplete`,
18
+ headers: {
19
+ accept: 'application/json, text/plain, */*',
20
+ },
21
+ },
22
+ [GoogleTrendsEndpoints.explore]: {
23
+ path: '/trends/api/explore',
24
+ method: 'POST',
25
+ host: GOOGLE_TRENDS_BASE_URL,
26
+ url: `https://${GOOGLE_TRENDS_BASE_URL}/trends/api/explore`,
27
+ headers: {},
28
+ },
29
+ [GoogleTrendsEndpoints.interestByRegion]: {
30
+ path: '/trends/api/widgetdata/comparedgeo',
31
+ method: 'GET',
32
+ host: GOOGLE_TRENDS_BASE_URL,
33
+ url: `https://${GOOGLE_TRENDS_BASE_URL}/trends/api/widgetdata/comparedgeo`,
34
+ headers: {},
35
+ },
36
+ };
@@ -0,0 +1,23 @@
1
+ import { GoogleTrendsError } from '../types';
2
+ export declare class RateLimitError extends Error implements GoogleTrendsError {
3
+ code: string;
4
+ statusCode: number;
5
+ constructor(message?: string);
6
+ }
7
+ export declare class InvalidRequestError extends Error implements GoogleTrendsError {
8
+ code: string;
9
+ statusCode: number;
10
+ constructor(message?: string);
11
+ }
12
+ export declare class NetworkError extends Error implements GoogleTrendsError {
13
+ code: string;
14
+ constructor(message?: string);
15
+ }
16
+ export declare class ParseError extends Error implements GoogleTrendsError {
17
+ code: string;
18
+ constructor(message?: string);
19
+ }
20
+ export declare class UnknownError extends Error implements GoogleTrendsError {
21
+ code: string;
22
+ constructor(message?: string);
23
+ }
@@ -0,0 +1,37 @@
1
+ export class RateLimitError extends Error {
2
+ constructor(message = 'Rate limit exceeded') {
3
+ super(message);
4
+ this.code = 'RATE_LIMIT_EXCEEDED';
5
+ this.statusCode = 429;
6
+ this.name = 'RateLimitError';
7
+ }
8
+ }
9
+ export class InvalidRequestError extends Error {
10
+ constructor(message = 'Invalid request parameters') {
11
+ super(message);
12
+ this.code = 'INVALID_REQUEST';
13
+ this.statusCode = 400;
14
+ this.name = 'InvalidRequestError';
15
+ }
16
+ }
17
+ export class NetworkError extends Error {
18
+ constructor(message = 'Network request failed') {
19
+ super(message);
20
+ this.code = 'NETWORK_ERROR';
21
+ this.name = 'NetworkError';
22
+ }
23
+ }
24
+ export class ParseError extends Error {
25
+ constructor(message = 'Failed to parse response') {
26
+ super(message);
27
+ this.code = 'PARSE_ERROR';
28
+ this.name = 'ParseError';
29
+ }
30
+ }
31
+ export class UnknownError extends Error {
32
+ constructor(message = 'An unknown error occurred') {
33
+ super(message);
34
+ this.code = 'UNKNOWN_ERROR';
35
+ this.name = 'UnknownError';
36
+ }
37
+ }
@@ -0,0 +1,2 @@
1
+ import { DailyTrendingTopics } from '../types';
2
+ export declare const extractJsonFromResponse: (text: string) => DailyTrendingTopics | null;
@@ -0,0 +1,76 @@
1
+ import { ParseError } from '../errors/GoogleTrendsError';
2
+ // For future refrence and update: from google trends page rpc call response,
3
+ // 0 "twitter down" The main trending search term.
4
+ // 1 null Unused (reserved for future Google Trends data).
5
+ // 2 "US" Country code (where the trend is happening).
6
+ // 3 [1741599600] Unix timestamp (represents when the search started trending).
7
+ // 4 null Unused (reserved for future data).
8
+ // 5 null Unused (reserved for future data).
9
+ // 6 500000 Search volume index (estimated search interest for the term).
10
+ // 7 null Unused (reserved for future data).
11
+ // 8 1000 Trend ranking score (higher means more popular).
12
+ // 9 ["twitter down", "is twitter down", "is x down", ...] Related searches (other queries that users searched alongside this term).
13
+ // 10 [11] Unclear, possibly a category identifier.
14
+ // 11 [[3606769742, "en", "US"], [3596035008, "en", "US"]] User demographics or trending sources, with numerical IDs, language ("en" for English), and country ("US" for United States).
15
+ // 12 "twitter down" The original trending keyword (sometimes a duplicate of index 0).
16
+ export const extractJsonFromResponse = (text) => {
17
+ const cleanedText = text.replace(/^\)\]\}'/, '').trim();
18
+ try {
19
+ const parsedResponse = JSON.parse(cleanedText);
20
+ if (!Array.isArray(parsedResponse) || parsedResponse.length === 0) {
21
+ throw new ParseError('Invalid response format: empty array');
22
+ }
23
+ const nestedJsonString = parsedResponse[0][2];
24
+ if (!nestedJsonString) {
25
+ throw new ParseError('Invalid response format: missing nested JSON');
26
+ }
27
+ const data = JSON.parse(nestedJsonString);
28
+ if (!data || !Array.isArray(data) || data.length < 2) {
29
+ throw new ParseError('Invalid response format: missing data array');
30
+ }
31
+ return updateResponseObject(data[1]);
32
+ }
33
+ catch (e) {
34
+ if (e instanceof ParseError) {
35
+ throw e;
36
+ }
37
+ throw new ParseError('Failed to parse response');
38
+ }
39
+ };
40
+ const updateResponseObject = (data) => {
41
+ if (!Array.isArray(data)) {
42
+ throw new ParseError('Invalid data format: expected array');
43
+ }
44
+ const allTrendingStories = [];
45
+ const summary = [];
46
+ data.forEach((item) => {
47
+ if (Array.isArray(item)) {
48
+ const story = {
49
+ title: String(item[0] || ''),
50
+ traffic: String(item[6] || '0'),
51
+ articles: Array.isArray(item[9]) ? item[9].map((article) => ({
52
+ title: String(article[0] || ''),
53
+ url: String(article[1] || ''),
54
+ source: String(article[2] || ''),
55
+ time: String(article[3] || ''),
56
+ snippet: String(article[4] || '')
57
+ })) : [],
58
+ shareUrl: String(item[12] || '')
59
+ };
60
+ if (item[1]) {
61
+ story.image = {
62
+ newsUrl: String(item[1][0] || ''),
63
+ source: String(item[1][1] || ''),
64
+ imageUrl: String(item[1][2] || '')
65
+ };
66
+ }
67
+ allTrendingStories.push(story);
68
+ summary.push({
69
+ title: story.title,
70
+ traffic: story.traffic,
71
+ articles: story.articles
72
+ });
73
+ }
74
+ });
75
+ return { allTrendingStories, summary };
76
+ };
@@ -0,0 +1,26 @@
1
+ import { DailyTrendingTopics, DailyTrendingTopicsOptions, RealTimeTrendsOptions, ExploreOptions, ExploreResponse, InterestByRegionOptions, InterestByRegionResponse, GoogleTrendsResponse } from '../types/index';
2
+ export declare class GoogleTrendsApi {
3
+ /**
4
+ * Get autocomplete suggestions for a keyword
5
+ * @param keyword - The keyword to get suggestions for
6
+ * @param hl - Language code (default: 'en-US')
7
+ * @returns Promise with array of suggestion strings
8
+ */
9
+ autocomplete(keyword: string, hl?: string): Promise<GoogleTrendsResponse<string[]>>;
10
+ /**
11
+ * Get daily trending topics
12
+ * @param options - Options for daily trends request
13
+ * @returns Promise with trending topics data
14
+ */
15
+ dailyTrends({ geo, lang }: DailyTrendingTopicsOptions): Promise<GoogleTrendsResponse<DailyTrendingTopics>>;
16
+ /**
17
+ * Get real-time trending topics
18
+ * @param options - Options for real-time trends request
19
+ * @returns Promise with trending topics data
20
+ */
21
+ realTimeTrends({ geo, trendingHours }: RealTimeTrendsOptions): Promise<GoogleTrendsResponse<DailyTrendingTopics>>;
22
+ explore({ keyword, geo, time, category, property, hl, }: ExploreOptions): Promise<ExploreResponse>;
23
+ interestByRegion({ keyword, startTime, endTime, geo, resolution, hl, timezone, category }: InterestByRegionOptions): Promise<InterestByRegionResponse>;
24
+ }
25
+ declare const _default: GoogleTrendsApi;
26
+ export default _default;
@@ -0,0 +1,207 @@
1
+ import { GoogleTrendsEndpoints } from '../types/enums';
2
+ import { request } from './request';
3
+ import { extractJsonFromResponse } from './format';
4
+ import { GOOGLE_TRENDS_MAPPER } from '../constants';
5
+ import { NetworkError, ParseError, UnknownError, } from '../errors/GoogleTrendsError';
6
+ export class GoogleTrendsApi {
7
+ /**
8
+ * Get autocomplete suggestions for a keyword
9
+ * @param keyword - The keyword to get suggestions for
10
+ * @param hl - Language code (default: 'en-US')
11
+ * @returns Promise with array of suggestion strings
12
+ */
13
+ async autocomplete(keyword, hl = 'en-US') {
14
+ if (!keyword) {
15
+ return { data: [] };
16
+ }
17
+ const options = {
18
+ ...GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.autocomplete],
19
+ qs: {
20
+ hl,
21
+ tz: '240',
22
+ },
23
+ };
24
+ try {
25
+ const response = await request(`${options.url}/${encodeURIComponent(keyword)}`, options);
26
+ const text = await response.text();
27
+ // Remove the first 5 characters (JSONP wrapper) and parse
28
+ const data = JSON.parse(text.slice(5));
29
+ return { data: data.default.topics.map((topic) => topic.title) };
30
+ }
31
+ catch (error) {
32
+ if (error instanceof Error) {
33
+ return { error: new NetworkError(error.message) };
34
+ }
35
+ return { error: new UnknownError() };
36
+ }
37
+ }
38
+ /**
39
+ * Get daily trending topics
40
+ * @param options - Options for daily trends request
41
+ * @returns Promise with trending topics data
42
+ */
43
+ async dailyTrends({ geo = 'US', lang = 'en' }) {
44
+ const defaultOptions = GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.dailyTrends];
45
+ const options = {
46
+ ...defaultOptions,
47
+ body: new URLSearchParams({
48
+ 'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"${lang}\\",24,1]",null,"generic"]]]`,
49
+ }).toString(),
50
+ contentType: 'form'
51
+ };
52
+ try {
53
+ const response = await request(options.url, options);
54
+ const text = await response.text();
55
+ const trendingTopics = extractJsonFromResponse(text);
56
+ if (!trendingTopics) {
57
+ return { error: new ParseError() };
58
+ }
59
+ return { data: trendingTopics };
60
+ }
61
+ catch (error) {
62
+ if (error instanceof Error) {
63
+ return { error: new NetworkError(error.message) };
64
+ }
65
+ return { error: new UnknownError() };
66
+ }
67
+ }
68
+ /**
69
+ * Get real-time trending topics
70
+ * @param options - Options for real-time trends request
71
+ * @returns Promise with trending topics data
72
+ */
73
+ async realTimeTrends({ geo = 'US', trendingHours = 4 }) {
74
+ const defaultOptions = GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.dailyTrends];
75
+ const options = {
76
+ ...defaultOptions,
77
+ body: new URLSearchParams({
78
+ 'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"en\\",${trendingHours},1]",null,"generic"]]]`,
79
+ }).toString(),
80
+ contentType: 'form'
81
+ };
82
+ try {
83
+ const response = await request(options.url, options);
84
+ const text = await response.text();
85
+ const trendingTopics = extractJsonFromResponse(text);
86
+ if (!trendingTopics) {
87
+ return { error: new ParseError() };
88
+ }
89
+ return { data: trendingTopics };
90
+ }
91
+ catch (error) {
92
+ if (error instanceof Error) {
93
+ return { error: new NetworkError(error.message) };
94
+ }
95
+ return { error: new UnknownError() };
96
+ }
97
+ }
98
+ async explore({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
99
+ const options = {
100
+ ...GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.explore],
101
+ qs: {
102
+ hl,
103
+ tz: '240',
104
+ req: JSON.stringify({
105
+ comparisonItem: [
106
+ {
107
+ keyword,
108
+ geo,
109
+ time,
110
+ },
111
+ ],
112
+ category,
113
+ property,
114
+ }),
115
+ },
116
+ contentType: 'form'
117
+ };
118
+ try {
119
+ const response = await request(options.url, options);
120
+ const text = await response.text();
121
+ // Remove the first 5 characters (JSONP wrapper) and parse
122
+ const data = JSON.parse(text.slice(5));
123
+ return data;
124
+ }
125
+ catch (error) {
126
+ console.error('Explore request failed:', error);
127
+ return { widgets: [] };
128
+ }
129
+ }
130
+ //
131
+ async interestByRegion({ keyword, startTime = new Date('2004-01-01'), endTime = new Date(), geo = 'US', resolution = 'REGION', hl = 'en-US', timezone = new Date().getTimezoneOffset(), category = 0 }) {
132
+ const formatDate = (date) => {
133
+ return date.toISOString().split('T')[0];
134
+ };
135
+ const formatTrendsDate = (date) => {
136
+ const pad = (n) => n.toString().padStart(2, '0');
137
+ const yyyy = date.getFullYear();
138
+ const mm = pad(date.getMonth() + 1);
139
+ const dd = pad(date.getDate());
140
+ const hh = pad(date.getHours());
141
+ const min = pad(date.getMinutes());
142
+ const ss = pad(date.getSeconds());
143
+ return `${yyyy}-${mm}-${dd}T${hh}\\:${min}\\:${ss}`;
144
+ };
145
+ const getDateRangeParam = (date) => {
146
+ const yesterday = new Date(date);
147
+ yesterday.setDate(date.getDate() - 1);
148
+ const formattedStart = formatTrendsDate(yesterday);
149
+ const formattedEnd = formatTrendsDate(date);
150
+ return `${formattedStart} ${formattedEnd}`;
151
+ };
152
+ const exploreResponse = await this.explore({
153
+ keyword: Array.isArray(keyword) ? keyword[0] : keyword,
154
+ geo: Array.isArray(geo) ? geo[0] : geo,
155
+ time: `${getDateRangeParam(startTime)} ${getDateRangeParam(endTime)}`,
156
+ category,
157
+ hl
158
+ });
159
+ const widget = exploreResponse.widgets.find(w => w.id === 'GEO_MAP');
160
+ if (!widget) {
161
+ return { default: { geoMapData: [] } };
162
+ }
163
+ const options = {
164
+ ...GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.interestByRegion],
165
+ qs: {
166
+ hl,
167
+ tz: timezone.toString(),
168
+ req: JSON.stringify({
169
+ geo: {
170
+ country: Array.isArray(geo) ? geo[0] : geo
171
+ },
172
+ comparisonItem: [{
173
+ time: `${formatDate(startTime)} ${formatDate(endTime)}`,
174
+ complexKeywordsRestriction: {
175
+ keyword: [{
176
+ type: 'BROAD',
177
+ value: Array.isArray(keyword) ? keyword[0] : keyword
178
+ }]
179
+ }
180
+ }],
181
+ resolution,
182
+ locale: hl,
183
+ requestOptions: {
184
+ property: '',
185
+ backend: 'CM',
186
+ category
187
+ },
188
+ userConfig: {
189
+ userType: 'USER_TYPE_LEGIT_USER'
190
+ }
191
+ }),
192
+ token: widget.token
193
+ }
194
+ };
195
+ try {
196
+ const response = await request(options.url, options);
197
+ const text = await response.text();
198
+ // Remove the first 5 characters (JSONP wrapper) and parse
199
+ const data = JSON.parse(text.slice(5));
200
+ return data;
201
+ }
202
+ catch (error) {
203
+ return { default: { geoMapData: [] } };
204
+ }
205
+ }
206
+ }
207
+ export default new GoogleTrendsApi();
@@ -0,0 +1,9 @@
1
+ export declare const request: (url: string, options: {
2
+ method?: string;
3
+ qs?: Record<string, any>;
4
+ body?: string | Record<string, any>;
5
+ headers?: Record<string, string>;
6
+ contentType?: 'json' | 'form';
7
+ }) => Promise<{
8
+ text: () => Promise<string>;
9
+ }>;
@@ -0,0 +1,75 @@
1
+ import https from 'https';
2
+ import querystring from 'querystring';
3
+ let cookieVal;
4
+ function rereq(options, body) {
5
+ return new Promise((resolve, reject) => {
6
+ const req = https.request(options, (res) => {
7
+ let chunk = '';
8
+ res.on('data', (data) => { chunk += data; });
9
+ res.on('end', () => resolve(chunk));
10
+ });
11
+ req.on('error', reject);
12
+ if (body)
13
+ req.write(body);
14
+ req.end();
15
+ });
16
+ }
17
+ export const request = async (url, options) => {
18
+ const parsedUrl = new URL(url);
19
+ const method = options.method || 'POST';
20
+ // Prepare body
21
+ let bodyString = '';
22
+ const contentType = options.contentType || 'json';
23
+ if (typeof options.body === 'string') {
24
+ bodyString = options.body;
25
+ }
26
+ else if (contentType === 'form') {
27
+ bodyString = querystring.stringify(options.body || {});
28
+ }
29
+ else if (options.body) {
30
+ bodyString = JSON.stringify(options.body);
31
+ }
32
+ const requestOptions = {
33
+ hostname: parsedUrl.hostname,
34
+ port: parsedUrl.port || 443,
35
+ path: `${parsedUrl.pathname}${options.qs ? '?' + querystring.stringify(options.qs) : ''}`,
36
+ method,
37
+ headers: {
38
+ ...(options.headers || {}),
39
+ ...(contentType === 'form'
40
+ ? { 'Content-Type': 'application/x-www-form-urlencoded' }
41
+ : { 'Content-Type': 'application/json' }),
42
+ ...(bodyString ? { 'Content-Length': Buffer.byteLength(bodyString).toString() } : {}),
43
+ ...(cookieVal ? { cookie: cookieVal } : {})
44
+ }
45
+ };
46
+ const response = await new Promise((resolve, reject) => {
47
+ const req = https.request(requestOptions, (res) => {
48
+ let chunk = '';
49
+ res.on('data', (data) => { chunk += data; });
50
+ res.on('end', async () => {
51
+ if (res.statusCode === 429 && res.headers['set-cookie']) {
52
+ cookieVal = res.headers['set-cookie'][0].split(';')[0];
53
+ requestOptions.headers['cookie'] = cookieVal;
54
+ try {
55
+ const retryResponse = await rereq(requestOptions, bodyString);
56
+ resolve(retryResponse);
57
+ }
58
+ catch (err) {
59
+ reject(err);
60
+ }
61
+ }
62
+ else {
63
+ resolve(chunk);
64
+ }
65
+ });
66
+ });
67
+ req.on('error', reject);
68
+ if (bodyString)
69
+ req.write(bodyString);
70
+ req.end();
71
+ });
72
+ return {
73
+ text: () => Promise.resolve(response)
74
+ };
75
+ };
@@ -0,0 +1,9 @@
1
+ export declare const dailyTrends: ({ geo, lang }: import("./types").DailyTrendingTopicsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
2
+ export declare const realTimeTrends: ({ geo, trendingHours }: import("./types").RealTimeTrendsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
3
+ export declare const autocomplete: (keyword: string, hl?: string) => Promise<import("./types").GoogleTrendsResponse<string[]>>;
4
+ declare const _default: {
5
+ dailyTrends: ({ geo, lang }: import("./types").DailyTrendingTopicsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
6
+ realTimeTrends: ({ geo, trendingHours }: import("./types").RealTimeTrendsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
7
+ autocomplete: (keyword: string, hl?: string) => Promise<import("./types").GoogleTrendsResponse<string[]>>;
8
+ };
9
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import { GoogleTrendsApi } from './helpers/googleTrendsAPI';
2
+ const api = new GoogleTrendsApi();
3
+ export const dailyTrends = api.dailyTrends.bind(api);
4
+ export const realTimeTrends = api.realTimeTrends.bind(api);
5
+ export const autocomplete = api.autocomplete.bind(api);
6
+ // Default export for CommonJS compatibility
7
+ export default {
8
+ dailyTrends,
9
+ realTimeTrends,
10
+ autocomplete
11
+ };
@@ -0,0 +1,12 @@
1
+ export declare enum GoogleTrendsEndpoints {
2
+ dailyTrends = "dailyTrends",
3
+ autocomplete = "autocomplete",
4
+ explore = "explore",
5
+ interestByRegion = "interestByRegion"
6
+ }
7
+ export declare enum GoogleTrendsTrendingHours {
8
+ fourHrs = 4,
9
+ oneDay = 24,
10
+ twoDays = 48,
11
+ sevenDays = 168
12
+ }
@@ -0,0 +1,14 @@
1
+ export var GoogleTrendsEndpoints;
2
+ (function (GoogleTrendsEndpoints) {
3
+ GoogleTrendsEndpoints["dailyTrends"] = "dailyTrends";
4
+ GoogleTrendsEndpoints["autocomplete"] = "autocomplete";
5
+ GoogleTrendsEndpoints["explore"] = "explore";
6
+ GoogleTrendsEndpoints["interestByRegion"] = "interestByRegion";
7
+ })(GoogleTrendsEndpoints || (GoogleTrendsEndpoints = {}));
8
+ export var GoogleTrendsTrendingHours;
9
+ (function (GoogleTrendsTrendingHours) {
10
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["fourHrs"] = 4] = "fourHrs";
11
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["oneDay"] = 24] = "oneDay";
12
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["twoDays"] = 48] = "twoDays";
13
+ GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["sevenDays"] = 168] = "sevenDays";
14
+ })(GoogleTrendsTrendingHours || (GoogleTrendsTrendingHours = {}));
package/package.json CHANGED
@@ -1,49 +1,43 @@
1
1
  {
2
2
  "name": "@shaivpidadi/trends-js",
3
- "version": "0.0.0-beta.6",
3
+ "version": "0.0.0-beta.7",
4
4
  "description": "Google Trends API for Node.js",
5
- "main": "lib/index.js",
6
- "types": "lib/index.d.ts",
5
+ "main": "./dist/cjs/index.js",
6
+ "module": "./dist/esm/index.js",
7
+ "types": "./dist/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/esm/index.js",
11
+ "require": "./dist/cjs/index.js",
12
+ "types": "./dist/types/index.d.ts"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
7
18
  "scripts": {
8
- "build": "tsc",
9
- "format": "prettier --write \"src/**/*.(js|ts)\"",
10
- "lint": "eslint src --ext .js,.ts",
11
- "lint:fix": "eslint src --fix --ext .js,.ts",
12
- "test": "jest --config jest.config.js",
13
- "prepare": "npm run build",
14
- "prepublishOnly": "npm test && npm run lint",
15
- "preversion": "npm run lint",
16
- "version": "npm run format && git add -A src",
17
- "postversion": "git push && git push --tags"
19
+ "build": "npm run build:esm && npm run build:cjs",
20
+ "build:esm": "tsc -p tsconfig.json --outDir dist/esm",
21
+ "build:cjs": "tsc -p tsconfig.json --outDir dist/cjs --module commonjs",
22
+ "test": "jest",
23
+ "prepare": "npm run build"
18
24
  },
19
25
  "repository": {
20
26
  "type": "git",
21
27
  "url": "git+https://github.com/Shaivpidadi/trends-js.git"
22
28
  },
23
29
  "keywords": [
24
- "boilerplate",
25
- "typescript",
26
- "npm",
27
- "module"
30
+ "google-trends",
31
+ "api",
32
+ "typescript"
28
33
  ],
29
- "author": "Shaishav Pidadi",
30
- "private": false,
31
- "publishConfig": {
32
- "access": "public"
33
- },
34
+ "author": "",
34
35
  "license": "MIT",
35
36
  "devDependencies": {
36
- "@types/jest": "29.5.14",
37
- "@typescript-eslint/eslint-plugin": "5.62.0",
38
- "@typescript-eslint/parser": "5.62.0",
39
- "eslint": "8.57.1",
40
- "eslint-plugin-jest": "27.9.0",
41
- "jest": "29.7.0",
42
- "prettier": "2.8.8",
43
- "ts-jest": "29.2.5",
44
- "typescript": "4.9.5"
45
- },
46
- "files": [
47
- "lib/**/*"
48
- ]
49
- }
37
+ "@types/jest": "^29.5.0",
38
+ "@types/node": "^20.0.0",
39
+ "jest": "^29.5.0",
40
+ "ts-jest": "^29.1.0",
41
+ "typescript": "^5.0.0"
42
+ }
43
+ }
@@ -1,2 +0,0 @@
1
- import { GoogleTrendsEndpoints, GoogleTrendsMapper } from './types';
2
- export declare const GOOGLE_TRENDS_MAPPER: Record<GoogleTrendsEndpoints, GoogleTrendsMapper>;
@@ -1,211 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.GoogleTrendsApi = void 0;
13
- const request_1 = require("./request");
14
- const format_1 = require("./format");
15
- const constants_1 = require("../constants");
16
- const GoogleTrendsError_1 = require("../errors/GoogleTrendsError");
17
- class GoogleTrendsApi {
18
- /**
19
- * Get autocomplete suggestions for a keyword
20
- * @param keyword - The keyword to get suggestions for
21
- * @param hl - Language code (default: 'en-US')
22
- * @returns Promise with array of suggestion strings
23
- */
24
- autocomplete(keyword, hl = 'en-US') {
25
- return __awaiter(this, void 0, void 0, function* () {
26
- if (!keyword) {
27
- return { data: [] };
28
- }
29
- const options = Object.assign(Object.assign({}, constants_1.GOOGLE_TRENDS_MAPPER["autocomplete" /* GoogleTrendsEndpoints.autocomplete */]), { qs: {
30
- hl,
31
- tz: '240',
32
- } });
33
- try {
34
- const response = yield (0, request_1.request)(`${options.url}/${encodeURIComponent(keyword)}`, options);
35
- const text = yield response.text();
36
- // Remove the first 5 characters (JSONP wrapper) and parse
37
- const data = JSON.parse(text.slice(5));
38
- return { data: data.default.topics.map((topic) => topic.title) };
39
- }
40
- catch (error) {
41
- if (error instanceof Error) {
42
- return { error: new GoogleTrendsError_1.NetworkError(error.message) };
43
- }
44
- return { error: new GoogleTrendsError_1.UnknownError() };
45
- }
46
- });
47
- }
48
- /**
49
- * Get daily trending topics
50
- * @param options - Options for daily trends request
51
- * @returns Promise with trending topics data
52
- */
53
- dailyTrends({ geo = 'US', lang = 'en' }) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- const defaultOptions = constants_1.GOOGLE_TRENDS_MAPPER["dailyTrends" /* GoogleTrendsEndpoints.dailyTrends */];
56
- const options = Object.assign(Object.assign({}, defaultOptions), { body: new URLSearchParams({
57
- 'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"${lang}\\",24,1]",null,"generic"]]]`,
58
- }).toString(), contentType: 'form' });
59
- try {
60
- const response = yield (0, request_1.request)(options.url, options);
61
- const text = yield response.text();
62
- const trendingTopics = (0, format_1.extractJsonFromResponse)(text);
63
- if (!trendingTopics) {
64
- return { error: new GoogleTrendsError_1.ParseError() };
65
- }
66
- return { data: trendingTopics };
67
- }
68
- catch (error) {
69
- if (error instanceof Error) {
70
- return { error: new GoogleTrendsError_1.NetworkError(error.message) };
71
- }
72
- return { error: new GoogleTrendsError_1.UnknownError() };
73
- }
74
- });
75
- }
76
- /**
77
- * Get real-time trending topics
78
- * @param options - Options for real-time trends request
79
- * @returns Promise with trending topics data
80
- */
81
- realTimeTrends({ geo = 'US', trendingHours = 4 }) {
82
- return __awaiter(this, void 0, void 0, function* () {
83
- const defaultOptions = constants_1.GOOGLE_TRENDS_MAPPER["dailyTrends" /* GoogleTrendsEndpoints.dailyTrends */];
84
- const options = Object.assign(Object.assign({}, defaultOptions), { body: new URLSearchParams({
85
- 'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"en\\",${trendingHours},1]",null,"generic"]]]`,
86
- }).toString(), contentType: 'form' });
87
- try {
88
- const response = yield (0, request_1.request)(options.url, options);
89
- const text = yield response.text();
90
- const trendingTopics = (0, format_1.extractJsonFromResponse)(text);
91
- if (!trendingTopics) {
92
- return { error: new GoogleTrendsError_1.ParseError() };
93
- }
94
- return { data: trendingTopics };
95
- }
96
- catch (error) {
97
- if (error instanceof Error) {
98
- return { error: new GoogleTrendsError_1.NetworkError(error.message) };
99
- }
100
- return { error: new GoogleTrendsError_1.UnknownError() };
101
- }
102
- });
103
- }
104
- explore({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
105
- return __awaiter(this, void 0, void 0, function* () {
106
- const options = Object.assign(Object.assign({}, constants_1.GOOGLE_TRENDS_MAPPER["explore" /* GoogleTrendsEndpoints.explore */]), { qs: {
107
- hl,
108
- tz: '240',
109
- req: JSON.stringify({
110
- comparisonItem: [
111
- {
112
- keyword,
113
- geo,
114
- time,
115
- },
116
- ],
117
- category,
118
- property,
119
- }),
120
- }, contentType: 'form' });
121
- try {
122
- const response = yield (0, request_1.request)(options.url, options);
123
- const text = yield response.text();
124
- // Remove the first 5 characters (JSONP wrapper) and parse
125
- const data = JSON.parse(text.slice(5));
126
- return data;
127
- }
128
- catch (error) {
129
- console.error('Explore request failed:', error);
130
- return { widgets: [] };
131
- }
132
- });
133
- }
134
- //
135
- interestByRegion({ keyword, startTime = new Date('2004-01-01'), endTime = new Date(), geo = 'US', resolution = 'REGION', hl = 'en-US', timezone = new Date().getTimezoneOffset(), category = 0 }) {
136
- return __awaiter(this, void 0, void 0, function* () {
137
- const formatDate = (date) => {
138
- return date.toISOString().split('T')[0];
139
- };
140
- const formatTrendsDate = (date) => {
141
- const pad = (n) => n.toString().padStart(2, '0');
142
- const yyyy = date.getFullYear();
143
- const mm = pad(date.getMonth() + 1);
144
- const dd = pad(date.getDate());
145
- const hh = pad(date.getHours());
146
- const min = pad(date.getMinutes());
147
- const ss = pad(date.getSeconds());
148
- return `${yyyy}-${mm}-${dd}T${hh}\\:${min}\\:${ss}`;
149
- };
150
- const getDateRangeParam = (date) => {
151
- const yesterday = new Date(date);
152
- yesterday.setDate(date.getDate() - 1);
153
- const formattedStart = formatTrendsDate(yesterday);
154
- const formattedEnd = formatTrendsDate(date);
155
- return `${formattedStart} ${formattedEnd}`;
156
- };
157
- const exploreResponse = yield this.explore({
158
- keyword: Array.isArray(keyword) ? keyword[0] : keyword,
159
- geo: Array.isArray(geo) ? geo[0] : geo,
160
- time: `${getDateRangeParam(startTime)} ${getDateRangeParam(endTime)}`,
161
- category,
162
- hl
163
- });
164
- const widget = exploreResponse.widgets.find(w => w.id === 'GEO_MAP');
165
- if (!widget) {
166
- return { default: { geoMapData: [] } };
167
- }
168
- const options = Object.assign(Object.assign({}, constants_1.GOOGLE_TRENDS_MAPPER["interestByRegion" /* GoogleTrendsEndpoints.interestByRegion */]), { qs: {
169
- hl,
170
- tz: timezone.toString(),
171
- req: JSON.stringify({
172
- geo: {
173
- country: Array.isArray(geo) ? geo[0] : geo
174
- },
175
- comparisonItem: [{
176
- time: `${formatDate(startTime)} ${formatDate(endTime)}`,
177
- complexKeywordsRestriction: {
178
- keyword: [{
179
- type: 'BROAD',
180
- value: Array.isArray(keyword) ? keyword[0] : keyword
181
- }]
182
- }
183
- }],
184
- resolution,
185
- locale: hl,
186
- requestOptions: {
187
- property: '',
188
- backend: 'CM',
189
- category
190
- },
191
- userConfig: {
192
- userType: 'USER_TYPE_LEGIT_USER'
193
- }
194
- }),
195
- token: widget.token
196
- } });
197
- try {
198
- const response = yield (0, request_1.request)(options.url, options);
199
- const text = yield response.text();
200
- // Remove the first 5 characters (JSONP wrapper) and parse
201
- const data = JSON.parse(text.slice(5));
202
- return data;
203
- }
204
- catch (error) {
205
- return { default: { geoMapData: [] } };
206
- }
207
- });
208
- }
209
- }
210
- exports.GoogleTrendsApi = GoogleTrendsApi;
211
- exports.default = new GoogleTrendsApi();
package/lib/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import GoogleTrendsApi from './helpers/googleTrendsAPI';
2
- export default GoogleTrendsApi;
package/lib/index.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const googleTrendsAPI_1 = __importDefault(require("./helpers/googleTrendsAPI"));
7
- exports.default = googleTrendsAPI_1.default;
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes