pendra 0.15.1 → 0.16.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/dist/index.d.mts CHANGED
@@ -748,15 +748,31 @@ declare class APIError extends Error {
748
748
  declare class APIConnectionError extends APIError {
749
749
  constructor(message?: string);
750
750
  }
751
+ interface APIStatusErrorOptions {
752
+ /** The parsed JSON body, or the raw text when it wasn't JSON. */
753
+ body?: unknown;
754
+ /** The body's `detail` field as the API sent it (string, array or object). */
755
+ detail?: unknown;
756
+ }
757
+ /**
758
+ * Raised when the API returns a non-2xx response.
759
+ *
760
+ * `message` is always a readable string. The response stays available for
761
+ * callers that want to act on its structure: `body` is the parsed JSON body (or
762
+ * the raw text when it wasn't JSON), and `detail` is the body's `detail` field
763
+ * as sent — an array or object for validation and structured errors.
764
+ */
751
765
  declare class APIStatusError extends APIError {
752
766
  readonly status: number;
753
- constructor(message: string, status: number);
767
+ readonly body: unknown;
768
+ readonly detail: unknown;
769
+ constructor(message: string, status: number, options?: APIStatusErrorOptions);
754
770
  }
755
771
  declare class AuthenticationError extends APIStatusError {
756
- constructor(message?: string);
772
+ constructor(message?: string, options?: APIStatusErrorOptions);
757
773
  }
758
774
  declare class RateLimitError extends APIStatusError {
759
- constructor(message?: string);
775
+ constructor(message?: string, options?: APIStatusErrorOptions);
760
776
  }
761
777
  /**
762
778
  * Raised when a response arrives but isn't the shape the SDK expects.
@@ -812,4 +828,4 @@ declare class APIStreamError extends APIError {
812
828
  });
813
829
  }
814
830
 
815
- export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
831
+ export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, type APIStatusErrorOptions, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
package/dist/index.d.ts CHANGED
@@ -748,15 +748,31 @@ declare class APIError extends Error {
748
748
  declare class APIConnectionError extends APIError {
749
749
  constructor(message?: string);
750
750
  }
751
+ interface APIStatusErrorOptions {
752
+ /** The parsed JSON body, or the raw text when it wasn't JSON. */
753
+ body?: unknown;
754
+ /** The body's `detail` field as the API sent it (string, array or object). */
755
+ detail?: unknown;
756
+ }
757
+ /**
758
+ * Raised when the API returns a non-2xx response.
759
+ *
760
+ * `message` is always a readable string. The response stays available for
761
+ * callers that want to act on its structure: `body` is the parsed JSON body (or
762
+ * the raw text when it wasn't JSON), and `detail` is the body's `detail` field
763
+ * as sent — an array or object for validation and structured errors.
764
+ */
751
765
  declare class APIStatusError extends APIError {
752
766
  readonly status: number;
753
- constructor(message: string, status: number);
767
+ readonly body: unknown;
768
+ readonly detail: unknown;
769
+ constructor(message: string, status: number, options?: APIStatusErrorOptions);
754
770
  }
755
771
  declare class AuthenticationError extends APIStatusError {
756
- constructor(message?: string);
772
+ constructor(message?: string, options?: APIStatusErrorOptions);
757
773
  }
758
774
  declare class RateLimitError extends APIStatusError {
759
- constructor(message?: string);
775
+ constructor(message?: string, options?: APIStatusErrorOptions);
760
776
  }
