@graphext/cuery 0.9.5 → 0.10.1

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.
Files changed (85) hide show
  1. package/esm/browser.d.ts +1 -1
  2. package/esm/browser.js +1 -1
  3. package/esm/mod.d.ts +3 -3
  4. package/esm/mod.d.ts.map +1 -1
  5. package/esm/mod.js +3 -3
  6. package/esm/src/apis/brightdata/contentScraper/index.d.ts.map +1 -0
  7. package/{script/src/apis/brightdata → esm/src/apis/brightdata/contentScraper}/scrape.d.ts +1 -1
  8. package/esm/src/apis/brightdata/contentScraper/scrape.d.ts.map +1 -0
  9. package/esm/src/apis/brightdata/{scrape.js → contentScraper/scrape.js} +2 -2
  10. package/esm/src/apis/brightdata/llmScraper/brightdata.d.ts +20 -0
  11. package/esm/src/apis/brightdata/llmScraper/brightdata.d.ts.map +1 -0
  12. package/esm/src/apis/brightdata/llmScraper/brightdata.js +182 -0
  13. package/esm/src/apis/brightdata/llmScraper/index.d.ts +14 -0
  14. package/esm/src/apis/brightdata/llmScraper/index.d.ts.map +1 -0
  15. package/esm/src/apis/brightdata/llmScraper/index.js +97 -0
  16. package/esm/src/apis/brightdata/llmScraper/oxy.d.ts +16 -0
  17. package/esm/src/apis/brightdata/llmScraper/oxy.d.ts.map +1 -0
  18. package/esm/src/apis/brightdata/llmScraper/oxy.js +171 -0
  19. package/{script/src/apis/chatgptScraper/scraper.d.ts → esm/src/apis/brightdata/llmScraper/scrape.d.ts} +12 -15
  20. package/esm/src/apis/brightdata/llmScraper/scrape.d.ts.map +1 -0
  21. package/esm/src/apis/brightdata/llmScraper/scrape.js +184 -0
  22. package/esm/src/apis/hasdata/helpers.d.ts.map +1 -1
  23. package/esm/src/apis/hasdata/helpers.js +56 -18
  24. package/esm/src/schemas/search.schema.d.ts +2 -2
  25. package/esm/src/schemas/search.schema.d.ts.map +1 -1
  26. package/esm/src/schemas/sources.schema.d.ts +1 -4
  27. package/esm/src/schemas/sources.schema.d.ts.map +1 -1
  28. package/package.json +1 -1
  29. package/script/browser.d.ts +1 -1
  30. package/script/browser.js +1 -1
  31. package/script/mod.d.ts +3 -3
  32. package/script/mod.d.ts.map +1 -1
  33. package/script/mod.js +6 -6
  34. package/script/src/apis/brightdata/contentScraper/index.d.ts.map +1 -0
  35. package/{esm/src/apis/brightdata → script/src/apis/brightdata/contentScraper}/scrape.d.ts +1 -1
  36. package/script/src/apis/brightdata/contentScraper/scrape.d.ts.map +1 -0
  37. package/script/src/apis/brightdata/{scrape.js → contentScraper/scrape.js} +2 -2
  38. package/script/src/apis/brightdata/llmScraper/brightdata.d.ts +20 -0
  39. package/script/src/apis/brightdata/llmScraper/brightdata.d.ts.map +1 -0
  40. package/script/src/apis/brightdata/llmScraper/brightdata.js +219 -0
  41. package/script/src/apis/brightdata/llmScraper/index.d.ts +14 -0
  42. package/script/src/apis/brightdata/llmScraper/index.d.ts.map +1 -0
  43. package/script/src/apis/brightdata/llmScraper/index.js +140 -0
  44. package/script/src/apis/brightdata/llmScraper/oxy.d.ts +16 -0
  45. package/script/src/apis/brightdata/llmScraper/oxy.d.ts.map +1 -0
  46. package/script/src/apis/brightdata/llmScraper/oxy.js +208 -0
  47. package/{esm/src/apis/chatgptScraper/scraper.d.ts → script/src/apis/brightdata/llmScraper/scrape.d.ts} +12 -15
  48. package/script/src/apis/brightdata/llmScraper/scrape.d.ts.map +1 -0
  49. package/script/src/apis/brightdata/llmScraper/scrape.js +224 -0
  50. package/script/src/apis/hasdata/helpers.d.ts.map +1 -1
  51. package/script/src/apis/hasdata/helpers.js +56 -18
  52. package/script/src/schemas/search.schema.d.ts +2 -2
  53. package/script/src/schemas/search.schema.d.ts.map +1 -1
  54. package/script/src/schemas/sources.schema.d.ts +1 -4
  55. package/script/src/schemas/sources.schema.d.ts.map +1 -1
  56. package/esm/src/apis/brightdata/index.d.ts.map +0 -1
  57. package/esm/src/apis/brightdata/scrape.d.ts.map +0 -1
  58. package/esm/src/apis/chatgptScraper/brightdata.d.ts +0 -3
  59. package/esm/src/apis/chatgptScraper/brightdata.d.ts.map +0 -1
  60. package/esm/src/apis/chatgptScraper/brightdata.js +0 -172
  61. package/esm/src/apis/chatgptScraper/index.d.ts +0 -10
  62. package/esm/src/apis/chatgptScraper/index.d.ts.map +0 -1
  63. package/esm/src/apis/chatgptScraper/index.js +0 -41
  64. package/esm/src/apis/chatgptScraper/oxy.d.ts +0 -3
  65. package/esm/src/apis/chatgptScraper/oxy.d.ts.map +0 -1
  66. package/esm/src/apis/chatgptScraper/oxy.js +0 -156
  67. package/esm/src/apis/chatgptScraper/scraper.d.ts.map +0 -1
  68. package/esm/src/apis/chatgptScraper/scraper.js +0 -98
  69. package/script/src/apis/brightdata/index.d.ts.map +0 -1
  70. package/script/src/apis/brightdata/scrape.d.ts.map +0 -1
  71. package/script/src/apis/chatgptScraper/brightdata.d.ts +0 -3
  72. package/script/src/apis/chatgptScraper/brightdata.d.ts.map +0 -1
  73. package/script/src/apis/chatgptScraper/brightdata.js +0 -208
  74. package/script/src/apis/chatgptScraper/index.d.ts +0 -10
  75. package/script/src/apis/chatgptScraper/index.d.ts.map +0 -1
  76. package/script/src/apis/chatgptScraper/index.js +0 -81
  77. package/script/src/apis/chatgptScraper/oxy.d.ts +0 -3
  78. package/script/src/apis/chatgptScraper/oxy.d.ts.map +0 -1
  79. package/script/src/apis/chatgptScraper/oxy.js +0 -192
  80. package/script/src/apis/chatgptScraper/scraper.d.ts.map +0 -1
  81. package/script/src/apis/chatgptScraper/scraper.js +0 -139
  82. /package/esm/src/apis/brightdata/{index.d.ts → contentScraper/index.d.ts} +0 -0
  83. /package/esm/src/apis/brightdata/{index.js → contentScraper/index.js} +0 -0
  84. /package/script/src/apis/brightdata/{index.d.ts → contentScraper/index.d.ts} +0 -0
  85. /package/script/src/apis/brightdata/{index.js → contentScraper/index.js} +0 -0
