conare 0.23.0 → 0.24.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/README.md CHANGED
@@ -61,11 +61,11 @@ for await (const doc of docs.list()) {} // every document, page by page (
61
61
  await docs.delete("refunds"); // 404 document_not_found if it does not exist
62
62
  await docs.deleteMany(["a", "b"]); // up to 1000 ids in one call; missing ids are skipped. Returns the count
63
63
  await docs.deleteWhere({ team: "support" }); // every document matching the filter, whole documents. Returns the count
64
- await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page), a .docx (Markdown), a .pptx (one per slide)
65
- // or an .xlsx (Markdown tables per sheet), up to 20 MiB. The same name (or { id }) again replaces it.
66
- // Returns { fileId, type, ids, pages, sheets, slides, slidesWithoutText, pagesOcr, pagesWithoutText, ocrPending }:
67
- // scanned pages are OCR'd after the answer (ocrPending; { wait: true } reads them first)
68
- await docs.getFile("report.pdf"); // that upload's outcome, OCR after the answer included (kept 7 days)
64
+ await docs.uploadFile(bytes, "report.pdf"); // any file up to 512 MiB in one call: a PDF (one document per page), a .docx, a .pptx
65
+ // (one per slide), an .xlsx (Markdown tables per sheet), CSV, text or images; scans are OCR'd.
66
+ // Documents are <sourceId>:<fileId>:<part>; the same name (or { id }) again replaces them.
67
+ // { user, metadata, type, wait } optional. Returns { state, fileId, ids, markdown, parts, ... }
68
+ await docs.getFile("report.pdf"); // its state; once ready, its documents and parse
69
69
  await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
70
70
 
71
71
  await conare.namespaces(); // [{ name, documents }]
@@ -203,26 +203,6 @@ await conare.events.list({ cursor: "0", types: ["run.*"] }); // { data: [{ seq,
203
203
  `sources.list()` and `sources.get()` answer custom sources too, with `kind: "custom"`. These
204
204
  calls send an `Idempotency-Key` when they create or delete something, so their retries are safe.
205
205
 
206
- ### Files
207
-
208
- A PDF, Word document, PowerPoint deck, Excel workbook, CSV, text or image file becomes documents, one
209
- per page, sheet part, slide or Word part, each citing where it came from (`page`; `sheet` and `rows`;
210
- `slide`; `heading` and `part`) in its metadata. Parsing runs in the background; every page without a
211
- usable text layer (a scan, an image) is read by OCR, and a page OCR could not read is listed in
212
- `ocrFailed`, never left out silently. Declare the `type` when you know it: the file is parsed as that
213
- type, and bytes of another type are a `ConareError` 415 `type_mismatch`.
214
-
215
- ```ts
216
- const { file } = await conare.files.upload({ file: bytes, name: "Q3 report.pdf", namespace: "kb", type: "pdf",
217
- metadata: { deal: "acme" } }); // up to 64 MiB in one request, up to 512 MiB in 16 MiB parts
218
- const [ready] = await conare.files.waitUntilReady({ namespace: "kb", ids: [file.id] });
219
- // { state: "ready", pages, pagesText, pagesOcr, pagesWithoutText, ocrFailed, documents, locators, ... }
220
- await conare.files.status({ namespace: "kb", ids: [file.id] });
221
- await conare.files.reparse(file.id, { namespace: "kb" }); // again, from the stored original
222
- ```
223
-
224
- The same bytes and metadata again answer `result: "unchanged"`: nothing is parsed or embedded.
225
-
226
206
  ### Errors
227
207
 
228
208
  Every failure is a `ConareError` with `status`, `code`, `message` and `requestId`
package/dist/cli/scrub.js CHANGED
@@ -39,7 +39,19 @@ const RULES = [
39
39
  re: /\bsk-[A-Za-z0-9][A-Za-z0-9_-]{19,}/g,
40
40
  accept: (s) => hasDigit(s) && (/[A-Z]/.test(s) || s.length >= 35),
41
41
  },
