@foxnose/sdk 0.6.0 → 0.7.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.js CHANGED
@@ -93,6 +93,36 @@ var PlanExhaustedError = class extends FoxnoseAPIError {
93
93
  this.upgradeUrl = options.upgradeUrl;
94
94
  }
95
95
  };
96
+ var FilesQuotaExceededError = class extends FoxnoseAPIError {
97
+ axis;
98
+ reason;
99
+ usedUnits;
100
+ includedUnits;
101
+ capUsd;
102
+ windowResetsAt;
103
+ upgradeUrl;
104
+ raiseCapUrl;
105
+ constructor(options) {
106
+ super(options);
107
+ this.name = "FilesQuotaExceededError";
108
+ this.axis = options.axis;
109
+ this.reason = options.reason;
110
+ this.usedUnits = options.usedUnits;
111
+ this.includedUnits = options.includedUnits;
112
+ this.capUsd = options.capUsd;
113
+ this.windowResetsAt = options.windowResetsAt;
114
+ this.upgradeUrl = options.upgradeUrl;
115
+ this.raiseCapUrl = options.raiseCapUrl;
116
+ }
117
+ };
118
+ var FilesQuotaUnavailableError = class extends FoxnoseAPIError {
119
+ retryAfter;
120
+ constructor(options) {
121
+ super(options);
122
+ this.name = "FilesQuotaUnavailableError";
123
+ this.retryAfter = options.retryAfter;
124
+ }
125
+ };
96
126
  var PlanLimitExceededError = class extends FoxnoseAPIError {
97
127
  /** Entity whose limit was exceeded (e.g. collections, environments, api_keys). */
98
128
  entity;
@@ -165,6 +195,12 @@ function getHeader(headers, name) {
165
195
  }
166
196
  return void 0;
167
197
  }
198
+ function retryAfterSeconds(headers) {
199
+ const raw = getHeader(headers, "Retry-After");
200
+ const parsed = raw !== void 0 ? Number(raw) : NaN;
201
+ return Number.isNaN(parsed) ? void 0 : parsed;
202
+ }
203
+ var CONTENT_VALIDATION_CODES = /* @__PURE__ */ new Set(["content_validation_failed", "data_validation_error"]);
168
204
  function buildAPIError(options) {
169
205
  const { statusCode, errorCode, detail, responseHeaders, responseBody } = options;
170
206
  const body = isPlainObject(responseBody) ? responseBody : void 0;
@@ -186,6 +222,29 @@ function buildAPIError(options) {
186
222
  upgradeUrl: typeof body.upgrade_url === "string" ? body.upgrade_url : void 0
187
223
  });
188
224
  }