@@ -1,156 +0,0 @@
1
- /* eslint no-console: ["warn", { allow: ["log", "warn", "error"] }] */
2
- /**
3
- * Oxylabs GPT Scraper Provider.
4
- *
5
- * API Flow (Async Push-Pull):
6
- * 1. Trigger: POST to /v1/queries → returns job id
7
- * 2. Monitor: GET /v1/queries/{id} until status is 'done'
8
- * 3. Download: GET /v1/queries/{id}/results
9
- */
10
- import * as dntShim from "../../../_dnt.shims.js";
11
- import { withRetries, sleep } from '../../helpers/async.js';
12
- import { getAbortSignal, cleanAnswer, buildSources } from './scraper.js';
13
- // ============================================================================
14
- // Constants
15
- // ============================================================================
16
- const API_BASE = 'https://data.oxylabs.io/v1';
17
- const RETRY_CONFIG = {
18
- maxRetries: 3,
19
- initialDelay: 1000,
20
- statusCodes: [429, 500, 502, 503, 504, 524, 612, 613]
21
- };
22
- const MAX_WAIT_MS = 600_000; // 10 minutes
23
- const POLL_INTERVAL_MS = 5_000;
24
- // ============================================================================
25
- // Auth
26
- // ============================================================================
27
- function getAuthHeader() {
28
- const username = dntShim.Deno.env.get('OXYLABS_USERNAME');
29
- const password = dntShim.Deno.env.get('OXYLABS_PASSWORD');
30
- if (!username || !password) {
31
- throw new Error('OXYLABS_USERNAME and OXYLABS_PASSWORD environment variables are required');
32
- }
33
- return `Basic ${btoa(`${username}:${password}`)}`;
34
- }
35
- // ============================================================================
36
- // Provider Functions
37
- // ============================================================================
38
- async function triggerJob(prompt, useSearch, countryISOCode) {
39
- const authHeader = getAuthHeader();
40
- const url = `${API_BASE}/queries`;
41
- const body = {
42
- source: 'chatgpt',
43
- prompt,
44
- parse: true,
45
- search: true // Oxylabs requires search: true (cannot be false or blank)
46
- };
47
- if (countryISOCode) {
48
- body.geo_location = countryISOCode;
49
- }
50
- try {
51
- const response = await withRetries(() => fetch(url, {
52
- method: 'POST',
53
- headers: {
54
- 'Authorization': authHeader,
55
- 'Content-Type': 'application/json'
56
- },
57
- body: JSON.stringify(body),
58
- signal: getAbortSignal()
59
- }), RETRY_CONFIG);
60
- if (!response.ok) {
61
- console.error(`[Oxylabs] Trigger error: ${response.status}`);
62
- return null;
63
- }
64
- const data = await response.json();
65
- return data?.id || null;
66
- }
67
- catch (error) {
68
- console.error('[Oxylabs] Trigger failed:', error);
69
- return null;
70
- }
71
- }
72
- async function monitorJob(jobId) {
73
- const authHeader = getAuthHeader();
74
- const url = `${API_BASE}/queries/${jobId}`;
75
- const startTime = Date.now();
76
- const abortSignal = getAbortSignal();
77
- while (Date.now() - startTime < MAX_WAIT_MS) {
78
- if (abortSignal?.aborted)
79
- return false;
80
- try {
81
- const response = await fetch(url, {
82
- headers: { 'Authorization': authHeader },
83
- signal: abortSignal
84
- });
85
- // 204 = job not completed yet, continue polling
86
- if (response.status === 204) {
87
- await sleep(POLL_INTERVAL_MS, abortSignal);
88
- continue;
89
- }
90
- if (response.ok) {
91
- const status = await response.json();
92
- if (status.status === 'done')
93
- return true;
94
- if (status.status === 'faulted' || status.status === 'failed')
95
- return false;
96
- }
97
- }
98
- catch (error) {
99
- console.error('[Oxylabs] Monitor error:', error);
100
- }
101
- await sleep(POLL_INTERVAL_MS, abortSignal);
102
- }
103
- console.error(`[Oxylabs] Monitor timeout after ${MAX_WAIT_MS / 1000}s`);
104
- return false;
105
- }
106
- async function downloadJob(jobId) {
107
- const authHeader = getAuthHeader();
108
- const url = `${API_BASE}/queries/${jobId}/results`;
109
- try {
110
- const response = await withRetries(() => fetch(url, {
111
- headers: { 'Authorization': authHeader },
112
- signal: getAbortSignal()
113
- }), RETRY_CONFIG);
114
- if (!response.ok) {
115
- console.error(`[Oxylabs] Download error: ${response.status}`);
116
- return null;
117
- }
118
- return await response.json();
119
- }
120
- catch (error) {
121
- console.error('[Oxylabs] Download failed:', error);
122
- return null;
123
- }
124
- }
125
- function transformResponse(raw) {
126
- const response = raw;
127
- const content = response?.results?.[0]?.content;
128
- if (!content)
129
- return null;
130
- let answer = content.markdown_text || content.response_text || '';
131
- answer = cleanAnswer(answer);
132
- // Map section='citations' to cited=true (like Brightdata's cited field)
133
- const citations = (content.citations ?? []).map(c => ({
134
- ...c,
135
- cited: c.section === 'citations'
136
- }));
137
- return {
138
- prompt: content.prompt || '',
139
- answer,
140
- sources: buildSources(citations),
141
- searchQueries: [],
142
- searchSources: []
143
- };
144
- }
145
- // ============================================================================
146
- // Export
147
- // ============================================================================
148
- export const oxylabsProvider = {
149
- name: 'Oxylabs',
150
- maxConcurrency: 10,
151
- maxPromptsPerRequest: 1,
152
- triggerJob,
153
- monitorJob,
154
- downloadJob,
155
- transformResponse
156
- };
@@ -1 +0,0 @@
1
- {"version":3,"file":"scraper.d.ts","sourceRoot":"","sources":["../../../../src/src/apis/chatgptScraper/scraper.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAO5E,MAAM,WAAW,YAAY;IAC5B,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;IACvB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,IAAI,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC1G,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAChD,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACjD,iBAAiB,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,WAAW,GAAG,IAAI,CAAC;CACxD;AAED,MAAM,WAAW,UAAU;IAC1B,cAAc,EAAE,MAAM,CAAC;IACvB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,cAAc,EAAE,CAAC,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;IACvE,eAAe,EAAE,CAAC,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;IAC1E,oBAAoB,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;CACpF;AAMD,wBAAgB,cAAc,IAAI,WAAW,GAAG,SAAS,CAExD;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAMlD;AAED,wBAAgB,YAAY,CAC3B,SAAS,EAAE,KAAK,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,EACvG,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,GAC3C,KAAK,CAAC,MAAM,CAAC,CAQf;AAED,wBAAgB,kBAAkB,CACjC,OAAO,EAAE,KAAK,CAAC;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GACxG,KAAK,CAAC,YAAY,CAAC,CAQrB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,WAAW,CAS5G;AAMD,wBAAgB,aAAa,CAAC,QAAQ,EAAE,iBAAiB,GAAG,UAAU,CAkErE"}
@@ -1,98 +0,0 @@
1
- /* eslint no-console: ["warn", { allow: ["log", "warn", "error"] }] */
2
- /**
3
- * GPT Scraper - Core types and orchestration logic.
4
- *
5
- * Uses composition: providers supply functions, this module orchestrates them.
6
- */
7
- import * as dntShim from "../../../_dnt.shims.js";
8
- import { mapParallel } from '../../helpers/async.js';
9
- import { extractDomain } from '../../helpers/urls.js';
10
- // ============================================================================
11
- // Shared Utilities
12
- // ============================================================================
13
- export function getAbortSignal() {
14
- return dntShim.dntGlobalThis.abortSignal;
15
- }
16
- export function cleanAnswer(answer) {
17
- return answer
18
- .replace(/!\[([^\]]*)\]\([^)]+\)/g, '')
19
- .replace(/\n\s*Image\s*\n/g, '\n')
20
- .replace(/\n{3,}/g, '\n\n')
21
- .trim();
22
- }
23
- export function buildSources(citations, linkPositions) {
24
- return citations.map(c => ({
25
- title: c.title || c.description || c.text || '',
26
- url: c.url,
27
- domain: extractDomain(c.url),
28
- cited: c.cited,
29
- positions: linkPositions?.[c.url]
30
- }));
31
- }
32
- export function buildSearchSources(sources) {
33
- return sources.map(s => ({
34
- title: s.title || s.snippet || '',
35
- url: s.url || '',
36
- domain: s.url ? extractDomain(s.url) : '',
37
- rank: s.rank || 0,
38
- datePublished: s.date_published || null
39
- }));
40
- }
41
- /**
42
- * Creates an empty model result for failed jobs.
43
- * This ensures we always return the same number of rows as input.
44
- */
45
- export function emptyModelResult(providerName, errorMessage, context) {
46
- if (errorMessage) {
47
- console.error(`[${providerName}] ${errorMessage}`, context ?? '');
48
- }
49
- return {
50
- prompt: '',
51
- answer: '',
52
- sources: []
53
- };
54
- }
55
- // ============================================================================
56
- // Scraper Factory
57
- // ============================================================================
58
- export function createScraper(provider) {
59
- const { name, maxConcurrency, maxPromptsPerRequest, triggerJob, monitorJob, downloadJob, transformResponse } = provider;
60
- async function triggerGPTBatch({ prompts, useSearch = false, countryISOCode = null }) {
61
- const jobIds = await mapParallel(prompts, maxConcurrency, (prompt) => triggerJob(prompt, useSearch, countryISOCode));
62
- console.log(`[${name}] Triggered ${jobIds.length} jobs for ${prompts.length} prompts`);
63
- return jobIds;
64
- }
65
- async function downloadGPTSnapshots(jobIds) {
66
- const results = [];
67
- for (const jobId of jobIds) {
68
- if (!jobId) {
69
- results.push(emptyModelResult(name, 'No job ID provided'));
70
- continue;
71
- }
72
- const isReady = await monitorJob(jobId);
73
- if (!isReady) {
74
- results.push(emptyModelResult(name, 'Job not ready or failed', jobId));
75
- continue;
76
- }
77
- const raw = await downloadJob(jobId);
78
- if (!raw) {
79
- results.push(emptyModelResult(name, 'Failed to download job', jobId));
80
- continue;
81
- }
82
- const result = transformResponse(raw);
83
- results.push(result ?? emptyModelResult(name, 'Failed to transform response', jobId));
84
- }
85
- return results;
86
- }
87
- async function scrapeGPTBatch(options) {
88
- const jobIds = await triggerGPTBatch(options);
89
- return downloadGPTSnapshots(jobIds);
90
- }
91
- return {
92
- maxConcurrency,
93
- maxPromptsPerRequest,
94
- scrapeGPTBatch,
95
- triggerGPTBatch,
96
- downloadGPTSnapshots
97
- };
98
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/src/apis/brightdata/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"scrape.d.ts","sourceRoot":"","sources":["../../../../src/src/apis/brightdata/scrape.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAapF,MAAM,WAAW,uBAAuB;IACpC,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6DAA6D;IAC7D,MAAM,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACxB,8DAA8D;IAC9D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oDAAoD;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,kCAAkC;IAClC,WAAW,CAAC,EAAE,WAAW,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACrC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AA4ED;;;GAGG;AACH,wBAAsB,gBAAgB,CAClC,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,uBAA4B,GACtC,OAAO,CAAC,wBAAwB,CAAC,CAYnC;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CACvC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EACnB,OAAO,GAAE,uBAA4B,EACrC,cAAc,GAAE,MAA+B,GAChD,OAAO,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAQ1C"}
@@ -1,3 +0,0 @@
1
- import { type ProviderFunctions } from './scraper.js';
2
- export declare const brightdataProvider: ProviderFunctions;
3
- //# sourceMappingURL=brightdata.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"brightdata.d.ts","sourceRoot":"","sources":["../../../../src/src/apis/chatgptScraper/brightdata.ts"],"names":[],"mappings":"AAeA,OAAO,EACN,KAAK,iBAAiB,EAKtB,MAAM,cAAc,CAAC;AAmNtB,eAAO,MAAM,kBAAkB,EAAE,iBAQhC,CAAC"}
@@ -1,208 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.brightdataProvider = void 0;
37
- /* eslint no-console: ["warn", { allow: ["log", "warn", "error"] }] */
38
- /**
39
- * Brightdata GPT Scraper Provider.
40
- *
41
- * API Flow:
42
- * 1. Trigger: POST to /datasets/v3/trigger → returns snapshot_id
43
- * 2. Monitor: GET /datasets/v3/progress/{snapshot_id} until ready
44
- * 3. Download: GET /datasets/v3/snapshot/{snapshot_id}
45
- */
46
- const dntShim = __importStar(require("../../../_dnt.shims.js"));
47
- const async_js_1 = require("../../helpers/async.js");
48
- const scraper_js_1 = require("./scraper.js");
49
- // ============================================================================
50
- // Constants
51
- // ============================================================================
52
- const API_BASE = 'https://api.brightdata.com';
53
- const DATASET_ID = 'gd_m7aof0k82r803d5bjm';
54
- const OUTPUT_FIELDS = 'url|prompt|answer_text|answer_text_markdown|citations|links_attached|search_sources|country|model|web_search_triggered|web_search_query|index';
55
- const TRIGGER_RETRY = {
56
- maxRetries: 3,
57
- initialDelay: 0,
58
- statusCodes: [429, 500, 502, 503, 504]
59
- };
60
- const DOWNLOAD_RETRY = {
61
- maxRetries: 5,
62
- initialDelay: 2000,
63
- statusCodes: [202, 500, 502, 503, 504]
64
- };
65
- const MONITOR_RETRY = {
66
- maxRetries: 4,
67
- initialDelay: 1000,
68
- statusCodes: [408, 425, 429, 500, 502, 503, 504]
69
- };
70
- const MONITOR_RETRIABLE = new Set(MONITOR_RETRY.statusCodes ?? []);
71
- const MAX_WAIT_MS = 600_000; // 10 minutes
72
- const POLL_INTERVAL_MS = 5_000;
73
- // ============================================================================
74
- // API Key
75
- // ============================================================================
76
- function getApiKey() {
77
- const apiKey = dntShim.Deno.env.get('BRIGHTDATA_API_KEY');
78
- if (!apiKey) {
79
- throw new Error('BRIGHTDATA_API_KEY environment variable is required');
80
- }
81
- return apiKey;
82
- }
83
- // ============================================================================
84
- // Provider Functions
85
- // ============================================================================
86
- async function triggerJob(prompt, useSearch, countryISOCode) {
87
- const apiKey = getApiKey();
88
- const url = `${API_BASE}/datasets/v3/trigger?dataset_id=${DATASET_ID}&include_errors=true`;
89
- const body = {
90
- custom_output_fields: OUTPUT_FIELDS,
91
- input: [{
92
- url: 'http://chatgpt.com/',
93
- prompt,
94
- web_search: useSearch,
95
- country: countryISOCode || '',
96
- index: 0
97
- }]
98
- };
99
- try {
100
- const response = await (0, async_js_1.withRetries)(() => fetch(url, {
101
- method: 'POST',
102
- headers: {
103
- 'Authorization': `Bearer ${apiKey}`,
104
- 'Content-Type': 'application/json'
105
- },
106
- body: JSON.stringify(body),
107
- signal: (0, scraper_js_1.getAbortSignal)()
108
- }), TRIGGER_RETRY);
109
- if (!response.ok) {
110
- console.error(`[Brightdata] Trigger error: ${response.status}`);
111
- return null;
112
- }
113
- const data = await response.json();
114
- return data?.snapshot_id || null;
115
- }
116
- catch (error) {
117
- console.error('[Brightdata] Trigger failed:', error);
118
- return null;
119
- }
120
- }
121
- async function monitorJob(snapshotId) {
122
- const apiKey = getApiKey();
123
- const url = `${API_BASE}/datasets/v3/progress/${snapshotId}`;
124
- const startTime = Date.now();
125
- const abortSignal = (0, scraper_js_1.getAbortSignal)();
126
- while (Date.now() - startTime < MAX_WAIT_MS) {
127
- if (abortSignal?.aborted)
128
- return false;
129
- try {
130
- const response = await (0, async_js_1.withRetries)(() => fetch(url, {
131
- headers: { 'Authorization': `Bearer ${apiKey}` },
132
- signal: abortSignal
133
- }), MONITOR_RETRY);
134
- if (!response.ok) {
135
- if (!MONITOR_RETRIABLE.has(response.status))
136
- return false;
137
- }
138
- else {
139
- const status = await response.json();
140
- if (status.status === 'ready' || status.status === 'complete')
141
- return true;
142
- if (status.status === 'failed' || status.status === 'error')
143
- return false;
144
- }
145
- }
146
- catch (error) {
147
- console.error('[Brightdata] Monitor error:', error);
148
- }
149
- await (0, async_js_1.sleep)(POLL_INTERVAL_MS, abortSignal);
150
- }
151
- console.error(`[Brightdata] Monitor timeout after ${MAX_WAIT_MS / 1000}s`);
152
- return false;
153
- }
154
- async function downloadJob(snapshotId) {
155
- const apiKey = getApiKey();
156
- const url = `${API_BASE}/datasets/v3/snapshot/${snapshotId}?format=json`;
157
- try {
158
- const response = await (0, async_js_1.withRetries)(() => fetch(url, {
159
- headers: { 'Authorization': `Bearer ${apiKey}` },
160
- signal: (0, scraper_js_1.getAbortSignal)()
161
- }), DOWNLOAD_RETRY);
162
- if (!response.ok) {
163
- console.error(`[Brightdata] Download error: ${response.status}`);
164
- return null;
165
- }
166
- const data = await response.json();
167
- return Array.isArray(data) ? data : null;
168
- }
169
- catch (error) {
170
- console.error('[Brightdata] Download failed:', error);
171
- return null;
172
- }
173
- }
174
- function transformResponse(raw) {
175
- const responses = raw;
176
- if (!responses || responses.length === 0)
177
- return null;
178
- const response = responses[0];
179
- let answer = response.answer_text_markdown || response.answer_text || '';
180
- answer = (0, scraper_js_1.cleanAnswer)(answer);
181
- // Build link positions map
182
- const linkPositions = {};
183
- for (const link of response.links_attached ?? []) {
184
- if (link.url && link.position != null) {
185
- linkPositions[link.url] ??= [];
186
- linkPositions[link.url].push(link.position);
187
- }
188
- }
189
- return {
190
- prompt: response.prompt,
191
- answer,
192
- sources: (0, scraper_js_1.buildSources)(response.citations ?? [], linkPositions),
193
- searchQueries: response.web_search_query || [],
194
- searchSources: (0, scraper_js_1.buildSearchSources)(response.search_sources ?? [])
195
- };
196
- }
197
- // ============================================================================
198
- // Export
199
- // ============================================================================
200
- exports.brightdataProvider = {
201
- name: 'Brightdata',
202
- maxConcurrency: 50,
203
- maxPromptsPerRequest: 1,
204
- triggerJob,
205
- monitorJob,
206
- downloadJob,
207
- transformResponse
208
- };
@@ -1,10 +0,0 @@
1
- import type { ModelResult } from '../../schemas/models.schema.js';
2
- import { type BatchOptions } from './scraper.js';
3
- export type { BatchOptions };
4
- export type JobId = string | null;
5
- export declare function getMaxConcurrency(): number;
6
- export declare function getMaxPromptsPerRequest(): number;
7
- export declare function scrapeGPTBatch(options: BatchOptions): Promise<Array<ModelResult>>;
8
- export declare function triggerGPTBatch(options: BatchOptions): Promise<Array<string | null>>;
9
- export declare function downloadGPTSnapshots(jobIds: Array<string | null>): Promise<Array<ModelResult>>;
10
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/src/apis/chatgptScraper/index.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,KAAK,YAAY,EAAkC,MAAM,cAAc,CAAC;AAKjF,YAAY,EAAE,YAAY,EAAE,CAAC;AAC7B,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG,IAAI,CAAC;AAqBlC,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C;AAED,wBAAgB,uBAAuB,IAAI,MAAM,CAEhD;AAED,wBAAsB,cAAc,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAEvF;AAED,wBAAsB,eAAe,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAE1F;AAED,wBAAsB,oBAAoB,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAEpG"}
@@ -1,81 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.getMaxConcurrency = getMaxConcurrency;
37
- exports.getMaxPromptsPerRequest = getMaxPromptsPerRequest;
38
- exports.scrapeGPTBatch = scrapeGPTBatch;
39
- exports.triggerGPTBatch = triggerGPTBatch;
40
- exports.downloadGPTSnapshots = downloadGPTSnapshots;
41
- /* eslint no-console: ["warn", { allow: ["log", "warn", "error"] }] */
42
- /**
43
- * GPT Scraper - Public API
44
- *
45
- * Selects between Brightdata and Oxylabs based on CHATGPT_SCRAPER_PROVIDER env var.
46
- * Default: oxylabs
47
- */
48
- const dntShim = __importStar(require("../../../_dnt.shims.js"));
49
- const scraper_js_1 = require("./scraper.js");
50
- const brightdata_js_1 = require("./brightdata.js");
51
- const oxy_js_1 = require("./oxy.js");
52
- // ============================================================================
53
- // Scraper Instance (lazy singleton)
54
- // ============================================================================
55
- let scraper = null;
56
- function getScraper() {
57
- if (!scraper) {
58
- const providerName = dntShim.Deno.env.get('CHATGPT_SCRAPER_PROVIDER')?.toLowerCase();
59
- const provider = providerName === 'brightdata' ? brightdata_js_1.brightdataProvider : oxy_js_1.oxylabsProvider;
60
- scraper = (0, scraper_js_1.createScraper)(provider);
61
- }
62
- return scraper;
63
- }
64
- // ============================================================================
65
- // Public API
66
- // ============================================================================
67
- function getMaxConcurrency() {
68
- return getScraper().maxConcurrency;
69
- }
70
- function getMaxPromptsPerRequest() {
71
- return getScraper().maxPromptsPerRequest;
72
- }
73
- async function scrapeGPTBatch(options) {
74
- return getScraper().scrapeGPTBatch(options);
75
- }
76
- async function triggerGPTBatch(options) {
77
- return getScraper().triggerGPTBatch(options);
78
- }
79
- async function downloadGPTSnapshots(jobIds) {
80
- return getScraper().downloadGPTSnapshots(jobIds);
81
- }
@@ -1,3 +0,0 @@
1
- import { type ProviderFunctions } from './scraper.js';
2
- export declare const oxylabsProvider: ProviderFunctions;
3
- //# sourceMappingURL=oxy.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"oxy.d.ts","sourceRoot":"","sources":["../../../../src/src/apis/chatgptScraper/oxy.ts"],"names":[],"mappings":"AAeA,OAAO,EACN,KAAK,iBAAiB,EAItB,MAAM,cAAc,CAAC;AA6LtB,eAAO,MAAM,eAAe,EAAE,iBAQ7B,CAAC"}