pendra 0.12.2 → 0.13.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.
package/dist/index.mjs CHANGED
@@ -31,6 +31,33 @@ var RateLimitError = class extends APIStatusError {
31
31
  this.name = "RateLimitError";
32
32
  }
33
33
  };
34
+ var _APIResponseValidationError = class _APIResponseValidationError extends APIError {
35
+ constructor(message, options = {}) {
36
+ const { status, body } = options;
37
+ let text = message;
38
+ if (body) {
39
+ const max = _APIResponseValidationError.BODY_EXCERPT_CHARS;
40
+ text = `${message} (body: ${body.slice(0, max)}${body.length > max ? "\u2026" : ""})`;
41
+ }
42
+ super(text, status);
43
+ this.name = "APIResponseValidationError";
44
+ this.body = body;
45
+ }
46
+ };
47
+ /** How much of the offending body to keep in the message. */
48
+ _APIResponseValidationError.BODY_EXCERPT_CHARS = 200;
49
+ var APIResponseValidationError = _APIResponseValidationError;
50
+ var APIStreamError = class extends APIError {
51
+ constructor(message, options = {}) {
52
+ super(message, typeof options.code === "number" ? options.code : void 0);
53
+ this.name = "APIStreamError";
54
+ this.type = options.type;
55
+ this.code = options.code;
56
+ this.requestId = options.requestId;
57
+ this.workerId = options.workerId;
58
+ this.workerName = options.workerName;
59
+ }
60
+ };
34
61
 
35
62
  // src/resources/audio/transcriptions.ts
36
63
  var MAX_FILE_SIZE = 25 * 1024 * 1024;
@@ -160,6 +187,89 @@ var Audio = class {
160
187
  }
161
188
  };
162
189
 
190
+ // src/_parsing.ts
191
+ function asString(v) {
192
+ return typeof v === "string" ? v : void 0;
193
+ }
194
+ function throwIfInBandError(parsed) {
195
+ if (typeof parsed !== "object" || parsed === null) return;
196
+ const err = parsed.error;
197
+ if (typeof err !== "object" || err === null || Array.isArray(err)) return;
198
+ const e = err;
199
+ throw new APIStreamError(
200
+ asString(e.message) ?? "The server reported an error mid-stream",
201
+ {
202
+ type: asString(e.type),
203
+ code: typeof e.code === "number" ? e.code : void 0,
204
+ requestId: asString(e.request_id),
205
+ workerId: asString(e.worker_id),
206
+ workerName: asString(e.worker_name)
207
+ }
208
+ );
209
+ }
210
+ function isChunkShaped(parsed) {
211
+ if (typeof parsed !== "object" || parsed === null) return false;
212
+ const c = parsed;
213
+ return typeof c.id === "string" && typeof c.model === "string" && Array.isArray(c.choices);
214
+ }
215
+ function parseStreamFrame(data, label = "Stream frame") {
216
+ let parsed;
217
+ try {
218
+ parsed = JSON.parse(data);
219
+ } catch {
220
+ throw new APIResponseValidationError(`${label} was not valid JSON`, { body: data });
221
+ }
222
+ throwIfInBandError(parsed);
223
+ if (!isChunkShaped(parsed)) {
224
+ throw new APIResponseValidationError(`${label} was not a chat completion chunk`, {
225
+ body: data
226
+ });
227
+ }
228
+ return parsed;
229
+ }
230
+ function completionFrom(parsed, body, status) {
231
+ if (typeof parsed !== "object" || parsed === null) {
232
+ throw new APIResponseValidationError("Response was not a chat completion", { status, body });
233
+ }
234
+ const c = parsed;
235
+ if (typeof c.id !== "string" || typeof c.model !== "string" || !Array.isArray(c.choices)) {
236
+ throw new APIResponseValidationError("Response was not a chat completion", { status, body });
237
+ }
238
+ return parsed;
239
+ }
240
+ async function parseCompletion(response) {
241
+ const body = await response.text();
242
+ let parsed;
243
+ try {
244
+ parsed = JSON.parse(body);
245
+ } catch {
246
+ throw new APIResponseValidationError("Response was not valid JSON", {
247
+ status: response.status,
248
+ body
249
+ });
250
+ }
251
+ return completionFrom(parsed, body, response.status);
252
+ }
253
+ function parseDecryptedCompletion(json, status) {
254
+ let parsed;
255
+ try {
256
+ parsed = JSON.parse(json);
257
+ } catch {
258
+ throw new APIResponseValidationError("Decrypted response was not valid JSON", {
259
+ status,
260
+ body: json
261
+ });
262
+ }
263
+ try {
264
+ return completionFrom(parsed, json, status);
265
+ } catch {
266
+ throw new APIResponseValidationError("Decrypted response was not a chat completion", {
267
+ status,
268
+ body: json
269
+ });
270
+ }
271
+ }
272
+
163
273
  // src/_sse.ts