42
+ // Stripe and WorkOS secret and restricted keys (sk_live_, sk_test_, rk_…), Stripe webhook secrets.
43
+ { kind: "api_key", re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}/g, accept: hasDigit },
44
+ { kind: "webhook_secret", re: /\bwhsec_[A-Za-z0-9+/=]{24,}/g, accept: hasDigit },
42
45
  { kind: "github_token", re: /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})/g },
46
+ { kind: "gitlab_token", re: /\bglpat-[A-Za-z0-9_-]{20,}/g },
47
+ { kind: "npm_token", re: /\bnpm_[A-Za-z0-9]{36}\b/g, accept: hasDigit },
48
+ { kind: "pypi_token", re: /\bpypi-AgE[A-Za-z0-9_-]{50,}/g },
49
+ { kind: "sendgrid_key", re: /\bSG\.[A-Za-z0-9_-]{20,24}\.[A-Za-z0-9_-]{40,46}/g },
50
+ // Google OAuth access tokens (ya29.…) and refresh tokens (1//0…).
51
+ { kind: "google_oauth_token", re: /\bya29\.[A-Za-z0-9_-]{20,}/g },
52
+ { kind: "google_oauth_token", re: /(?<![\w/])1\/\/0[A-Za-z0-9_-]{30,}/g },
53
+ // A GCP service-account key file's private_key_id (40 hex); its private_key is a PEM block.
54
+ { kind: "private_key_id", re: /(\bprivate_key_id["']?\s*[:=]\s*["']?)([a-f0-9]{40})\b/g, label: true },
43
55
  { kind: "aws_access_key", re: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g },
44
56
  { kind: "slack_token", re: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g },
45
57
  { kind: "google_api_key", re: /\bAIza[0-9A-Za-z_-]{35}/g },
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.23.0";
1
+ export declare const VERSION = "0.24.0";
2
2
  /** A metadata value: string, number, boolean or an array of strings. */
3
3
  export type MetadataValue = string | number | boolean | string[];
4
4
  export type Metadata = Record<string, MetadataValue>;
@@ -170,9 +170,11 @@ export interface ParseFailed {
170
170
  /** What `uploadFile` stored. */
171
171
  export interface FileUpload {
172
172
  fileId: string;
173
- /** The whole document as `parse` answers it, once OCR is done (null while `ocr`, or for a file read in the background). */
173
+ /** `unchanged`: the same bytes, name and options as the file's last parse; nothing was parsed again. */
174
+ result?: "unchanged";
175
+ /** The whole document as `parse` answers it, once `ready` (null before). */
174
176
  markdown: string | null;
175
- /** Its parts as `parse` answers them (empty while `ocr`, or for a file read in the background). */
177
+ /** Its parts as `parse` answers them, once `ready` (empty before). */
176
178
  parts: ParsePart[];
177
179
  /** The type it was read as: an image of any format is `image`. */
178
180
  type: "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "image";
@@ -186,26 +188,22 @@ export interface FileUpload {
186
188
  slides: number | null;
187
189
  /** A deck's slides with no text (pictures only): not stored. */
188
190
  slidesWithoutText: number[];
189
- /** PDF or image pages read by OCR before the answer (`wait: true`); stored like the rest. */
191
+ /** PDF or image pages read by OCR; stored like the rest. */
190
192
  pagesOcr: number;
191
- /** Pictures of a Word document or deck read by OCR before the answer (`wait: true`), each a document of its own. */
193
+ /** Pictures of a Word document or deck read by OCR, each a document of its own. */
192
194
  imagesOcr: number;
193
195
  /** Pictures of a Word document or deck OCR did not turn into text, each with where it is and why. */
194
196
  imagesWithoutText: PictureWithoutText[];
195
197
  /** PDF pages with no text even after OCR (blank, or OCR could not read them): not stored. */
196
198
  pagesWithoutText: number[];
197
- /**
198
- * PDF pages OCR reads after the answer (without `wait`): each is stored, marked `ocr`, within about a minute.
199
- * `getFile(fileId)` says when OCR ended and which of them it could not read.
200
- */
199
+ /** Pages waiting for OCR to try them again (`state: "ocr"`). */
201
200
  ocrPending: number[];
202
201
  /**
203
- * `ready`: every document is stored. `ocr`: pages are still being read by OCR (`ocrPending`). `queued`,
204
- * `parsing`: a large file (over 20 MiB, or over 100 pages for OCR) read in the background; follow it with
205
- * `getFile(fileId)`. `failed`: the background read failed (`error`).
202
+ * `queued`, `parsing`: the parse runs; follow it with `getFile(fileId)`. `ocr`: stored, with pages OCR tries
203
+ * again (`ocrPending`). `ready`: every document is stored. `failed`: the parse failed (`error`).
206
204
  */
207
205
  state: "queued" | "parsing" | "ocr" | "ready" | "failed";
208
- /** Read in the background: the namespace's files source; its documents are `<sourceId>:<fileId>:<part>`. */
206
+ /** The files source of the namespace (and user): its documents are `<sourceId>:<fileId>:<part>`. */
209
207
  sourceId: string | null;
210
208
  /** Everything the file stored no text for, in one place (`pagesWithoutText`, `slidesWithoutText` and `imagesWithoutText` say the same). */
211
209
  withoutText: WithoutText;
@@ -215,7 +213,7 @@ export interface FileUpload {
215
213
  message: string;
216
214
  } | null;
217
215
  }
218
- /** What `getFile` reads: an upload's outcome, with OCR after the answer folded in as it ends. */
216
+ /** What `getFile` reads: a file's latest upload. */
219
217
  export interface FileStatus extends FileUpload {
220
218
  /** The file's name as uploaded. */
221
219
  name: string;
@@ -525,78 +523,6 @@ export declare class ConareError extends Error {
525
523
  readonly requestId: string | null;
526
524
  constructor(status: number, code: string, message: string, requestId?: string | null);
527
525
  }
528
- /** A file of `files.upload`, as `files.status` reads it. */
529
- export interface StoredFile {
530
- /** The file's id in its namespace (and user). */
531
- id: string;
532
- name: string;
533
- namespace: string;
534
- user: string | null;
535
- /** The namespace's files source: the file's documents are `<sourceId>:<id>:<part>`. */
536
- sourceId: string;
537
- /** What it was parsed as: pdf, xlsx, docx, pptx, csv, tsv, txt, md or image. */
538
- type: string | null;
539
- /** Whether the type was declared rather than recognized. */
540
- declared: boolean;
541
- bytes: number;
542
- sha256: string | null;
543
- metadata: Metadata;
544
- /** `ocr`: pages are being read by OCR, or wait to be tried again. */
545
- state: "queued" | "parsing" | "ocr" | "ready" | "failed";
546
- /** PDF pages, sheets, slides, Word parts or image frames. */
547
- pages: number;
548
- /** Pages stored from their text layer. */
549
- pagesText: number;
550
- /** Pages read by OCR with text. */
551
- pagesOcr: number;
552
- /** Every page this parse stored no text for: blank, read as empty, unreadable, or without a text layer and not read by OCR. */
553
- pagesWithoutText: number[];
554
- /** Pages waiting for OCR. */
555
- ocrPending: number;
556
- /** Pages OCR could not read after its retries; each keeps what an earlier upload stored for it. */
557
- ocrFailed: number[];
558
- /** Pages no reader can open because the file is damaged there, each with why; not tried again. */
559
- pagesUnreadable: {
560
- page: number;
561
- reason: string;
562
- }[];
563
- documents: number;
564
- /** Parts the write refused, each with why. */
565
- rejected: {
566
- id: string;
567
- code: string;
568
- message: string;
569
- }[];
570
- /** The locator fields its documents carry: page, sheet, rows, slide, heading, part, frame. */
571
- locators: string[];
572
- /** Pictures of a Word document or deck OCR did not turn into text, each with where it is and why. */
573
- imagesWithoutText: PictureWithoutText[];
574
- chunksEmbedded: number;
575
- /** The file's latest parse. */
576
- run: {
577
- id: string;
578
- kind: "parse" | "reparse";
579
- state: string;
580
- phase: string | null;
581
- error: unknown;
582
- retryAt?: Date;
583
- };
584
- /** When `failed`: `{ code, message }`. */
585
- error: {
586
- code: string;
587
- message: string;
588
- } | null;
589
- updatedAt: Date;
590
- }
591
- /** What `files.upload` and `files.reparse` answer. */
592
- export interface FileQueued {
593
- /** `unchanged`: the same bytes and metadata as the file's last parse; nothing was queued. */
594
- result?: "unchanged";
595
- file: StoredFile;
596
- run?: Run;
597
- }
598
- /** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
599
- export declare const MAX_FILE_REQUEST_BYTES: number;
600
526
  /**
601
527
  * The Conare client.
602
528
  *
@@ -610,8 +536,6 @@ export declare class Conare {
610
536
  readonly runs: Runs;
611
537
  /** Files of documents written into a custom source. */
612
538
  readonly imports: Imports;
613
- /** Files (PDF, Word, PowerPoint, Excel, CSV, text, images) kept as documents, a page each. */
614
- readonly files: Files;
615
539
  /** Delete everything Conare holds of one of your users. */
616
540
  readonly users: Users;
617
541
  /** What changed, in order. */
@@ -705,35 +629,31 @@ export declare class Namespace {
705
629
  */
706
630
  write(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<WriteResult[]>;
707
631
  /**
708
- * Store a PDF, a Word document (.docx), a PowerPoint deck (.pptx), an Excel workbook (.xlsx), a CSV or
709
- * TSV, a text or Markdown file, or an image (PNG, JPEG, WebP, TIFF), at most 20 MiB. Say its type with
710
- * `type`: it is read as that type, and bytes of another type are refused (415) rather than misread;
711
- * without it the type comes from the bytes, then the name. One document per PDF page with a text
712
- * layer (`<fileId>:page-3`), per image page (read by OCR), a CSV as Markdown tables with its header
713
- * on every part and the rows each holds in `rows` metadata, a Word document as
714
- * Markdown (`<fileId>:part-1`, more parts past 240 KiB), one per slide with text (`<fileId>:slide-2`:
715
- * title, shapes in reading order, tables, speaker notes) and Markdown tables per worksheet
716
- * (`<fileId>:Sheet1-1`), each with `file`, `file_id`, `file_type` and `page`, `part`, `slide` or
717
- * `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
718
- * name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
719
- * such names do not collide); uploading the same one again replaces every document it made, and two
720
- * uploads of one id run one at a time. The answer also holds what `parse` answers (`markdown`, `parts`,
721
- * `withoutText`), and takes its options (`pages`, `password`, `layout`, `wait`). Pages with something on them
722
- * are read by OCR: the answer waits `wait` seconds for it (default 60); pages it still reads then are in
723
- * `ocrPending` (`state: "ocr"`, stored within about a minute; `wait: false` answers once the text layers are
724
- * stored). Pages with no text even then are listed in `withoutText.pages` and not stored. Any file up to 512 MiB
725
- * goes in this one call: one over 20 MiB, or with more than 100 pages for OCR, is read in the background and
726
- * answers `state` `queued` or `parsing` (follow it with `getFile`), or `ready` once done within `wait`.
632
+ * Store a file, up to 512 MiB, in one call: a PDF, a Word document (.docx), a PowerPoint deck (.pptx),
633
+ * an Excel workbook (.xlsx), a CSV or TSV, a text or Markdown file, or an image (PNG, JPEG, WebP,
634
+ * TIFF). Say its type with `type`: it is read as that type, and bytes of another type are refused (415)
635
+ * rather than misread; without it the type comes from the bytes, then the name. It is parsed into one
636
+ * document per PDF page, image page, slide, Word part or worksheet part, each `<sourceId>:<fileId>:<part>`
637
+ * (`sourceId` is the namespace's files source) with `file`, `file_id`, `file_type` and its locator
638
+ * (`page`, `part`, `slide`, `sheet`, `rows`) in metadata, beside `metadata` of your own. Pages without
639
+ * a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading the same one
640
+ * again replaces every document it made, and the same bytes, name and options again answer
641
+ * `result: "unchanged"`. `user` keeps the file to one of your users. The answer waits `wait` seconds
642
+ * (default 60) for the parse: once `ready` it holds what `parse` answers (`markdown`, `parts`,
643
+ * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
727
644
  */
728
645
  uploadFile(file: Blob | Uint8Array | ArrayBuffer, name: string, options?: RequestOptions & ParseOptions & {
729
646
  id?: string;
647
+ user?: string;
648
+ metadata?: Metadata;
730
649
  }): Promise<FileUpload>;
731
650
  /**
732
- * An upload's outcome: the last upload of `fileId` here in the last 7 days. While OCR reads after the
733
- * answer, `ocrPending` lists its pages; once it ended, the pages it read are in `ids` and `pagesOcr`, and
734
- * those it could not read in `pagesWithoutText`. A file id with no upload throws 404 `file_not_found`.
651
+ * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its documents
652
+ * and its parse (`markdown`, `parts`). An id with no file throws 404 `file_not_found`.
735
653
  */
736
- getFile(fileId: string, options?: RequestOptions): Promise<FileStatus>;
654
+ getFile(fileId: string, options?: RequestOptions & {
655
+ user?: string;
656
+ }): Promise<FileStatus>;
737
657
  /**
738
658
  * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
739
659
  * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
@@ -948,50 +868,6 @@ export declare class Imports {
948
868
  filename?: string;
949
869
  }, options?: RequestOptions): Promise<Run>;
950
870
  }
951
- export declare class Files {
952
- private readonly client;
953
- constructor(client: Conare);
954
- /**
955
- * Upload a file: it is stored and parsed in the background into a document per page, sheet part,
956
- * slide or Word part, each citing where it came from; pages without text are read by OCR. Declare
957
- * its `type` when you know it: it is then parsed as that type, and bytes of another type are a
958
- * ConareError 415 `type_mismatch`. Up to 64 MiB goes in one request, larger files (up to 512 MiB)
959
- * in parts of 16 MiB. `wait` (seconds, at most 100) holds the answer until the file is ready.
960
- */
961
- upload(params: {
962
- file: Blob | Uint8Array | ArrayBuffer | string;
963
- name: string;
964
- namespace: string;
965
- user?: string;
966
- id?: string;
967
- type?: FileType;
968
- metadata?: Metadata;
969
- wait?: number;
970
- }, options?: RequestOptions): Promise<FileQueued>;
971
- /** The files `ids` of a namespace (and user), or, without ids, its first 100 files. */
972
- status(params: {
973
- namespace: string;
974
- user?: string;
975
- ids?: string[];
976
- }, options?: RequestOptions): Promise<StoredFile[]>;
977
- /** Parse a file again from its stored original. */
978
- reparse(id: string, params: {
979
- namespace: string;
980
- user?: string;
981
- wait?: number;
982
- }, options?: RequestOptions): Promise<FileQueued>;
983
- /**
984
- * Wait until every file of `ids` is ready or failed (polling `status` every `interval` ms), at most
985
- * `timeout` ms (10 minutes by default): the files as they ended, or a ConareError `timeout`.
986
- */
987
- waitUntilReady(params: {
988
- namespace: string;
989
- user?: string;
990
- ids: string[];
991
- timeout?: number;
992
- interval?: number;
993
- }, options?: RequestOptions): Promise<StoredFile[]>;
994
- }
995
871
  export declare class Users {
996
872
  private readonly client;
997
873
  constructor(client: Conare);
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
2
- export const VERSION = "0.23.0";
2
+ export const VERSION = "0.24.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  // A JSON body this long or longer goes gzip-encoded: past the first ~14 KB a new connection may send,
@@ -35,6 +35,7 @@ function parseQuery(options) {
35
35
  function toFileUpload(body) {
36
36
  const pending = body.ocr_pending ?? [];
37
37
  return {
38
+ ...(body.result ? { result: body.result } : {}),
38
39
  state: body.state ?? (pending.length > 0 ? "ocr" : "ready"),
39
40
  sourceId: body.source_id ?? null,
40
41
  withoutText: {
@@ -104,23 +105,6 @@ function queryBody(query, options) {
104
105
  hops: options.hops,
105
106
  };
106
107
  }
107
- /** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
108
- export const MAX_FILE_REQUEST_BYTES = 64 * 1024 * 1024;
109
- function toStoredFile(f) {
110
- return {
111
- id: f.id, name: f.name, namespace: f.namespace, user: f.user, sourceId: f.source_id, type: f.type, declared: f.declared,
112
- bytes: f.bytes, sha256: f.sha256, metadata: f.metadata ?? {}, state: f.state, pages: f.pages, pagesText: f.pages_text,
113
- pagesOcr: f.pages_ocr, pagesWithoutText: f.pages_without_text ?? [], ocrPending: f.ocr_pending, ocrFailed: f.ocr_failed ?? [],
114
- pagesUnreadable: f.pages_unreadable ?? [], documents: f.documents, rejected: f.rejected ?? [], locators: f.locators ?? [], chunksEmbedded: f.chunks_embedded ?? 0,
115
- imagesWithoutText: f.images_without_text ?? [],
116
- run: { id: f.run.id, kind: f.run.kind, state: f.run.state, phase: f.run.phase, error: f.run.error,
117
- ...(f.run.retry_at ? { retryAt: new Date(f.run.retry_at) } : {}) },
118
- error: f.error ?? null, updatedAt: new Date(f.updated_at),
119
- };
120
- }
121
- function toFileQueued(body) {
122
- return { ...(body.result ? { result: body.result } : {}), file: toStoredFile(body.file), ...(body.run ? { run: toRun(body.run) } : {}) };
123
- }
124
108
  // ---- Client ----------------------------------------------------------------
125
109
  /**
126
110
  * The Conare client.
@@ -135,8 +119,6 @@ export class Conare {
135
119
  runs;
136
120
  /** Files of documents written into a custom source. */
137
121
  imports;
138
- /** Files (PDF, Word, PowerPoint, Excel, CSV, text, images) kept as documents, a page each. */
139
- files;
140
122
  /** Delete everything Conare holds of one of your users. */
141
123
  users;
142
124
  /** What changed, in order. */
@@ -168,7 +150,6 @@ export class Conare {
168
150
  this.sources = new Sources(this);
169
151
  this.runs = new Runs(this);
170
152
  this.imports = new Imports(this);
171
- this.files = new Files(this);
172
153
  this.users = new Users(this);
173
154
  this.events = new Events(this);
174
155
  }
@@ -398,40 +379,39 @@ export class Namespace {
398
379
  return out;
399
380
  }
400
381
  /**
401
- * Store a PDF, a Word document (.docx), a PowerPoint deck (.pptx), an Excel workbook (.xlsx), a CSV or
402
- * TSV, a text or Markdown file, or an image (PNG, JPEG, WebP, TIFF), at most 20 MiB. Say its type with
403
- * `type`: it is read as that type, and bytes of another type are refused (415) rather than misread;
404
- * without it the type comes from the bytes, then the name. One document per PDF page with a text
405
- * layer (`<fileId>:page-3`), per image page (read by OCR), a CSV as Markdown tables with its header
406
- * on every part and the rows each holds in `rows` metadata, a Word document as
407
- * Markdown (`<fileId>:part-1`, more parts past 240 KiB), one per slide with text (`<fileId>:slide-2`:
408
- * title, shapes in reading order, tables, speaker notes) and Markdown tables per worksheet
409
- * (`<fileId>:Sheet1-1`), each with `file`, `file_id`, `file_type` and `page`, `part`, `slide` or
410
- * `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
411
- * name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
412
- * such names do not collide); uploading the same one again replaces every document it made, and two
413
- * uploads of one id run one at a time. The answer also holds what `parse` answers (`markdown`, `parts`,
414
- * `withoutText`), and takes its options (`pages`, `password`, `layout`, `wait`). Pages with something on them
415
- * are read by OCR: the answer waits `wait` seconds for it (default 60); pages it still reads then are in
416
- * `ocrPending` (`state: "ocr"`, stored within about a minute; `wait: false` answers once the text layers are
417
- * stored). Pages with no text even then are listed in `withoutText.pages` and not stored. Any file up to 512 MiB
418
- * goes in this one call: one over 20 MiB, or with more than 100 pages for OCR, is read in the background and
419
- * answers `state` `queued` or `parsing` (follow it with `getFile`), or `ready` once done within `wait`.
382
+ * Store a file, up to 512 MiB, in one call: a PDF, a Word document (.docx), a PowerPoint deck (.pptx),
383
+ * an Excel workbook (.xlsx), a CSV or TSV, a text or Markdown file, or an image (PNG, JPEG, WebP,
384
+ * TIFF). Say its type with `type`: it is read as that type, and bytes of another type are refused (415)
385
+ * rather than misread; without it the type comes from the bytes, then the name. It is parsed into one
386
+ * document per PDF page, image page, slide, Word part or worksheet part, each `<sourceId>:<fileId>:<part>`
387
+ * (`sourceId` is the namespace's files source) with `file`, `file_id`, `file_type` and its locator
388
+ * (`page`, `part`, `slide`, `sheet`, `rows`) in metadata, beside `metadata` of your own. Pages without
389
+ * a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading the same one
390
+ * again replaces every document it made, and the same bytes, name and options again answer
391
+ * `result: "unchanged"`. `user` keeps the file to one of your users. The answer waits `wait` seconds
392
+ * (default 60) for the parse: once `ready` it holds what `parse` answers (`markdown`, `parts`,
393
+ * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
420
394
  */
421
395
  async uploadFile(file, name, options = {}) {
422
- const query = new URLSearchParams({ name, ...(options.id ? { id: options.id } : {}), ...parseQuery(options) });
396
+ const query = new URLSearchParams({
397
+ name,
398
+ ...(options.id ? { id: options.id } : {}),
399
+ ...(options.user ? { user: options.user } : {}),
400
+ ...(options.metadata ? { metadata: JSON.stringify(options.metadata) } : {}),
401
+ ...parseQuery(options),
402
+ });
423
403
  const waitS = typeof options.wait === "number" ? options.wait : options.wait === false ? 0 : 60;
424
- const timeout = Math.max(120_000, waitS * 1000 + 60_000);
404
+ const timeout = Math.max(300_000, waitS * 1000 + 60_000);
425
405
  const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout, ...options });
426
406
  return toFileUpload(body);
427
407
  }
428
408
  /**
429
- * An upload's outcome: the last upload of `fileId` here in the last 7 days. While OCR reads after the
430
- * answer, `ocrPending` lists its pages; once it ended, the pages it read are in `ids` and `pagesOcr`, and
431
- * those it could not read in `pagesWithoutText`. A file id with no upload throws 404 `file_not_found`.
409
+ * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its documents
410
+ * and its parse (`markdown`, `parts`). An id with no file throws 404 `file_not_found`.
432
411
  */
433
- async getFile(fileId, options) {
434
- const body = await this.client.request("GET", this.path(`/files/${segment(fileId)}`), undefined, options);
412
+ async getFile(fileId, options = {}) {
413
+ const q = options.user ? `?${new URLSearchParams({ user: options.user })}` : "";
414
+ const body = await this.client.request("GET", this.path(`/files/${segment(fileId)}${q}`), undefined, options);
435
415
  return { ...toFileUpload(body), name: body.name, uploadedAt: new Date(body.uploaded_at) };
436
416
  }
437
417
  /**
@@ -780,88 +760,6 @@ export class Imports {
780
760
  return toRun(body.run);
781
761
  }
782
762
  }
783
- export class Files {
784
- client;
785
- constructor(client) {
786
- this.client = client;
787
- }
788
- /**
789
- * Upload a file: it is stored and parsed in the background into a document per page, sheet part,
790
- * slide or Word part, each citing where it came from; pages without text are read by OCR. Declare
791
- * its `type` when you know it: it is then parsed as that type, and bytes of another type are a
792
- * ConareError 415 `type_mismatch`. Up to 64 MiB goes in one request, larger files (up to 512 MiB)
793
- * in parts of 16 MiB. `wait` (seconds, at most 100) holds the answer until the file is ready.
794
- */
795
- async upload(params, options = {}) {
796
- const f = params.file;
797
- const bytes = typeof f === "string"
798
- ? new TextEncoder().encode(f)
799
- : f instanceof Uint8Array
800
- ? f
801
- : f instanceof ArrayBuffer
802
- ? new Uint8Array(f)
803
- : new Uint8Array(await f.arrayBuffer());
804
- const timeout = options.timeout ?? 300_000;
805
- if (bytes.length <= MAX_FILE_REQUEST_BYTES) {
806
- const q = new URLSearchParams({ namespace: params.namespace, name: params.name });
807
- if (params.user)
808
- q.set("user", params.user);
809
- if (params.id)
810
- q.set("id", params.id);
811
- if (params.type)
812
- q.set("type", params.type);
813
- if (params.metadata)
814
- q.set("metadata", JSON.stringify(params.metadata));
815
- if (params.wait !== undefined)
816
- q.set("wait", String(params.wait));
817
- return toFileQueued(await this.client.request("POST", `/files?${q}`, bytes, { ...options, timeout }));
818
- }
819
- const upload = await this.client.request("POST", "/uploads", { bytes: bytes.length, filename: params.name, purpose: "file" }, options);
820
- const key = options.idempotencyKey;
821
- for (let n = 1; n <= upload.parts; n++) {
822
- const part = bytes.subarray((n - 1) * upload.part_size, n * upload.part_size);
823
- await this.client.request("PUT", `/uploads/${segment(upload.id)}/parts/${n}`, part, { timeout: 300_000, ...options, idempotencyKey: stepKey(key, `part-${n}`) }, { "Content-MD5": contentMd5(part) });
824
- }
825
- return toFileQueued(await this.client.request("POST", `/uploads/${segment(upload.id)}/complete`, { purpose: "file", namespace: params.namespace, user: params.user, id: params.id, type: params.type, name: params.name,
826
- metadata: params.metadata, wait: params.wait }, { ...options, timeout, idempotencyKey: stepKey(key, "complete") }));
827
- }
828
- /** The files `ids` of a namespace (and user), or, without ids, its first 100 files. */
829
- async status(params, options = {}) {
830
- const q = new URLSearchParams({ namespace: params.namespace });
831
- if (params.user)
832
- q.set("user", params.user);
833
- if (params.ids)
834
- q.set("ids", params.ids.join(","));
835
- else
836
- q.set("limit", "100");
837
- const body = await this.client.request("GET", `/files/status?${q}`, undefined, options);
838
- return body.data.map(toStoredFile);
839
- }
840
- /** Parse a file again from its stored original. */
841
- async reparse(id, params, options = {}) {
842
- const q = new URLSearchParams({ namespace: params.namespace });
843
- if (params.user)
844
- q.set("user", params.user);
845
- if (params.wait !== undefined)
846
- q.set("wait", String(params.wait));
847
- return toFileQueued(await this.client.request("POST", `/files/${segment(id)}/reparse?${q}`, undefined, { timeout: 300_000, ...options }));
848
- }
849
- /**
850
- * Wait until every file of `ids` is ready or failed (polling `status` every `interval` ms), at most
851
- * `timeout` ms (10 minutes by default): the files as they ended, or a ConareError `timeout`.
852
- */
853
- async waitUntilReady(params, options = {}) {
854
- const deadline = Date.now() + (params.timeout ?? 600_000);
855
- for (;;) {
856
- const files = await this.status(params, options);
857
- if (files.length === params.ids.length && files.every((f) => f.state === "ready" || f.state === "failed"))
858
- return files;
859
- if (Date.now() >= deadline)
860
- throw new ConareError(0, "timeout", `Files still parsing after ${params.timeout ?? 600_000} ms.`);
861
- await sleep(params.interval ?? 2_000, options.signal);
862
- }
863
- }
864
- }
865
763
  export class Users {
866
764
  client;
867
765
  constructor(client) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",