perplex.js 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,20 +1,20 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 DIDELOT Tim
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1
+ MIT License
2
+
3
+ Copyright (c) 2025 DIDELOT Tim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,36 +1,36 @@
1
-
2
- # Perplex.js — Minimal Node.js client for Perplexity AI
3
-
4
- This small library provides a minimal client to query the Perplexity API.
5
-
6
-
7
- Features:
8
- - Synchronous request to the SSE endpoint `/rest/sse/perplexity_ask`.
9
- - Methods: `search` (returns the final response), `streamSearch` (async iterator for streaming messages).
10
-
11
- Installation:
12
-
13
- ```bash
14
- npm install perplex.js
15
- ```
16
-
17
-
18
-
19
- Usage (example):
20
-
21
- ```js
22
- import { PerplexityClient } from 'perplex.js';
23
- const c = new PerplexityClient();
24
- // To use your account, manually export cookies from your browser
25
- // (for example using a cookie export extension) and save them
26
- // into `perplexity_cookies.json` as an array of {name, value, domain, ...} objects.
27
- // Then:
28
- // const cookies = JSON.parse(fs.readFileSync('./perplexity_cookies.json', 'utf8'));
29
- // const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; ');
30
- // const c = new PerplexityClient({ cookies: cookieHeader });
31
- // await c.search('What is the capital of France?');
32
- ```
33
-
34
- Notes:
35
- - Authentication is performed via session cookies. This library does not require an API key.
36
- - Endpoints and payload formats aim to match Perplexity's publicly observed API.
1
+
2
+ # Perplex.js — Minimal Node.js client for Perplexity AI
3
+
4
+ This small library provides a minimal client to query the Perplexity API.
5
+
6
+
7
+ Features:
8
+ - Synchronous request to the SSE endpoint `/rest/sse/perplexity_ask`.
9
+ - Methods: `search` (returns the final response), `streamSearch` (async iterator for streaming messages).
10
+
11
+ Installation:
12
+
13
+ ```bash
14
+ npm install perplex.js
15
+ ```
16
+
17
+
18
+
19
+ Usage (example):
20
+
21
+ ```js
22
+ import { PerplexityClient } from 'perplex.js';
23
+ const c = new PerplexityClient();
24
+ // To use your account, manually export cookies from your browser
25
+ // (for example using a cookie export extension) and save them
26
+ // into `perplexity_cookies.json` as an array of {name, value, domain, ...} objects.
27
+ // Then:
28
+ // const cookies = JSON.parse(fs.readFileSync('./perplexity_cookies.json', 'utf8'));
29
+ // const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; ');
30
+ // const c = new PerplexityClient({ cookies: cookieHeader });
31
+ // await c.search('What is the capital of France?');
32
+ ```
33
+
34
+ Notes:
35
+ - Authentication is performed via session cookies. This library does not require an API key.
36
+ - Endpoints and payload formats aim to match Perplexity's publicly observed API.
package/package.json CHANGED
@@ -1,30 +1,30 @@
1
- {
2
- "name": "perplex.js",
3
- "version": "0.1.6",
4
- "description": "Minimal Node.js client for the Perplexity API",
5
- "type": "module",
6
- "main": "src/index.js",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/xFufly/Perplex.js.git"
10
- },
11
- "files": [
12
- "src",
13
- "README.md"
14
- ],
15
- "engines": {
16
- "node": ">=18"
17
- },
18
- "scripts": {
19
- "test": "node example.js",
20
- "cli": "node examples/cli.js"
21
- },
22
- "keywords": ["perplexity", "perplexity.ai", "ai", "client"],
23
- "author": "DIDELOT Tim",
24
- "license": "MIT",
25
- "dependencies": {
26
- "undici": "^6.0.0"
27
- }
28
- }
29
-
30
-
1
+ {
2
+ "name": "perplex.js",
3
+ "version": "0.2.0",
4
+ "description": "Minimal Node.js client for the Perplexity API",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/xFufly/Perplex.js.git"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "scripts": {
19
+ "test": "node example.js",
20
+ "cli": "node examples/cli.js"
21
+ },
22
+ "keywords": ["perplexity", "perplexity.ai", "ai", "client"],
23
+ "author": "DIDELOT Tim",
24
+ "license": "MIT",
25
+ "dependencies": {
26
+ "undici": "^6.0.0"
27
+ }
28
+ }
29
+
30
+
package/src/client.js CHANGED
@@ -1,290 +1,301 @@
1
- import {
2
- request
3
- } from 'undici';
4
- import {
5
- parseSSE
6
- } from './sseParser.js';
7
-
8
- function defaultHeaders(cookie) {
9
- const headers = {
10
- 'accept': 'text/event-stream, text/plain, */*',
11
- 'content-type': 'application/json',
12
- 'user-agent': 'perplexity-js/0.1',
13
- };
14
-
15
- if (cookie) headers['cookie'] = typeof cookie === 'string' ? cookie : Object.entries(cookie).map(([k, v]) => `${k}=${v}`).join('; ');
16
- return headers;
17
- }
18
-
19
- export default class PerplexityClient {
20
- constructor(options = {}) {
21
- // Perplexity access is done via session cookies (or anonymously). No API key is required.
22
- this.base = options.base || 'https://www.perplexity.ai';
23
- this.version = options.version || '2.18';
24
- // optional cookies: either string or object map
25
- this.cookies = options.cookies || null;
26
- }
27
-
28
- // Static mapping of modes -> available models
29
- static modelMap() {
30
- return {
31
- auto: [null],
32
- pro: [null, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
33
- reasoning: [null, 'r1', 'o3-mini', 'claude 3.7 sonnet', 'gpt5', 'gpt5_thinking', 'claude37sonnetthinking'],
34
- 'deep research': [null],
35
- copilot: ['grok41reasoning']
36
- };
37
- }
38
-
39
- static getAvailableModels(mode) {
40
- const map = PerplexityClient.modelMap();
41
- return map[mode] || [];
42
- }
43
-
44
- static getAvailableModels(mode = 'auto') {
45
- const modelPreferences = {
46
- auto: [null],
47
- pro: [null, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
48
- reasoning: [null, 'r1', 'o3-mini', 'claude 3.7 sonnet', 'gpt5', 'gpt5_thinking'],
49
- 'deep research': [null],
50
- copilot: ['grok41reasoning']
51
- };
52
- return modelPreferences[mode] ?? modelPreferences.auto;
53
- }
54
-
55
- // Build the payload for the request
56
- _buildPayload(query, opts = {}) {
57
- const {
58
- mode = 'auto', model = null, sources = ['web'], attachments = [], language = 'en-US', follow_up = null, incognito = false
59
- } = opts;
60
-
61
- const attachmentsFinal = attachments.concat(follow_up && follow_up.attachments ? follow_up.attachments : []);
62
-
63
- const modelPreferences = {
64
- auto: {
65
- null: 'turbo'
66
- },
67
- pro: {
68
- null: 'pplx_pro',
69
- 'sonar': 'experimental',
70
- 'gpt-4.5': 'gpt45',
71
- 'gpt-4o': 'gpt4o',
72
- 'claude 3.7 sonnet': 'claude2',
73
- 'gemini 2.0 flash': 'gemini2flash',
74
- 'grok-2': 'grok'
75
- },
76
- reasoning: {
77
- null: 'pplx_reasoning',
78
- 'r1': 'r1',
79
- 'o3-mini': 'o3mini',
80
- 'claude 3.7 sonnet': 'claude37sonnetthinking',
81
- 'gpt5': 'gpt5',
82
- 'gpt5_thinking': 'gpt5thinking'
83
- },
84
- 'deep research': {
85
- null: 'pplx_alpha'
86
- },
87
- copilot: {
88
- 'grok41reasoning': 'grok41reasoning'
89
- }
90
- };
91
-
92
- // safe lookup: try to pick the exact key, else fallback to the first available value
93
- const mpForMode = modelPreferences[mode] || modelPreferences.auto;
94
- let modelPref = null;
95
- if (mpForMode) {
96
- // if model is null, treat as null key
97
- if (model == null) modelPref = mpForMode.null ?? Object.values(mpForMode)[0];
98
- else if (Object.prototype.hasOwnProperty.call(mpForMode, model)) modelPref = mpForMode[model];
99
- else {
100
- // invalid model for the chosen mode
101
- const allowed = Object.keys(mpForMode).filter(k => k !== 'null');
102
- throw new Error(`Invalid model '${model}' for mode '${mode}'. Allowed: ${allowed.join(', ') || '<none>'}`);
103
- }
104
- }
105
-
106
- const params = {
107
- attachments: attachmentsFinal,
108
- frontend_context_uuid: cryptoRandomUUID(),
109
- frontend_uuid: cryptoRandomUUID(),
110
- is_incognito: incognito,
111
- language,
112
- last_backend_uuid: follow_up ? follow_up.backend_uuid : null,
113
- mode: mode === 'auto' ? 'concise' : 'copilot',
114
- model_preference: modelPref,
115
- source: 'default',
116
- sources,
117
- version: this.version
118
- };
119
-
120
- return {
121
- query_str: query,
122
- params
123
- };
124
- }
125
-
126
- // Simple helper to generate UUID without depending on node <16 helpers
127
- async _fetch(url, opts) {
128
- const res = await request(url, opts);
129
- const {
130
- statusCode,
131
- headers,
132
- body
133
- } = res;
134
- return {
135
- statusCode,
136
- headers,
137
- body
138
- };
139
- }
140
-
141
- // Supports both: (query, opts) and positional signature:
142
- // search(query, mode='auto', model=null, sources=['web'], files={}, stream=false, language='en-US', follow_up=null, incognito=false)
143
- async search(...args) {
144
- let query;
145
- let opts = {};
146
-
147
- if (args.length === 0) throw new Error('search requires at least a query string');
148
-
149
- query = args[0];
150
-
151
- // If second arg is an object, assume opts form
152
- if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
153
- opts = args[1];
154
- } else if (args.length >= 2) {
155
- // positional mapping for backwards compatibility
156
- const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
157
- opts = {
158
- mode,
159
- model,
160
- sources,
161
- files,
162
- stream,
163
- language,
164
- follow_up,
165
- incognito
166
- };
167
- }
168
-
169
- if (opts.files && Object.keys(opts.files).length) {
170
- throw new Error('File upload support is not implemented in this Node client yet');
171
- }
172
-
173
- const payload = this._buildPayload(query, opts);
174
- const url = `${this.base}/rest/sse/perplexity_ask`;
175
-
176
- const {
177
- statusCode,
178
- headers,
179
- body
180
- } = await this._fetch(url, {
181
- method: 'POST',
182
- body: JSON.stringify(payload),
183
- headers: defaultHeaders(this.cookies)
184
- });
185
-
186
- if (statusCode >= 400) {
187
- const text = await body.text();
188
- const err = new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
189
- err.status = statusCode;
190
- throw err;
191
- }
192
-
193
- // collect SSE messages
194
- const messages = [];
195
- for await (const msg of parseSSE(body)) {
196
- if (msg.event === 'message') {
197
- let data = msg.data;
198
- try {
199
- data = JSON.parse(data);
200
- } catch (e) {}
201
- if (data && data.text) {
202
- try {
203
- data.text = JSON.parse(data.text);
204
- } catch (e) {}
205
- }
206
- messages.push(data);
207
- } else if (msg.event === 'end_of_stream') {
208
- break;
209
- }
210
- }
211
-
212
- return messages.length ? messages[messages.length - 1] : null;
213
- }
214
-
215
- // streamSearch supports same signatures as search
216
- async * streamSearch(...args) {
217
- let query;
218
- let opts = {};
219
-
220
- if (args.length === 0) throw new Error('streamSearch requires at least a query string');
221
-
222
- query = args[0];
223
- if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
224
- opts = args[1];
225
- } else if (args.length >= 2) {
226
- const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
227
- opts = {
228
- mode,
229
- model,
230
- sources,
231
- files,
232
- stream,
233
- language,
234
- follow_up,
235
- incognito
236
- };
237
- }
238
-
239
- if (opts.files && Object.keys(opts.files).length) {
240
- throw new Error('File upload support is not implemented in this Node client yet');
241
- }
242
-
243
- const payload = this._buildPayload(query, opts);
244
- const url = `${this.base}/rest/sse/perplexity_ask`;
245
-
246
- const {
247
- statusCode,
248
- headers,
249
- body
250
- } = await this._fetch(url, {
251
- method: 'POST',
252
- body: JSON.stringify(payload),
253
- headers: defaultHeaders(this.cookies)
254
- });
255
-
256
- if (statusCode >= 400) {
257
- const text = await body.text();
258
- throw new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
259
- }
260
-
261
- for await (const msg of parseSSE(body)) {
262
- if (msg.event === 'message') {
263
- let data = msg.data;
264
- try {
265
- data = JSON.parse(data);
266
- } catch (e) {}
267
- if (data && data.text) {
268
- try {
269
- data.text = JSON.parse(data.text);
270
- } catch (e) {}
271
- }
272
- yield data;
273
- } else if (msg.event === 'end_of_stream') {
274
- return;
275
- }
276
- }
277
- }
278
- }
279
-
280
- function cryptoRandomUUID() {
281
- // Use global crypto if available
282
- if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
283
-
284
- // Fallback simple UUID v4 generator
285
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
286
- const r = Math.random() * 16 | 0;
287
- const v = c === 'x' ? r : (r & 0x3 | 0x8);
288
- return v.toString(16);
289
- });
1
+ import {
2
+ request
3
+ } from 'undici';
4
+ import {
5
+ parseSSE
6
+ } from './sseParser.js';
7
+
8
+ function defaultHeaders(cookie) {
9
+ const headers = {
10
+ 'accept': 'text/event-stream, text/plain, */*',
11
+ 'content-type': 'application/json',
12
+ 'user-agent': 'perplexity-js/0.1',
13
+ };
14
+
15
+ if (cookie) headers['cookie'] = typeof cookie === 'string' ? cookie : Object.entries(cookie).map(([k, v]) => `${k}=${v}`).join('; ');
16
+ return headers;
17
+ }
18
+
19
+ export default class PerplexityClient {
20
+ constructor(options = {}) {
21
+ // Perplexity access is done via session cookies (or anonymously). No API key is required.
22
+ this.base = options.base || 'https://www.perplexity.ai';
23
+ this.version = options.version || '2.18';
24
+ // optional cookies: either string or object map
25
+ this.cookies = options.cookies || null;
26
+ }
27
+
28
+ // Static mapping of modes -> available models
29
+ static modelMap() {
30
+ return {
31
+ auto: [null],
32
+ pro: [null, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
33
+ reasoning: [null, 'r1', 'o3-mini', 'claude 3.7 sonnet', 'gpt5', 'gpt5_thinking', 'claude37sonnetthinking'],
34
+ 'deep research': [null],
35
+ copilot: [null, 'grok41nonreasoning', 'grok41reasoning', 'sonar', 'gpt52', 'gpt52_thinking', 'gemini30pro', 'gemini30flash', 'gemini30flash_high', 'kimik2thinking', 'claude45sonnet', 'claude45sonnetthinking']
36
+ };
37
+ }
38
+
39
+ static getAvailableModels(mode) {
40
+ const map = PerplexityClient.modelMap();
41
+ return map[mode] || [];
42
+ }
43
+
44
+ static getAvailableModels(mode = 'auto') {
45
+ const modelPreferences = {
46
+ auto: [null],
47
+ pro: [null, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
48
+ reasoning: [null, 'r1', 'o3-mini', 'claude 3.7 sonnet', 'gpt5', 'gpt5_thinking'],
49
+ 'deep research': [null],
50
+ copilot: [null, 'grok41nonreasoning', 'grok41reasoning', 'sonar', 'gpt52', 'gpt52_thinking', 'gemini30pro', 'gemini30flash', 'gemini30flash_high', 'kimik2thinking', 'claude45sonnet', 'claude45sonnetthinking']
51
+ };
52
+ return modelPreferences[mode] ?? modelPreferences.auto;
53
+ }
54
+
55
+ // Build the payload for the request
56
+ _buildPayload(query, opts = {}) {
57
+ const {
58
+ mode = 'auto', model = null, sources = ['web'], attachments = [], language = 'en-US', follow_up = null, incognito = false
59
+ } = opts;
60
+
61
+ const attachmentsFinal = attachments.concat(follow_up && follow_up.attachments ? follow_up.attachments : []);
62
+
63
+ const modelPreferences = {
64
+ auto: {
65
+ null: 'turbo'
66
+ },
67
+ pro: {
68
+ null: 'pplx_pro',
69
+ 'sonar': 'experimental',
70
+ 'gpt-4.5': 'gpt45',
71
+ 'gpt-4o': 'gpt4o',
72
+ 'claude 3.7 sonnet': 'claude2',
73
+ 'gemini 2.0 flash': 'gemini2flash',
74
+ 'grok-2': 'grok'
75
+ },
76
+ reasoning: {
77
+ null: 'pplx_reasoning',
78
+ 'r1': 'r1',
79
+ 'o3-mini': 'o3mini',
80
+ 'claude 3.7 sonnet': 'claude37sonnetthinking',
81
+ 'gpt5': 'gpt5',
82
+ 'gpt5_thinking': 'gpt5thinking'
83
+ },
84
+ 'deep research': {
85
+ null: 'pplx_alpha'
86
+ },
87
+ copilot: {
88
+ null: 'pplx_pro',
89
+ 'grok41nonreasoning': 'grok41nonreasoning',
90
+ 'grok41reasoning': 'grok41reasoning',
91
+ 'sonar': 'experimental',
92
+ 'gpt52': 'gpt52',
93
+ 'gpt52_thinking': 'gpt52_thinking',
94
+ 'gemini30pro': 'gemini30pro',
95
+ 'gemini30flash': 'gemini30flash',
96
+ 'gemini30flash_high': 'gemini30flash_high',
97
+ 'kimik2thinking': 'kimik2thinking',
98
+ 'claude45sonnet': 'claude45sonnet',
99
+ 'claude45sonnetthinking': 'claude45sonnetthinking'
100
+ }
101
+ };
102
+
103
+ // safe lookup: try to pick the exact key, else fallback to the first available value
104
+ const mpForMode = modelPreferences[mode] || modelPreferences.auto;
105
+ let modelPref = null;
106
+ if (mpForMode) {
107
+ // if model is null, treat as null key
108
+ if (model == null) modelPref = mpForMode.null ?? Object.values(mpForMode)[0];
109
+ else if (Object.prototype.hasOwnProperty.call(mpForMode, model)) modelPref = mpForMode[model];
110
+ else {
111
+ // invalid model for the chosen mode
112
+ const allowed = Object.keys(mpForMode).filter(k => k !== 'null');
113
+ throw new Error(`Invalid model '${model}' for mode '${mode}'. Allowed: ${allowed.join(', ') || '<none>'}`);
114
+ }
115
+ }
116
+
117
+ const params = {
118
+ attachments: attachmentsFinal,
119
+ frontend_context_uuid: cryptoRandomUUID(),
120
+ frontend_uuid: cryptoRandomUUID(),
121
+ is_incognito: incognito,
122
+ language,
123
+ last_backend_uuid: follow_up ? follow_up.backend_uuid : null,
124
+ mode: mode === 'auto' ? 'concise' : 'copilot',
125
+ model_preference: modelPref,
126
+ source: 'default',
127
+ sources,
128
+ version: this.version
129
+ };
130
+
131
+ return {
132
+ query_str: query,
133
+ params
134
+ };
135
+ }
136
+
137
+ // Simple helper to generate UUID without depending on node <16 helpers
138
+ async _fetch(url, opts) {
139
+ const res = await request(url, opts);
140
+ const {
141
+ statusCode,
142
+ headers,
143
+ body
144
+ } = res;
145
+ return {
146
+ statusCode,
147
+ headers,
148
+ body
149
+ };
150
+ }
151
+
152
+ // Supports both: (query, opts) and positional signature:
153
+ // search(query, mode='auto', model=null, sources=['web'], files={}, stream=false, language='en-US', follow_up=null, incognito=false)
154
+ async search(...args) {
155
+ let query;
156
+ let opts = {};
157
+
158
+ if (args.length === 0) throw new Error('search requires at least a query string');
159
+
160
+ query = args[0];
161
+
162
+ // If second arg is an object, assume opts form
163
+ if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
164
+ opts = args[1];
165
+ } else if (args.length >= 2) {
166
+ // positional mapping for backwards compatibility
167
+ const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
168
+ opts = {
169
+ mode,
170
+ model,
171
+ sources,
172
+ files,
173
+ stream,
174
+ language,
175
+ follow_up,
176
+ incognito
177
+ };
178
+ }
179
+
180
+ if (opts.files && Object.keys(opts.files).length) {
181
+ throw new Error('File upload support is not implemented in this Node client yet');
182
+ }
183
+
184
+ const payload = this._buildPayload(query, opts);
185
+ const url = `${this.base}/rest/sse/perplexity_ask`;
186
+
187
+ const {
188
+ statusCode,
189
+ headers,
190
+ body
191
+ } = await this._fetch(url, {
192
+ method: 'POST',
193
+ body: JSON.stringify(payload),
194
+ headers: defaultHeaders(this.cookies)
195
+ });
196
+
197
+ if (statusCode >= 400) {
198
+ const text = await body.text();
199
+ const err = new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
200
+ err.status = statusCode;
201
+ throw err;
202
+ }
203
+
204
+ // collect SSE messages
205
+ const messages = [];
206
+ for await (const msg of parseSSE(body)) {
207
+ if (msg.event === 'message') {
208
+ let data = msg.data;
209
+ try {
210
+ data = JSON.parse(data);
211
+ } catch (e) {}
212
+ if (data && data.text) {
213
+ try {
214
+ data.text = JSON.parse(data.text);
215
+ } catch (e) {}
216
+ }
217
+ messages.push(data);
218
+ } else if (msg.event === 'end_of_stream') {
219
+ break;
220
+ }
221
+ }
222
+
223
+ return messages.length ? messages[messages.length - 1] : null;
224
+ }
225
+
226
+ // streamSearch supports same signatures as search
227
+ async * streamSearch(...args) {
228
+ let query;
229
+ let opts = {};
230
+
231
+ if (args.length === 0) throw new Error('streamSearch requires at least a query string');
232
+
233
+ query = args[0];
234
+ if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
235
+ opts = args[1];
236
+ } else if (args.length >= 2) {
237
+ const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
238
+ opts = {
239
+ mode,
240
+ model,
241
+ sources,
242
+ files,
243
+ stream,
244
+ language,
245
+ follow_up,
246
+ incognito
247
+ };
248
+ }
249
+
250
+ if (opts.files && Object.keys(opts.files).length) {
251
+ throw new Error('File upload support is not implemented in this Node client yet');
252
+ }
253
+
254
+ const payload = this._buildPayload(query, opts);
255
+ const url = `${this.base}/rest/sse/perplexity_ask`;
256
+
257
+ const {
258
+ statusCode,
259
+ headers,
260
+ body
261
+ } = await this._fetch(url, {
262
+ method: 'POST',
263
+ body: JSON.stringify(payload),
264
+ headers: defaultHeaders(this.cookies)
265
+ });
266
+
267
+ if (statusCode >= 400) {
268
+ const text = await body.text();
269
+ throw new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
270
+ }
271
+
272
+ for await (const msg of parseSSE(body)) {
273
+ if (msg.event === 'message') {
274
+ let data = msg.data;
275
+ try {
276
+ data = JSON.parse(data);
277
+ } catch (e) {}
278
+ if (data && data.text) {
279
+ try {
280
+ data.text = JSON.parse(data.text);
281
+ } catch (e) {}
282
+ }
283
+ yield data;
284
+ } else if (msg.event === 'end_of_stream') {
285
+ return;
286
+ }
287
+ }
288
+ }
289
+ }
290
+
291
+ function cryptoRandomUUID() {
292
+ // Use global crypto if available
293
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
294
+
295
+ // Fallback simple UUID v4 generator
296
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
297
+ const r = Math.random() * 16 | 0;
298
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
299
+ return v.toString(16);
300
+ });
290
301
  }
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import PerplexityClient from './client.js';
2
-
3
- // Provide a convenient alias `Client` to match common naming
4
- const Client = PerplexityClient;
5
-
6
- export { PerplexityClient, Client };
7
- export default PerplexityClient;
1
+ import PerplexityClient from './client.js';
2
+
3
+ // Provide a convenient alias `Client` to match common naming
4
+ const Client = PerplexityClient;
5
+
6
+ export { PerplexityClient, Client };
7
+ export default PerplexityClient;
package/src/sseParser.js CHANGED
@@ -1,48 +1,48 @@
1
- // Minimal SSE parser that yields {event, data} objects from a ReadableStream body
2
- export async function* parseSSE(body) {
3
- const reader = body[Symbol.asyncIterator] ? body[Symbol.asyncIterator]() : body.getReader();
4
-
5
- let decoder = new TextDecoder('utf-8');
6
- let buffer = '';
7
-
8
- for await (const chunk of body) {
9
- buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, {
10
- stream: true
11
- });
12
-
13
- let idx;
14
- while ((idx = buffer.indexOf('\r\n\r\n')) !== -1) {
15
- const raw = buffer.slice(0, idx);
16
- buffer = buffer.slice(idx + 4);
17
-
18
- const lines = raw.split(/\r\n/).filter(Boolean);
19
- let event = 'message';
20
- let data = '';
21
-
22
- for (const line of lines) {
23
- if (line.startsWith('event:')) event = line.slice(6).trim();
24
- else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
25
- }
26
-
27
- yield {
28
- event,
29
- data
30
- };
31
- }
32
- }
33
-
34
- if (buffer.trim()) {
35
- // last partial
36
- const lines = buffer.split(/\r\n/).filter(Boolean);
37
- let event = 'message';
38
- let data = '';
39
- for (const line of lines) {
40
- if (line.startsWith('event:')) event = line.slice(6).trim();
41
- else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
42
- }
43
- yield {
44
- event,
45
- data
46
- };
47
- }
1
+ // Minimal SSE parser that yields {event, data} objects from a ReadableStream body
2
+ export async function* parseSSE(body) {
3
+ const reader = body[Symbol.asyncIterator] ? body[Symbol.asyncIterator]() : body.getReader();
4
+
5
+ let decoder = new TextDecoder('utf-8');
6
+ let buffer = '';
7
+
8
+ for await (const chunk of body) {
9
+ buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, {
10
+ stream: true
11
+ });
12
+
13
+ let idx;
14
+ while ((idx = buffer.indexOf('\r\n\r\n')) !== -1) {
15
+ const raw = buffer.slice(0, idx);
16
+ buffer = buffer.slice(idx + 4);
17
+
18
+ const lines = raw.split(/\r\n/).filter(Boolean);
19
+ let event = 'message';
20
+ let data = '';
21
+
22
+ for (const line of lines) {
23
+ if (line.startsWith('event:')) event = line.slice(6).trim();
24
+ else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
25
+ }
26
+
27
+ yield {
28
+ event,
29
+ data
30
+ };
31
+ }
32
+ }
33
+
34
+ if (buffer.trim()) {
35
+ // last partial
36
+ const lines = buffer.split(/\r\n/).filter(Boolean);
37
+ let event = 'message';
38
+ let data = '';
39
+ for (const line of lines) {
40
+ if (line.startsWith('event:')) event = line.slice(6).trim();
41
+ else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
42
+ }
43
+ yield {
44
+ event,
45
+ data
46
+ };
47
+ }
48
48
  }