164
274
  var DEFAULT_EVENT = "message";
165
275
  function fieldValue(line, name) {
@@ -229,7 +339,7 @@ var SseDecoder = class {
229
339
 
230
340
  // src/streaming.ts
231
341
  var Stream = class {
232
- constructor(response, controller) {
342
+ constructor(response, controller, idleTimeoutMs) {
233
343
  this.decoder = new TextDecoder();
234
344
  this.sse = new SseDecoder();
235
345
  this.done = false;
@@ -238,21 +348,22 @@ var Stream = class {
238
348
  }
239
349
  this.reader = response.body.getReader();
240
350
  this.controller = controller;
351
+ this.idleTimeoutMs = idleTimeoutMs;
241
352
  }
242
353
  async *[Symbol.asyncIterator]() {
243
354
  try {
244
355
  while (!this.done) {
245
- const { value, done: readerDone } = await this.reader.read();
356
+ const { value, done: readerDone } = await readWithIdleTimeout(
357
+ this.reader,
358
+ this.idleTimeoutMs
359
+ );
246
360
  const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
247
361
  for (const data of payloads) {
248
362
  if (data === "[DONE]") {
249
363
  this.done = true;
250
364
  return;
251
365
  }
252
- try {
253
- yield JSON.parse(data);
254
- } catch {
255
- }
366
+ yield parseStreamFrame(data);
256
367
  }
257
368
  if (readerDone) {
258
369
  this.done = true;
@@ -260,7 +371,7 @@ var Stream = class {
260
371
  }
261
372
  }
262
373
  } finally {
263
- this.reader.releaseLock();
374
+ releaseReader(this.reader, this.controller, this.done);
264
375
  }
265
376
  }
266
377
  abort() {
@@ -268,11 +379,34 @@ var Stream = class {
268
379
  this.controller.abort();
269
380
  }
270
381
  };
382
+ async function readWithIdleTimeout(reader, idleTimeoutMs) {
383
+ if (!idleTimeoutMs) return reader.read();
384
+ let timer;
385
+ const idle = new Promise((_, reject) => {
386
+ timer = setTimeout(
387
+ () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
388
+ idleTimeoutMs
389
+ );
390
+ });
391
+ try {
392
+ return await Promise.race([reader.read(), idle]);
393
+ } finally {
394
+ clearTimeout(timer);
395
+ }
396
+ }
397
+ function releaseReader(reader, controller, finished) {
398
+ if (!finished) {
399
+ controller.abort();
400
+ reader.cancel().catch(() => {
401
+ });
402
+ }
403
+ reader.releaseLock();
404
+ }
271
405
 
272
406
  // src/_privateStreaming.ts
273
407
  var DECODER = new TextDecoder();
274
408
  var EncryptedStream = class {
275
- constructor(response, controller, decryptor) {
409
+ constructor(response, controller, decryptor, idleTimeoutMs) {
276
410
  this.decoder = new TextDecoder();
277
411
  this.sse = new SseDecoder();
278
412
  this.done = false;
@@ -282,26 +416,31 @@ var EncryptedStream = class {
282
416
  this.reader = response.body.getReader();
283
417
  this.controller = controller;
284
418
  this.decryptor = decryptor;
419
+ this.idleTimeoutMs = idleTimeoutMs;
285
420
  }
286
421
  async *[Symbol.asyncIterator]() {
287
422
  try {
288
423
  while (!this.done) {
289
- const { value, done: readerDone } = await this.reader.read();
424
+ const { value, done: readerDone } = await readWithIdleTimeout(
425
+ this.reader,
426
+ this.idleTimeoutMs
427
+ );
290
428
  const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
291
429
  for (const data of payloads) {
292
430
  if (data === "[DONE]") {
293
431
  this.done = true;
294
432
  return;
295
433
  }
296
- let parsed;
434
+ let inner;
297
435
  try {
298
- parsed = JSON.parse(data);
436
+ inner = JSON.parse(data).pendra_encrypted;
299
437
  } catch {
300
- continue;
438
+ throw new APIResponseValidationError("Stream frame was not valid JSON", {
439
+ body: data
440
+ });
301
441
  }
302
- const inner = parsed.pendra_encrypted;
303
442
  if (!inner) {
304
- yield parsed;
443
+ yield parseStreamFrame(data);
305
444
  continue;
306
445
  }
307
446
  const plain = this.decryptor.openChunk(inner);
@@ -313,10 +452,7 @@ var EncryptedStream = class {
313
452
  }
314
453
  continue;
315
454
  }
316
- try {
317
- yield JSON.parse(chunkJson);
318
- } catch {
319
- }
455
+ yield parseStreamFrame(chunkJson, "Decrypted stream frame");
320
456
  }
321
457
  if (readerDone) {
322
458
  this.done = true;
@@ -324,7 +460,7 @@ var EncryptedStream = class {
324
460
  }
325
461
  }
326
462
  } finally {
327
- this.reader.releaseLock();
463
+ releaseReader(this.reader, this.controller, this.done);
328
464
  }
329
465
  }
330
466
  abort() {
@@ -353,15 +489,15 @@ var Completions = class {
353
489
  if (params.stream) {
354
490
  const { response: response2, controller } = await this.client._fetch(
355
491
  "/api/v1/chat/completions",
356
- { method: "POST", body, stream: true, headers }
492
+ { method: "POST", body, headers }
357
493
  );
358
- return new Stream(response2, controller);
494
+ return new Stream(response2, controller, this.client.timeout);
359
495
  }
360
496
  const { response } = await this.client._fetch(
361
497
  "/api/v1/chat/completions",
362
498
  { method: "POST", body, headers }
363
499
  );
364
- return await response.json();
500
+ return parseCompletion(response);
365
501
  }
366
502
  async createEncrypted(params, body, headers) {
367
503
  const engine = await this.client._privateEngine();
@@ -376,20 +512,29 @@ var Completions = class {
376
512
  if (stream) {
377
513
  const { response: response2, controller } = await this.client._fetch(
378
514
  "/api/v1/chat/completions",
379
- { method: "POST", body: topLevel, stream: true, headers }
515
+ { method: "POST", body: topLevel, headers }
380
516
  );
381
- return new EncryptedStream(response2, controller, decryptor);
517
+ return new EncryptedStream(response2, controller, decryptor, this.client.timeout);
382
518
  }
383
519
  const { response } = await this.client._fetch(
384
520
  "/api/v1/chat/completions",
385
521
  { method: "POST", body: topLevel, headers }
386
522
  );
387
- const wrapper = await response.json();
523
+ const raw = await response.text();
524
+ let wrapper;
525
+ try {
526
+ wrapper = JSON.parse(raw);
527
+ } catch {
528
+ throw new APIResponseValidationError("Response was not valid JSON", {
529
+ status: response.status,
530
+ body: raw
531
+ });
532
+ }
388
533
  if (!wrapper.pendra_encrypted) {
389
- return wrapper;
534
+ return parseDecryptedCompletion(raw, response.status);
390
535
  }
391
536
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
392
- return JSON.parse(DECODER2.decode(plain));
537
+ return parseDecryptedCompletion(DECODER2.decode(plain), response.status);
393
538
  }
394
539
  };
395
540
 
@@ -623,7 +768,7 @@ var Rerank = class {
623
768
  };
624
769
 
625
770
  // src/version.ts
626
- var VERSION = "0.12.2";
771
+ var VERSION = "0.13.1";
627
772
  var USER_AGENT = `pendra-node/${VERSION}`;
628
773
 
629
774
  // src/_hpke.ts
@@ -1314,11 +1459,8 @@ var Pendra = class {
1314
1459
  err instanceof Error ? err.message : "Failed to connect to the Pendra API"
1315
1460
  );
1316
1461
  }
1317
- if (!options.stream) {
1318
- clearTimeout(timeoutId);
1319
- }
1462
+ clearTimeout(timeoutId);
1320
1463
  if (!response.ok) {
1321
- clearTimeout(timeoutId);
1322
1464
  this.invalidateKeyCacheIfRekeyed(response);
1323
1465
  let message;
1324
1466
  try {
@@ -1360,7 +1502,9 @@ var index_default = Pendra;
1360
1502
  export {
1361
1503
  APIConnectionError,
1362
1504
  APIError,
1505
+ APIResponseValidationError,
1363
1506
  APIStatusError,
1507
+ APIStreamError,
1364
1508
  AuthenticationError,
1365
1509
  Pendra,
1366
1510
  PrivateInferenceError,