761
777
  /**
762
778
  * Raised when a response arrives but isn't the shape the SDK expects.
@@ -812,4 +828,4 @@ declare class APIStreamError extends APIError {
812
828
  });
813
829
  }
814
830
 
815
- export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
831
+ export { APIConnectionError, APIError, APIResponseValidationError, APIStatusError, type APIStatusErrorOptions, APIStreamError, type AudioFileInput, AuthenticationError, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionCreateParams, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type Choice, type ChoiceDelta, type CompletionTokensDetails, type CreateEmbeddingResponse, type Embedding, type EmbeddingCreateParams, type EmbeddingUsage, type ImageData, type ImageGenerationCreateParams, type ImageResponse, type Model, Pendra, type PendraExtension, type PendraNotice, type PendraOptions, type PendraTiming, type PendraWebToolStep, PrivateInferenceError, RateLimitError, type RerankCreateParams, type RerankResponse, type RerankResult, type RerankResultDocument, Stream, type StreamChoice, type TranscriptionCreateParams, type TranscriptionResponse, type TranscriptionSegment, type Usage, Pendra as default };
package/dist/index.js CHANGED
@@ -59,21 +59,23 @@ var APIConnectionError = class extends APIError {
59
59
  }
60
60
  };
61
61
  var APIStatusError = class extends APIError {
62
- constructor(message, status) {
62
+ constructor(message, status, options = {}) {
63
63
  super(message, status);
64
64
  this.name = "APIStatusError";
65
65
  this.status = status;
66
+ this.body = options.body;
67
+ this.detail = options.detail;
66
68
  }
67
69
  };
68
70
  var AuthenticationError = class extends APIStatusError {
69
- constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY") {
70
- super(message, 401);
71
+ constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY", options = {}) {
72
+ super(message, 401, options);
71
73
  this.name = "AuthenticationError";
72
74
  }
73
75
  };
74
76
  var RateLimitError = class extends APIStatusError {
75
- constructor(message = "Rate limit exceeded") {
76
- super(message, 429);
77
+ constructor(message = "Rate limit exceeded", options = {}) {
78
+ super(message, 429, options);
77
79
  this.name = "RateLimitError";
78
80
  }
79
81
  };
@@ -104,6 +106,80 @@ var APIStreamError = class extends APIError {
104
106
  this.workerName = options.workerName;
105
107
  }
106
108
  };
109
+ var LOC_SOURCES = /* @__PURE__ */ new Set(["body", "query", "path", "header", "cookie"]);
110
+ function isRecord(value) {
111
+ return typeof value === "object" && value !== null && !Array.isArray(value);
112
+ }
113
+ function nonEmptyString(value) {
114
+ return typeof value === "string" && value ? value : void 0;
115
+ }
116
+ function compactJson(value) {
117
+ try {
118
+ return JSON.stringify(value) ?? String(value);
119
+ } catch {
120
+ return String(value);
121
+ }
122
+ }
123
+ function messageFromItem(item) {
124
+ if (isRecord(item)) {
125
+ const msg = nonEmptyString(item.msg) ?? nonEmptyString(item.message);
126
+ if (msg) {
127
+ let field = typeof item.field === "string" ? item.field : void 0;
128
+ if (field === void 0) {
129
+ const loc = Array.isArray(item.loc) ? [...item.loc] : [];
130
+ if (loc.length && LOC_SOURCES.has(String(loc[0]))) loc.shift();
131
+ field = loc.map(String).join(".");
132
+ }
133
+ return field ? `${field}: ${msg}` : msg;
134
+ }
135
+ }
136
+ return messageFromDetail(item);
137
+ }
138
+ function messageFromDetail(detail) {
139
+ if (detail === void 0 || detail === null) return void 0;
140
+ if (typeof detail === "string") return detail || void 0;
141
+ if (Array.isArray(detail)) {
142
+ const parts = detail.map(messageFromItem).filter((p) => !!p);
143
+ return parts.length ? parts.join("; ") : void 0;
144
+ }
145
+ if (isRecord(detail)) {
146
+ const err = detail.error;
147
+ const nested = isRecord(err) ? nonEmptyString(err.message) : void 0;
148
+ const msg = nested ?? nonEmptyString(detail.message) ?? nonEmptyString(detail.msg);
149
+ if (msg) return msg;
150
+ return Object.keys(detail).length ? compactJson(detail) : void 0;
151
+ }
152
+ return compactJson(detail);
153
+ }
154
+ async function readErrorBody(response) {
155
+ let raw;
156
+ try {
157
+ raw = await response.text();
158
+ } catch {
159
+ return void 0;
160
+ }
161
+ if (!raw) return void 0;
162
+ try {
163
+ return JSON.parse(raw);
164
+ } catch {
165
+ return raw;
166
+ }
167
+ }
168
+ function statusErrorFromBody(status, body, fallback) {
169
+ const detail = isRecord(body) ? body.detail : void 0;
170
+ const err = isRecord(body) ? body.error : void 0;
171
+ let message = (isRecord(err) ? nonEmptyString(err.message) : void 0) ?? messageFromDetail(detail) ?? (isRecord(body) ? nonEmptyString(body.message) : void 0);
172
+ if (message === void 0) {
173
+ if (typeof body === "string") message = body || fallback;
174
+ else if (Array.isArray(body) ? body.length : isRecord(body) && Object.keys(body).length) {
175
+ message = compactJson(body);
176
+ } else message = fallback;
177
+ }
178
+ const options = { body, detail };
179
+ if (status === 401) return new AuthenticationError(message, options);
180
+ if (status === 429) return new RateLimitError(message, options);
181
+ return new APIStatusError(message, status, options);
182
+ }
107
183
 
