perplex.js 0.1.0 → 0.1.3

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 https://github.com/xFufly/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,33 @@
1
- {
2
- "name": "perplex.js",
3
- "version": "0.1.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
-
1
+ {
2
+ "name": "perplex.js",
3
+ "version": "0.1.3",
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": [
23
+ "perplexity",
24
+ "perplexity.ai",
25
+ "ai",
26
+ "client"
27
+ ],
28
+ "author": "DIDELOT Tim",
29
+ "license": "MIT",
30
+ "dependencies": {
31
+ "undici": "^6.22.0"
32
+ }
33
+ }
package/src/client.js CHANGED
@@ -1,285 +1,355 @@
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
- };
36
- }
37
-
38
- static getAvailableModels(mode) {
39
- const map = PerplexityClient.modelMap();
40
- return map[mode] || [];
41
- }
42
-
43
- static getAvailableModels(mode = 'auto') {
44
- const modelPreferences = {
45
- auto: [null],
46
- pro: [null, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
47
- reasoning: [null, 'r1', 'o3-mini', 'claude 3.7 sonnet', 'gpt5', 'gpt5_thinking'],
48
- 'deep research': [null]
49
- };
50
- return modelPreferences[mode] ?? modelPreferences.auto;
51
- }
52
-
53
- // Build the payload for the request
54
- _buildPayload(query, opts = {}) {
55
- const {
56
- mode = 'auto', model = null, sources = ['web'], attachments = [], language = 'en-US', follow_up = null, incognito = false
57
- } = opts;
58
-
59
- const attachmentsFinal = attachments.concat(follow_up && follow_up.attachments ? follow_up.attachments : []);
60
-
61
- const modelPreferences = {
62
- auto: {
63
- null: 'turbo'
64
- },
65
- pro: {
66
- null: 'pplx_pro',
67
- 'sonar': 'experimental',
68
- 'gpt-4.5': 'gpt45',
69
- 'gpt-4o': 'gpt4o',
70
- 'claude 3.7 sonnet': 'claude2',
71
- 'gemini 2.0 flash': 'gemini2flash',
72
- 'grok-2': 'grok'
73
- },
74
- reasoning: {
75
- null: 'pplx_reasoning',
76
- 'r1': 'r1',
77
- 'o3-mini': 'o3mini',
78
- 'claude 3.7 sonnet': 'claude37sonnetthinking',
79
- 'gpt5': 'gpt5',
80
- 'gpt5_thinking': 'gpt5thinking'
81
- },
82
- 'deep research': {
83
- null: 'pplx_alpha'
84
- }
85
- };
86
-
87
- // safe lookup: try to pick the exact key, else fallback to the first available value
88
- const mpForMode = modelPreferences[mode] || modelPreferences.auto;
89
- let modelPref = null;
90
- if (mpForMode) {
91
- // if model is null, treat as null key
92
- if (model == null) modelPref = mpForMode.null ?? Object.values(mpForMode)[0];
93
- else if (Object.prototype.hasOwnProperty.call(mpForMode, model)) modelPref = mpForMode[model];
94
- else {
95
- // invalid model for the chosen mode
96
- const allowed = Object.keys(mpForMode).filter(k => k !== 'null');
97
- throw new Error(`Invalid model '${model}' for mode '${mode}'. Allowed: ${allowed.join(', ') || '<none>'}`);
98
- }
99
- }
100
-
101
- const params = {
102
- attachments: attachmentsFinal,
103
- frontend_context_uuid: cryptoRandomUUID(),
104
- frontend_uuid: cryptoRandomUUID(),
105
- is_incognito: incognito,
106
- language,
107
- last_backend_uuid: follow_up ? follow_up.backend_uuid : null,
108
- mode: mode === 'auto' ? 'concise' : 'copilot',
109
- model_preference: modelPref,
110
- source: 'default',
111
- sources,
112
- version: this.version
113
- };
114
-
115
- return {
116
- query_str: query,
117
- params
118
- };
119
- }
120
-
121
- // Simple helper to generate UUID without depending on node <16 helpers
122
- async _fetch(url, opts) {
123
- const res = await request(url, opts);
124
- const {
125
- statusCode,
126
- headers,
127
- body
128
- } = res;
129
- return {
130
- statusCode,
131
- headers,
132
- body
133
- };
134
- }
135
-
136
- // Supports both: (query, opts) and positional signature:
137
- // search(query, mode='auto', model=null, sources=['web'], files={}, stream=false, language='en-US', follow_up=null, incognito=false)
138
- async search(...args) {
139
- let query;
140
- let opts = {};
141
-
142
- if (args.length === 0) throw new Error('search requires at least a query string');
143
-
144
- query = args[0];
145
-
146
- // If second arg is an object, assume opts form
147
- if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
148
- opts = args[1];
149
- } else if (args.length >= 2) {
150
- // positional mapping for backwards compatibility
151
- const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
152
- opts = {
153
- mode,
154
- model,
155
- sources,
156
- files,
157
- stream,
158
- language,
159
- follow_up,
160
- incognito
161
- };
162
- }
163
-
164
- if (opts.files && Object.keys(opts.files).length) {
165
- throw new Error('File upload support is not implemented in this Node client yet');
166
- }
167
-
168
- const payload = this._buildPayload(query, opts);
169
- const url = `${this.base}/rest/sse/perplexity_ask`;
170
-
171
- const {
172
- statusCode,
173
- headers,
174
- body
175
- } = await this._fetch(url, {
176
- method: 'POST',
177
- body: JSON.stringify(payload),
178
- headers: defaultHeaders(this.cookies)
179
- });
180
-
181
- if (statusCode >= 400) {
182
- const text = await body.text();
183
- const err = new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
184
- err.status = statusCode;
185
- throw err;
186
- }
187
-
188
- // collect SSE messages
189
- const messages = [];
190
- for await (const msg of parseSSE(body)) {
191
- if (msg.event === 'message') {
192
- let data = msg.data;
193
- try {
194
- data = JSON.parse(data);
195
- } catch (e) {}
196
- if (data && data.text) {
197
- try {
198
- data.text = JSON.parse(data.text);
199
- } catch (e) {}
200
- }
201
- messages.push(data);
202
- } else if (msg.event === 'end_of_stream') {
203
- break;
204
- }
205
- }
206
-
207
- return messages.length ? messages[messages.length - 1] : null;
208
- }
209
-
210
- // streamSearch supports same signatures as search
211
- async * streamSearch(...args) {
212
- let query;
213
- let opts = {};
214
-
215
- if (args.length === 0) throw new Error('streamSearch requires at least a query string');
216
-
217
- query = args[0];
218
- if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
219
- opts = args[1];
220
- } else if (args.length >= 2) {
221
- const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
222
- opts = {
223
- mode,
224
- model,
225
- sources,
226
- files,
227
- stream,
228
- language,
229
- follow_up,
230
- incognito
231
- };
232
- }
233
-
234
- if (opts.files && Object.keys(opts.files).length) {
235
- throw new Error('File upload support is not implemented in this Node client yet');
236
- }
237
-
238
- const payload = this._buildPayload(query, opts);
239
- const url = `${this.base}/rest/sse/perplexity_ask`;
240
-
241
- const {
242
- statusCode,
243
- headers,
244
- body
245
- } = await this._fetch(url, {
246
- method: 'POST',
247
- body: JSON.stringify(payload),
248
- headers: defaultHeaders(this.cookies)
249
- });
250
-
251
- if (statusCode >= 400) {
252
- const text = await body.text();
253
- throw new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
254
- }
255
-
256
- for await (const msg of parseSSE(body)) {
257
- if (msg.event === 'message') {
258
- let data = msg.data;
259
- try {
260
- data = JSON.parse(data);
261
- } catch (e) {}
262
- if (data && data.text) {
263
- try {
264
- data.text = JSON.parse(data.text);
265
- } catch (e) {}
266
- }
267
- yield data;
268
- } else if (msg.event === 'end_of_stream') {
269
- return;
270
- }
271
- }
272
- }
273
- }
274
-
275
- function cryptoRandomUUID() {
276
- // Use global crypto if available
277
- if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
278
-
279
- // Fallback simple UUID v4 generator
280
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
281
- const r = Math.random() * 16 | 0;
282
- const v = c === 'x' ? r : (r & 0x3 | 0x8);
283
- return v.toString(16);
284
- });
1
+ import undici from 'undici';
2
+ const { request, fetch, FormData, Blob } = undici;
3
+ import { extname } from 'node:path';
4
+ import { parseSSE } from './sseParser.js';
5
+
6
+ const MODEL_PREFERENCES = {
7
+ auto: { null: 'turbo' },
8
+ pro: {
9
+ null: 'pplx_pro',
10
+ sonar: 'experimental',
11
+ 'gpt-5.2': 'gpt52',
12
+ 'claude-4.5-sonnet': 'claude45sonnet',
13
+ 'grok-4.1': 'grok41nonreasoning'
14
+ },
15
+ reasoning: {
16
+ null: 'pplx_reasoning',
17
+ 'gpt-5.2-thinking': 'gpt52_thinking',
18
+ 'claude-4.5-sonnet-thinking': 'claude45sonnetthinking',
19
+ 'gemini-3.0-pro': 'gemini30pro',
20
+ 'kimi-k2-thinking': 'kimik2thinking',
21
+ 'grok-4.1-reasoning': 'grok41reasoning'
22
+ },
23
+ 'deep research': { null: 'pplx_alpha' }
24
+ };
25
+
26
+ const MIME_MAP = {
27
+ '.txt': 'text/plain',
28
+ '.md': 'text/markdown',
29
+ '.json': 'application/json',
30
+ '.csv': 'text/csv',
31
+ '.pdf': 'application/pdf',
32
+ '.png': 'image/png',
33
+ '.jpg': 'image/jpeg',
34
+ '.jpeg': 'image/jpeg',
35
+ '.gif': 'image/gif',
36
+ '.webp': 'image/webp'
37
+ };
38
+
39
+ function defaultHeaders(cookie, contentType = 'application/json') {
40
+ const headers = {
41
+ accept: 'text/event-stream, text/plain, */*',
42
+ 'content-type': contentType,
43
+ 'user-agent': 'perplexity-js/0.1'
44
+ };
45
+
46
+ if (cookie) headers.cookie = serializeCookies(cookie);
47
+ return headers;
48
+ }
49
+
50
+ function serializeCookies(cookie) {
51
+ if (!cookie) return undefined;
52
+ return typeof cookie === 'string'
53
+ ? cookie
54
+ : Object.entries(cookie)
55
+ .map(([k, v]) => `${k}=${v}`)
56
+ .join('; ');
57
+ }
58
+
59
+ function guessMimeType(filename) {
60
+ const ext = extname(filename).toLowerCase();
61
+ return MIME_MAP[ext] || 'application/octet-stream';
62
+ }
63
+
64
+ function parseFinalAnswer(data) {
65
+ if (!data || !data.text) return data;
66
+
67
+ try {
68
+ const parsedText = typeof data.text === 'string' ? JSON.parse(data.text) : data.text;
69
+ data.text = parsedText;
70
+
71
+ if (Array.isArray(parsedText)) {
72
+ for (const step of parsedText) {
73
+ if (step && step.step_type === 'FINAL') {
74
+ const finalContent = step.content || {};
75
+ if (finalContent.answer) {
76
+ try {
77
+ const answerPayload = JSON.parse(finalContent.answer);
78
+ data.answer = answerPayload.answer ?? '';
79
+ data.chunks = answerPayload.chunks ?? [];
80
+ } catch (err) {
81
+ // swallow JSON parse errors and keep raw
82
+ }
83
+ }
84
+ break;
85
+ }
86
+ }
87
+ }
88
+ } catch (err) {
89
+ // leave data as-is if parsing fails
90
+ }
91
+
92
+ return data;
93
+ }
94
+
95
+ export default class PerplexityClient {
96
+ constructor(options = {}) {
97
+ // Perplexity access is done via session cookies (or anonymously). No API key is required.
98
+ this.base = options.base || 'https://www.perplexity.ai';
99
+ this.version = options.version || '2.18';
100
+ // optional cookies: either string or object map
101
+ this.cookies = options.cookies || null;
102
+ }
103
+
104
+ // Static mapping of modes -> available models
105
+ static getAvailableModels(mode = 'auto') {
106
+ const preferences = MODEL_PREFERENCES[mode] || MODEL_PREFERENCES.auto;
107
+ return Object.keys(preferences).map(k => (k === 'null' ? null : k));
108
+ }
109
+
110
+ // Build the payload for the request
111
+ _buildPayload(query, opts = {}) {
112
+ const {
113
+ mode = 'auto',
114
+ model = null,
115
+ sources = ['web'],
116
+ attachments = [],
117
+ language = 'en-US',
118
+ follow_up = null,
119
+ incognito = false
120
+ } = opts;
121
+
122
+ const attachmentsFinal = attachments.concat(
123
+ follow_up && follow_up.attachments ? follow_up.attachments : []
124
+ );
125
+
126
+ const mpForMode = MODEL_PREFERENCES[mode] || MODEL_PREFERENCES.auto;
127
+ let modelPref = null;
128
+ if (mpForMode) {
129
+ if (model == null) {
130
+ modelPref = mpForMode.null ?? Object.values(mpForMode)[0];
131
+ } else if (Object.prototype.hasOwnProperty.call(mpForMode, model)) {
132
+ modelPref = mpForMode[model];
133
+ } else {
134
+ const allowed = Object.keys(mpForMode)
135
+ .filter(k => k !== 'null')
136
+ .join(', ');
137
+ throw new Error(`Invalid model '${model}' for mode '${mode}'. Allowed: ${allowed || '<none>'}`);
138
+ }
139
+ }
140
+
141
+ const params = {
142
+ attachments: attachmentsFinal,
143
+ frontend_context_uuid: cryptoRandomUUID(),
144
+ frontend_uuid: cryptoRandomUUID(),
145
+ is_incognito: incognito,
146
+ language,
147
+ last_backend_uuid: follow_up ? follow_up.backend_uuid : null,
148
+ mode: mode === 'auto' ? 'concise' : 'copilot',
149
+ model_preference: modelPref,
150
+ source: 'default',
151
+ sources,
152
+ version: this.version
153
+ };
154
+
155
+ return {
156
+ query_str: query,
157
+ params
158
+ };
159
+ }
160
+
161
+ // Simple helper to generate UUID without depending on node <16 helpers
162
+ async _fetch(url, opts) {
163
+ const res = await request(url, opts);
164
+ const { statusCode, headers, body } = res;
165
+ return { statusCode, headers, body };
166
+ }
167
+
168
+ async _postJson(url, body) {
169
+ const res = await fetch(url, {
170
+ method: 'POST',
171
+ headers: defaultHeaders(this.cookies),
172
+ body: JSON.stringify(body)
173
+ });
174
+
175
+ const text = await res.text();
176
+ if (!res.ok) {
177
+ const err = new Error(`Request failed ${res.status} - ${text.slice(0, 200)}`);
178
+ err.status = res.status;
179
+ throw err;
180
+ }
181
+
182
+ return text ? JSON.parse(text) : {};
183
+ }
184
+
185
+ async _uploadFiles(files = {}) {
186
+ const entries = Object.entries(files);
187
+ if (!entries.length) return [];
188
+
189
+ const uploaded = [];
190
+
191
+ for (const [filename, raw] of entries) {
192
+ const mimeType = guessMimeType(filename);
193
+ const data = typeof raw === 'string' ? Buffer.from(raw) : Buffer.from(raw);
194
+ const fileSize = data.byteLength;
195
+
196
+ const uploadInfo = await this._postJson(
197
+ `${this.base}/rest/uploads/create_upload_url?version=${this.version}&source=default`,
198
+ {
199
+ content_type: mimeType,
200
+ file_size: fileSize,
201
+ filename,
202
+ force_image: false,
203
+ source: 'default'
204
+ }
205
+ );
206
+
207
+ const form = new FormData();
208
+ Object.entries(uploadInfo.fields || {}).forEach(([key, value]) => {
209
+ form.append(key, value);
210
+ });
211
+ form.append('file', new Blob([data], { type: mimeType }), filename);
212
+
213
+ const uploadResp = await fetch(uploadInfo.s3_bucket_url, {
214
+ method: 'POST',
215
+ body: form
216
+ });
217
+
218
+ if (!uploadResp.ok) {
219
+ const errText = await uploadResp.text();
220
+ const err = new Error(
221
+ `File upload failed for ${filename}: ${uploadResp.status} - ${errText.slice(0, 200)}`
222
+ );
223
+ err.status = uploadResp.status;
224
+ throw err;
225
+ }
226
+
227
+ let uploadedUrl = uploadInfo.s3_object_url;
228
+ if (uploadedUrl && uploadedUrl.includes('image/upload')) {
229
+ try {
230
+ const uploadBody = await uploadResp.json();
231
+ if (uploadBody.secure_url) {
232
+ uploadedUrl = uploadBody.secure_url.replace(
233
+ /\/private\/s--.*?--\/v\d+\/user_uploads\//,
234
+ '/private/user_uploads/'
235
+ );
236
+ }
237
+ } catch (err) {
238
+ // fall back to provided object url
239
+ }
240
+ }
241
+
242
+ uploaded.push(uploadedUrl);
243
+ }
244
+
245
+ return uploaded;
246
+ }
247
+
248
+ // Supports both: (query, opts) and positional signature:
249
+ // search(query, mode='auto', model=null, sources=['web'], files={}, stream=false, language='en-US', follow_up=null, incognito=false)
250
+ async search(...args) {
251
+ let query;
252
+ let opts = {};
253
+
254
+ if (args.length === 0) throw new Error('search requires at least a query string');
255
+
256
+ query = args[0];
257
+
258
+ // If second arg is an object, assume opts form
259
+ if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
260
+ opts = args[1];
261
+ } else if (args.length >= 2) {
262
+ // positional mapping for backwards compatibility
263
+ const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
264
+ opts = { mode, model, sources, files, stream, language, follow_up, incognito };
265
+ }
266
+
267
+ const uploaded = opts.files && Object.keys(opts.files).length ? await this._uploadFiles(opts.files) : [];
268
+ const payload = this._buildPayload(query, { ...opts, attachments: uploaded });
269
+ const url = `${this.base}/rest/sse/perplexity_ask`;
270
+
271
+ const { statusCode, headers, body } = await this._fetch(url, {
272
+ method: 'POST',
273
+ body: JSON.stringify(payload),
274
+ headers: defaultHeaders(this.cookies)
275
+ });
276
+
277
+ if (statusCode >= 400) {
278
+ const text = await body.text();
279
+ const err = new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
280
+ err.status = statusCode;
281
+ throw err;
282
+ }
283
+
284
+ // collect SSE messages
285
+ const messages = [];
286
+ for await (const msg of parseSSE(body)) {
287
+ if (msg.event === 'message') {
288
+ let data = msg.data;
289
+ try {
290
+ data = JSON.parse(data);
291
+ } catch (e) {}
292
+ messages.push(parseFinalAnswer(data));
293
+ } else if (msg.event === 'end_of_stream') {
294
+ break;
295
+ }
296
+ }
297
+
298
+ return messages.length ? messages[messages.length - 1] : null;
299
+ }
300
+
301
+ // streamSearch supports same signatures as search
302
+ async * streamSearch(...args) {
303
+ let query;
304
+ let opts = {};
305
+
306
+ if (args.length === 0) throw new Error('streamSearch requires at least a query string');
307
+
308
+ query = args[0];
309
+ if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
310
+ opts = args[1];
311
+ } else if (args.length >= 2) {
312
+ const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
313
+ opts = { mode, model, sources, files, stream, language, follow_up, incognito };
314
+ }
315
+
316
+ const uploaded = opts.files && Object.keys(opts.files).length ? await this._uploadFiles(opts.files) : [];
317
+ const payload = this._buildPayload(query, { ...opts, attachments: uploaded });
318
+ const url = `${this.base}/rest/sse/perplexity_ask`;
319
+
320
+ const { statusCode, headers, body } = await this._fetch(url, {
321
+ method: 'POST',
322
+ body: JSON.stringify(payload),
323
+ headers: defaultHeaders(this.cookies)
324
+ });
325
+
326
+ if (statusCode >= 400) {
327
+ const text = await body.text();
328
+ throw new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
329
+ }
330
+
331
+ for await (const msg of parseSSE(body)) {
332
+ if (msg.event === 'message') {
333
+ let data = msg.data;
334
+ try {
335
+ data = JSON.parse(data);
336
+ } catch (e) {}
337
+ yield parseFinalAnswer(data);
338
+ } else if (msg.event === 'end_of_stream') {
339
+ return;
340
+ }
341
+ }
342
+ }
343
+ }
344
+
345
+ function cryptoRandomUUID() {
346
+ // Use global crypto if available
347
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
348
+
349
+ // Fallback simple UUID v4 generator
350
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
351
+ const r = Math.random() * 16 | 0;
352
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
353
+ return v.toString(16);
354
+ });
285
355
  }
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
  }