225
+ if (statusCode === 402 && errorCode === "files_quota_exceeded" && body) {
226
+ const numberOrNull = (value) => typeof value === "number" ? value : value === null ? null : void 0;
227
+ const text = (value) => typeof value === "string" ? value : void 0;
228
+ return new FilesQuotaExceededError({
229
+ ...options,
230
+ message: "message" in body ? options.message : "File processing quota reached",
231
+ axis: text(body.axis),
232
+ reason: text(body.reason),
233
+ usedUnits: typeof body.used_units === "number" ? body.used_units : void 0,
234
+ includedUnits: numberOrNull(body.included_units),
235
+ capUsd: numberOrNull(body.cap_usd),
236
+ windowResetsAt: body.window_resets_at === null ? null : text(body.window_resets_at),
237
+ upgradeUrl: text(body.upgrade_url),
238
+ raiseCapUrl: text(body.raise_cap_url)
239
+ });
240
+ }
241
+ if (statusCode === 503 && errorCode === "files_quota_unavailable") {
242
+ return new FilesQuotaUnavailableError({
243
+ ...options,
244
+ message: body && "message" in body ? options.message : "File processing quota is unavailable",
245
+ retryAfter: retryAfterSeconds(responseHeaders)
246
+ });
247
+ }
189
248
  if (statusCode === 403 && errorCode === "plan_limit_exceeded") {
190
249
  const d = isPlainObject(detail) ? detail : {};
191
250
  return new PlanLimitExceededError({
@@ -197,11 +256,9 @@ function buildAPIError(options) {
197
256
  });
198
257
  }
199
258
  if (statusCode === 429 && errorCode === "rate_limited") {
200
- const raw = getHeader(responseHeaders, "Retry-After");
201
- const parsed = raw !== void 0 ? Number(raw) : NaN;
202
259
  return new RateLimitExceededError({
203
260
  ...options,
204
- retryAfter: Number.isNaN(parsed) ? void 0 : parsed
261
+ retryAfter: retryAfterSeconds(responseHeaders)
205
262
  });
206
263
  }
207
264
  if (statusCode === 403 && errorCode === "collection_not_writable") {
@@ -210,7 +267,7 @@ function buildAPIError(options) {
210
267
  if (statusCode === 409 && errorCode === "external_id_conflict") {
211
268
  return new ExternalIdConflictError(options);
212
269
  }
213
- if (statusCode === 422 && errorCode === "content_validation_failed") {
270
+ if (statusCode === 422 && CONTENT_VALIDATION_CODES.has(errorCode)) {
214
271
  const d = isPlainObject(detail) ? detail : {};
215
272
  const errors = Array.isArray(d.errors) ? d.errors : typeof d.json_path === "string" ? [d] : [];
216
273
  return new ContentValidationFailedError({
@@ -308,7 +365,7 @@ var DEFAULT_RETRY_CONFIG = {
308
365
  statusCodes: [408, 425, 429, 500, 502, 503, 504],
309
366
  methods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]
310
367
  };
311
- var SDK_VERSION = "0.6.0";
368
+ var SDK_VERSION = "0.7.0";
312
369
  var DEFAULT_USER_AGENT = `foxnose-sdk-js/${SDK_VERSION}`;
313
370
  function createConfig(options) {
314
371
  if (!options.baseUrl) {
@@ -492,7 +549,7 @@ var HttpTransport = class {
492
549
  body = payload;
493
550
  if (payload && typeof payload === "object" && !Array.isArray(payload)) {
494
551
  message = payload.message ?? message;
495
- errorCode = payload.error_code;
552
+ errorCode = payload.error_code ?? payload.code;
496
553
  detail = payload.detail;
497
554
  }
498
555
  } catch {
@@ -549,6 +606,26 @@ function nestedFieldMeta(opts) {
549
606
  auto_update: opts.autoUpdate ?? false
550
607
  };
551
608
  }
609
+ var TEXT_EVIDENCE_KINDS = /* @__PURE__ */ new Set(["hidden_text", "low_legibility_text"]);
610
+ function parseFindingEvidence(finding) {
611
+ if (!TEXT_EVIDENCE_KINDS.has(finding.kind) || !finding.evidence) {
612
+ return null;
613
+ }
614
+ let fields;
615
+ try {
616
+ fields = JSON.parse(finding.evidence);
617
+ } catch {
618
+ return null;
619
+ }
620
+ if (typeof fields !== "object" || fields === null || Array.isArray(fields)) {
621
+ return null;
622
+ }
623
+ const { parts } = fields;
624
+ if (parts !== void 0 && !Array.isArray(parts)) {
625
+ return null;
626
+ }
627
+ return { ...fields, parts: parts ?? [] };
628
+ }
552
629
  function resolveKey(value) {
553
630
  if (typeof value === "string") {
554
631
  return value;
@@ -588,6 +665,15 @@ function managementPaths(environmentKey) {
588
665
  // Resource paths
589
666
  resourceBase: (folderKey) => `/v1/${environmentKey}/folders/${folderKey}/resources`,
590
667
  revisionBase: (folderKey, resourceKey) => `/v1/${environmentKey}/folders/${folderKey}/resources/${resourceKey}/revisions`,
668
+ // Files paths
669
+ uploadLinksRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/upload-links`,
670
+ uploadLinkRoot: (collectionKey, uploadId) => `/v1/${environmentKey}/collections/${collectionKey}/upload-links/${encodeURIComponent(uploadId)}`,
671
+ fileRoot: (collectionKey, resourceKey) => `/v1/${environmentKey}/collections/${collectionKey}/files/${resourceKey}`,
672
+ fileTombstonesRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/files/tombstones`,
673
+ filesPolicyRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/files-policy`,
674
+ filesReviewRoot: () => `/v1/${environmentKey}/files/review`,
675
+ // Caller's own permissions
676
+ myPermissionsRoot: () => `/v1/${environmentKey}/permissions/me`,
591
677
  // Management API key paths
592
678
  managementApiKeysRoot: () => `/v1/${environmentKey}/permissions/management-api/api-keys`,
593
679
  managementApiKeyRoot: (apiKey) => `/v1/${environmentKey}/permissions/management-api/api-keys/${apiKey}`,
@@ -696,6 +782,14 @@ var ManagementClient = class {
696
782
  const key = resolveKey(orgKey);
697
783
  return this.request("PUT", `${this.paths.orgRoot(key)}/`, { jsonBody: payload });
698
784
  }
785
+ /**
786
+ * Write the given fields of an organization and leave the rest alone. The
787
+ * response is the whole organization as stored.
788
+ */
789
+ async patchOrganization(orgKey, payload) {
790
+ const key = resolveKey(orgKey);
791
+ return this.request("PATCH", `${this.paths.orgRoot(key)}/`, { jsonBody: payload });
792
+ }
699
793
  async listRegions() {
700
794
  const payload = await this.request("GET", "/regions/") ?? [];
701
795
  return Array.isArray(payload) ? payload : [payload];
@@ -1110,6 +1204,20 @@ var ManagementClient = class {
1110
1204
  jsonBody: payload
1111
1205
  });
1112
1206
  }
1207
+ /**
1208
+ * Write the given fields of a collection and leave the rest alone.
1209
+ *
1210
+ * `updateCollection` replaces the whole record; this does not. An omitted
1211
+ * `parent` keeps the collection where it is, and `{ parent: null }` moves it
1212
+ * to the root. The response is the whole collection as stored.
1213
+ */
1214
+ async patchCollection(collectionKey, payload) {
1215
+ const key = resolveKey(collectionKey);
1216
+ return this.request("PATCH", `${this.paths.collectionsTreeItem()}/`, {
1217
+ params: { key },
1218
+ jsonBody: payload
1219
+ });
1220
+ }
1113
1221
  async deleteCollection(collectionKey) {
1114
1222
  const key = resolveKey(collectionKey);
1115
1223
  await this.request("DELETE", `${this.paths.collectionsTreeItem()}/`, {
@@ -1447,6 +1555,14 @@ var ManagementClient = class {
1447
1555
  const key = resolveKey(componentKey);
1448
1556
  return this.request("PUT", `${this.paths.componentRoot(key)}/`, { jsonBody: payload });
1449
1557
  }
1558
+ /**
1559
+ * Write the given fields of a component and leave the rest alone. The response
1560
+ * is the whole component as stored.
1561
+ */
1562
+ async patchComponent(componentKey, payload) {
1563
+ const key = resolveKey(componentKey);
1564
+ return this.request("PATCH", `${this.paths.componentRoot(key)}/`, { jsonBody: payload });
1565
+ }
1450
1566
  async deleteComponent(componentKey) {
1451
1567
  const key = resolveKey(componentKey);
1452
1568
  await this.request("DELETE", `${this.paths.componentRoot(key)}/`, { parseJson: false });
@@ -1832,6 +1948,159 @@ var ManagementClient = class {
1832
1948
  protectionLevel: "none"
1833
1949
  });
1834
1950
  }
1951
+ // ------------------------------------------------------------------ //
1952
+ // Files
1953
+ // ------------------------------------------------------------------ //
1954
+ /**
1955
+ * List a files collection's upload links, newest first. `params` carries `limit` (at
1956
+ * most 100), `offset` and `state`: `active`, `ended` or `all` (the default).
1957
+ */
1958
+ async listUploadLinks(collectionKey, params) {
1959
+ const key = resolveKey(collectionKey);
1960
+ return this.request("GET", `${this.paths.uploadLinksRoot(key)}/`, { params });
1961
+ }
1962
+ /**
1963
+ * Create an upload link: a hosted page where an end user adds files.
1964
+ *
1965
+ * The collection must be strict. Works with a user token or a Management API
1966
+ * key of this environment. Read the link back with {@link getUploadLink}; the
1967
+ * Flux upload status answers only the Flux key that started an upload, never
1968
+ * a link made here.
1969
+ *
1970
+ * `upload_url` carries the link's token and is returned only by this call.
1971
+ */
1972
+ async createUploadLink(collectionKey, request) {
1973
+ const key = resolveKey(collectionKey);
1974
+ return this.transport.request("POST", `${this.paths.uploadLinksRoot(key)}/`, {
1975
+ jsonBody: { ...request, owner: resolveKey(request.owner) },
1976
+ allowRetries: false
1977
+ });
1978
+ }
1979
+ /** Read one upload link with its sessions and the status of each file. */
1980
+ async getUploadLink(collectionKey, uploadId) {
1981
+ const key = resolveKey(collectionKey);
1982
+ return this.request("GET", `${this.paths.uploadLinkRoot(key, uploadId)}/`);
1983
+ }
1984
+ /**
1985
+ * Revoke an upload link. Revoking a revoked link returns the same state. Files
1986
+ * already uploaded through the link are not affected.
1987
+ */
1988
+ async revokeUploadLink(collectionKey, uploadId) {
1989
+ const key = resolveKey(collectionKey);
1990
+ return this.request("POST", `${this.paths.uploadLinkRoot(key, uploadId)}/revoke/`);
1991
+ }
1992
+ /** Read a record's file: its verdict, the checks that ran and every finding. */
1993
+ async getFileAnalysis(collectionKey, resourceKey) {
1994
+ const root = this.fileRoot(collectionKey, resourceKey);
1995
+ return this.request("GET", `${root}/analysis/`);
1996
+ }
1997
+ /**
1998
+ * Release a file held for a reviewer.
1999
+ *
2000
+ * The answer's `outcome` says what happened; a publish that goes back through
2001
+ * processing completes on its own. A file no reviewer holds is
2002
+ * `409 file_not_in_review`, `file_not_ready` or `file_erased`.
2003
+ */
2004
+ async approveFile(collectionKey, resourceKey) {
2005
+ const root = this.fileRoot(collectionKey, resourceKey);
2006
+ return this.transport.request("POST", `${root}/approve/`, { allowRetries: false });
2007
+ }
2008
+ /** Reject a file held for a reviewer. Repeating it returns the same state. */
2009
+ async rejectFile(collectionKey, resourceKey) {
2010
+ const root = this.fileRoot(collectionKey, resourceKey);
2011
+ return this.request("POST", `${root}/reject/`);
2012
+ }
2013
+ /**
2014
+ * Analyze a file again under the collection's live policy.
2015
+ *
2016
+ * Accepted work runs in the background; a published generation keeps serving
2017
+ * until the new one publishes. A `storage_only` collection answers
2018
+ * `409 reanalysis_requires_agent_ready`. This is paid processing: a refusal over
2019
+ * the plan throws {@link FilesQuotaExceededError}, a quota that cannot be read
2020
+ * throws {@link FilesQuotaUnavailableError}, and over a budget is `429`.
2021
+ */
2022
+ async reanalyzeFile(collectionKey, resourceKey) {
2023
+ const root = this.fileRoot(collectionKey, resourceKey);
2024
+ return this.transport.request("POST", `${root}/reanalyze/`, { allowRetries: false });
2025
+ }
2026
+ /**
2027
+ * Get a short-lived link to a record's original file.
2028
+ *
2029
+ * A state that cannot be downloaded now is a `409`: `detail.reason` of the
2030
+ * thrown error names it. Check `warnings` before opening the file.
2031
+ */
2032
+ async getFileOriginal(collectionKey, resourceKey) {
2033
+ const root = this.fileRoot(collectionKey, resourceKey);
2034
+ return this.request("GET", `${root}/file/original/`);
2035
+ }
2036
+ /**
2037
+ * Get a short-lived link to a record's safe copy. It is an image-only PDF, or a PNG
2038
+ * for an image: read `content_type`.
2039
+ */
2040
+ async getFileSafeCopy(collectionKey, resourceKey) {
2041
+ const root = this.fileRoot(collectionKey, resourceKey);
2042
+ return this.request("GET", `${root}/file/safe-copy/`);
2043
+ }
2044
+ /** Get a short-lived link to the redacted PNG of one page. */
2045
+ async getFilePage(collectionKey, resourceKey, page) {
2046
+ const root = this.fileRoot(collectionKey, resourceKey);
2047
+ return this.request("GET", `${root}/file/pages/${page}/`);
2048
+ }
2049
+ /**
2050
+ * Read one page: its redacted image, what was withheld, its tables and the
2051
+ * text an agent receives.
2052
+ */
2053
+ async getFilePageDetail(collectionKey, resourceKey, page) {
2054
+ const root = this.fileRoot(collectionKey, resourceKey);
2055
+ return this.request("GET", `${root}/file/pages/${page}/detail/`);
2056
+ }
2057
+ /** List a collection's blocked and rejected files, newest first. */
2058
+ async listFileTombstones(collectionKey, params) {
2059
+ const key = resolveKey(collectionKey);
2060
+ return this.request("GET", `${this.paths.fileTombstonesRoot(key)}/`, { params });
2061
+ }
2062
+ /** Read a collection's live files policy. */
2063
+ async getFilesPolicy(collectionKey) {
2064
+ const key = resolveKey(collectionKey);
2065
+ return this.request("GET", `${this.paths.filesPolicyRoot(key)}/`);
2066
+ }
2067
+ /**
2068
+ * Replace a collection's files policy with a new version.
2069
+ *
2070
+ * A full replacement: an omitted field takes its default. Sending the live
2071
+ * body again creates no version.
2072
+ */
2073
+ async updateFilesPolicy(collectionKey, payload) {
2074
+ const key = resolveKey(collectionKey);
2075
+ return this.request("PUT", `${this.paths.filesPolicyRoot(key)}/`, { jsonBody: payload });
2076
+ }
2077
+ /**
2078
+ * List the files held for a reviewer in this environment, newest first.
2079
+ *
2080
+ * `collection` narrows the queue to one collection; one the caller cannot read,
2081
+ * or that does not exist, is an empty page. `params` carries `limit` (at most
2082
+ * 100) and `offset`.
2083
+ */
2084
+ async listFileReviewQueue(options) {
2085
+ const params = { ...options?.params };
2086
+ if (options?.collection !== void 0) {
2087
+ params.collection = resolveKey(options.collection);
2088
+ }
2089
+ return this.request("GET", `${this.paths.filesReviewRoot()}/`, { params });
2090
+ }
2091
+ /**
2092
+ * Read what the authenticated caller may do in this environment.
2093
+ *
2094
+ * Works for a user token and for a Management API key of this environment. A caller
2095
+ * with no grants at all is a `403`; a key of another environment is a
2096
+ * `404 environment_not_found`.
2097
+ */
2098
+ async getMyPermissions() {
2099
+ return this.request("GET", `${this.paths.myPermissionsRoot()}/`);
2100
+ }
2101
+ fileRoot(collectionKey, resourceKey) {
2102
+ return this.paths.fileRoot(resolveKey(collectionKey), resolveKey(resourceKey));
2103
+ }
1835
2104
  };
1836
2105
 
1837
2106
  // src/flux/models.ts
@@ -2082,6 +2351,45 @@ var FluxClient = class {
2082
2351
  const path = this.buildPath(folderPath, `/${resourceKey}/`);
2083
2352
  return this.transport.request("PUT", path, { jsonBody: { data }, allowRetries: false });
2084
2353
  }
2354
+ /**
2355
+ * Get a grant for one upload to a files collection.
2356
+ *
2357
+ * The grant is a credential: pass it on, do not log it. For a strict collection
2358
+ * `folderPath` names the owner, e.g. `support/tickets/tk_1/attachments`. Needs a
2359
+ * key with create access to the collection.
2360
+ *
2361
+ * `options.sessionKey` is an optional idempotency key of 43 URL-safe characters:
2362
+ * a repeat with the same key, collection and owner reaches the same upload
2363
+ * session. A failed request is never retried automatically, so send one to
2364
+ * retry safely.
2365
+ */
2366
+ async createUploadSignature(folderPath, options) {
2367
+ const path = this.buildPath(folderPath, "/_upload-signature");
2368
+ const sessionKey = options?.sessionKey;
2369
+ return this.transport.request("POST", path, {
2370
+ jsonBody: sessionKey === void 0 ? void 0 : { session_key: sessionKey },
2371
+ allowRetries: false
2372
+ });
2373
+ }
2374
+ /**
2375
+ * Read the status of an upload.
2376
+ *
2377
+ * A key reads the uploads that key started, and the path must name the same
2378
+ * collection and owner. Any other combination is `404 not_found`, which includes
2379
+ * a link made through the Management API: read that one with
2380
+ * `ManagementClient.getUploadLink`.
2381
+ *
2382
+ * `options.statusToken` is the end user's token from the grant, for a client that
2383
+ * holds no key (use `AnonymousAuth`). It answers the end user's view, which never
2384
+ * carries a record key. A request authenticated by a key ignores it.
2385
+ */
2386
+ async getUploadStatus(folderPath, uploadId, options) {
2387
+ const path = this.buildPath(folderPath, `/_uploads/${encodeURIComponent(uploadId)}`);
2388
+ const statusToken = options?.statusToken;
2389
+ return this.transport.request("GET", path, {
2390
+ headers: statusToken === void 0 ? void 0 : { "X-Upload-Status-Token": statusToken }
2391
+ });
2392
+ }
2085
2393
  /** Semantic search using auto-generated embeddings. */
2086
2394
  async vectorSearch(folderPath, options) {
2087
2395
  const {
@@ -2230,6 +2538,8 @@ export {
2230
2538
  DEFAULT_RETRY_CONFIG,
2231
2539
  DEFAULT_USER_AGENT,
2232
2540
  ExternalIdConflictError,
2541
+ FilesQuotaExceededError,
2542
+ FilesQuotaUnavailableError,
2233
2543
  FluxClient,
2234
2544
  FoxnoseAPIError,
2235
2545
  FoxnoseAuthError,
@@ -2252,6 +2562,7 @@ export {
2252
2562
  buildSearchBody,
2253
2563
  createConfig,
2254
2564
  nestedFieldMeta,
2565
+ parseFindingEvidence,
2255
2566
  resolveKey
2256
2567
  };
2257
2568
  //# sourceMappingURL=index.js.map