108
184
  // src/_privateInference.ts
109
185
  var import_chacha2 = require("@noble/ciphers/chacha.js");
@@ -620,21 +696,6 @@ function asBlob(file) {
620
696
  }
621
697
  return { blob: new Blob([content]), filename };
622
698
  }
623
- async function extractErrorDetail(response) {
624
- let raw = "";
625
- try {
626
- raw = await response.text();
627
- } catch {
628
- return response.statusText;
629
- }
630
- if (!raw) return response.statusText;
631
- try {
632
- const body = JSON.parse(raw);
633
- return body.detail ?? body.error?.message ?? raw;
634
- } catch {
635
- return raw;
636
- }
637
- }
638
699
  var Transcriptions = class {
639
700
  constructor(client) {
640
701
  this.client = client;
@@ -692,14 +753,8 @@ var Transcriptions = class {
692
753
  }
693
754
  clearTimeout(timeoutId);
694
755
  if (response.status >= 400) {
695
- const detail = await extractErrorDetail(response);
696
- if (response.status === 401) {
697
- throw new AuthenticationError(detail);
698
- }
699
- if (response.status === 429) {
700
- throw new RateLimitError(detail);
701
- }
702
- throw new APIStatusError(detail, response.status);
756
+ const body = await readErrorBody(response);
757
+ throw statusErrorFromBody(response.status, body, response.statusText);
703
758
  }
704
759
  const format = params.response_format;
705
760
  if (format === "text" || format === "srt" || format === "vtt") {
@@ -1331,7 +1386,7 @@ var Rerank = class {
1331
1386
  };
1332
1387
 
1333
1388
  // src/version.ts
1334
- var VERSION = "0.15.1";
1389
+ var VERSION = "0.16.0";
1335
1390
  var USER_AGENT = `pendra-node/${VERSION}`;
1336
1391
 
1337
1392
  // src/_privateInferenceEngine.ts
@@ -1341,6 +1396,25 @@ var PrivateInferenceError = class extends Error {
1341
1396
  this.name = "PrivateInferenceError";
1342
1397
  }
1343
1398
  };
1399
+ var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
1400
+ function parsePinnedFingerprints(pin) {
1401
+ if (typeof pin !== "string") {
1402
+ throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
1403
+ }
1404
+ const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1405
+ if (fps.length === 0) {
1406
+ throw new PrivateInferenceError(
1407
+ "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
1408
+ );
1409
+ }
1410
+ const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
1411
+ if (bad.length > 0) {
1412
+ throw new PrivateInferenceError(
1413
+ `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
1414
+ );
1415
+ }
1416
+ return new Set(fps);
1417
+ }
1344
1418
  function defaultTofuPath() {
1345
1419
  const env = typeof process !== "undefined" ? process.env : void 0;
1346
1420
  if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
@@ -1359,8 +1433,8 @@ var PrivateInferenceEngine = class {
1359
1433
  this.orgPubs = null;
1360
1434
  this.baseUrl = opts.baseUrl.replace(/\/$/, "");
1361
1435
  this.apiKey = opts.apiKey;
1362
- const fps = (opts.pinnedFingerprint || "").split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1363
- this.pinnedFingerprints = fps.length > 0 ? new Set(fps) : null;
1436
+ const pin = opts.pinnedFingerprint;
1437
+ this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
1364
1438
  this.affinitySalt = opts.affinitySalt ?? null;
1365
1439
  this.tofuPath = opts.tofuPath || defaultTofuPath();
1366
1440
  }
@@ -1556,12 +1630,19 @@ var Pendra = class {
1556
1630
  }
1557
1631
  let pinnedFingerprint;
1558
1632
  if (typeof piOpt === "object" && piOpt !== null) {
1633
+ for (const key of Object.keys(piOpt)) {
1634
+ if (key !== "pinnedFingerprint") {
1635
+ throw new TypeError(
1636
+ `Unknown privateInference option "${key}". Accepted options: pinnedFingerprint.`
1637
+ );
1638
+ }
1639
+ }
1559
1640
  this.privateInferenceEnabled = true;
1560
1641
  pinnedFingerprint = piOpt.pinnedFingerprint;
1561
1642
  } else {
1562
1643
  this.privateInferenceEnabled = Boolean(piOpt);
1563
1644
  }
1564
- pinnedFingerprint = pinnedFingerprint ?? env?.PENDRA_PINNED_ORG_FINGERPRINT ?? void 0;
1645
+ pinnedFingerprint = pinnedFingerprint ?? (env?.PENDRA_PINNED_ORG_FINGERPRINT || void 0);
1565
1646
  if (this.privateInferenceEnabled) {
1566
1647
  const affinitySalt = env?.PENDRA_AFFINITY_SALT ? new TextEncoder().encode(env.PENDRA_AFFINITY_SALT) : null;
1567
1648
  this._piEngine = new PrivateInferenceEngine({
@@ -1629,19 +1710,7 @@ var Pendra = class {
1629
1710
  );
1630
1711
  }
1631
1712
  if (!response.ok) {
1632
- let message;
1633
- try {
1634
- const body = await response.json();
1635
- if (typeof body.detail === "string") message = body.detail;
1636
- else if (typeof body.error?.message === "string") message = body.error.message;
1637
- else if (body.detail != null) message = JSON.stringify(body.detail);
1638
- else message = response.statusText;
1639
- } catch {
1640
- message = response.statusText;
1641
- }
1642
- if (response.status === 401) throw new AuthenticationError(message);
1643
- if (response.status === 429) throw new RateLimitError(message);
1644
- throw new APIStatusError(message, response.status);
1713
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
1645
1714
  }
1646
1715
  const json = await response.json();
1647
1716
  await engine.resolveOrgKey(json.keys ?? []);
@@ -1679,19 +1748,7 @@ var Pendra = class {
1679
1748
  clearTimeout(timeoutId);
1680
1749
  if (!response.ok) {
1681
1750
  this.invalidateKeyCacheIfRekeyed(response);
1682
- let message;
1683
- try {
1684
- const body = await response.json();
1685
- if (typeof body.detail === "string") message = body.detail;
1686
- else if (typeof body.error?.message === "string") message = body.error.message;
1687
- else if (body.detail != null) message = JSON.stringify(body.detail);
1688
- else message = response.statusText;
1689
- } catch {
1690
- message = response.statusText;
1691
- }
1692
- if (response.status === 401) throw new AuthenticationError(message);
1693
- if (response.status === 429) throw new RateLimitError(message);
1694
- throw new APIStatusError(message, response.status);
1751
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
1695
1752
  }
1696
1753
  return { response, controller };
1697
1754
  }