conare 0.20.0 → 0.22.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
@@ -1,7 +1,27 @@
1
1
  // conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
2
- export const VERSION = "0.20.0";
2
+ export const VERSION = "0.22.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
+ const CHECK_BATCH = 1000;
6
+ function toFileUpload(body) {
7
+ return {
8
+ fileId: body.file_id,
9
+ type: body.type,
10
+ ids: body.ids,
11
+ pages: body.pages ?? null,
12
+ sheets: body.sheets ?? null,
13
+ slides: body.slides ?? null,
14
+ slidesWithoutText: body.slides_without_text ?? [],
15
+ pagesOcr: body.pages_ocr ?? 0,
16
+ imagesOcr: body.images_ocr ?? 0,
17
+ pagesWithoutText: body.pages_without_text ?? [],
18
+ ocrPending: body.ocr_pending ?? [],
19
+ };
20
+ }
21
+ /** The float vectors int8 embeddings stand for: values × scale. */
22
+ export function dequantize(embeddings) {
23
+ return embeddings.values.map((v, i) => Array.from(v, (x) => x * (embeddings.scales[i] ?? 0)));
24
+ }
5
25
  // ---- Errors ----------------------------------------------------------------
6
26
  /** Every failure the SDK throws. `status` is 0 when no response arrived. */
7
27
  export class ConareError extends Error {
@@ -28,6 +48,36 @@ function segment(value) {
28
48
  }
29
49
  return encodeURIComponent(value);
30
50
  }
51
+ /** A query's request body (snake_case). */
52
+ function queryBody(query, options) {
53
+ return {
54
+ query,
55
+ top_k: options.topK,
56
+ filter: options.filter,
57
+ rerank: options.rerank,
58
+ rerank_depth: options.rerankDepth,
59
+ retrievers: options.retrievers,
60
+ user: options.user,
61
+ user_prefix: options.userPrefix,
62
+ exclude_ids: options.excludeIds,
63
+ };
64
+ }
65
+ /** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
66
+ export const MAX_FILE_REQUEST_BYTES = 64 * 1024 * 1024;
67
+ function toStoredFile(f) {
68
+ return {
69
+ id: f.id, name: f.name, namespace: f.namespace, user: f.user, sourceId: f.source_id, type: f.type, declared: f.declared,
70
+ bytes: f.bytes, sha256: f.sha256, metadata: f.metadata ?? {}, state: f.state, pages: f.pages, pagesText: f.pages_text,
71
+ pagesOcr: f.pages_ocr, pagesWithoutText: f.pages_without_text ?? [], ocrPending: f.ocr_pending, ocrFailed: f.ocr_failed ?? [],
72
+ documents: f.documents, rejected: f.rejected ?? [], locators: f.locators ?? [], chunksEmbedded: f.chunks_embedded ?? 0,
73
+ run: { id: f.run.id, kind: f.run.kind, state: f.run.state, phase: f.run.phase, error: f.run.error,
74
+ ...(f.run.retry_at ? { retryAt: new Date(f.run.retry_at) } : {}) },
75
+ error: f.error ?? null, updatedAt: new Date(f.updated_at),
76
+ };
77
+ }
78
+ function toFileQueued(body) {
79
+ return { ...(body.result ? { result: body.result } : {}), file: toStoredFile(body.file), ...(body.run ? { run: toRun(body.run) } : {}) };
80
+ }
31
81
  // ---- Client ----------------------------------------------------------------
32
82
  /**
33
83
  * The Conare client.
@@ -38,6 +88,18 @@ function segment(value) {
38
88
  export class Conare {
39
89
  baseURL;
40
90
  sources;
91
+ /** Snapshot runs of custom sources, and any run by id. */
92
+ runs;
93
+ /** Files of documents written into a custom source. */
94
+ imports;
95
+ /** Files (PDF, Word, PowerPoint, Excel, CSV, text, images) kept as documents, a page each. */
96
+ files;
97
+ /** Delete everything Conare holds of one of your users. */
98
+ users;
99
+ /** What changed, in order. */
100
+ events;
101
+ /** The organization requests act for (`X-Conare-Org`); undefined: the key's own. */
102
+ organization;
41
103
  apiKey;
42
104
  timeout;
43
105
  maxRetries;
@@ -57,7 +119,13 @@ export class Conare {
57
119
  this.timeout = options.timeout ?? 60_000;
58
120
  this.maxRetries = options.maxRetries ?? 2;
59
121
  this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
122
+ this.organization = options.organization || undefined;
60
123
  this.sources = new Sources(this);
124
+ this.runs = new Runs(this);
125
+ this.imports = new Imports(this);
126
+ this.files = new Files(this);
127
+ this.users = new Users(this);
128
+ this.events = new Events(this);
61
129
  }
62
130
  /** A handle to one namespace. Nothing is sent until you call a method; the first write creates it. */
63
131
  namespace(name) {
@@ -65,16 +133,34 @@ export class Conare {
65
133
  }
66
134
  /**
67
135
  * Every namespace in the organization (a scoped key: every one it reaches) with its document
68
- * count; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
136
+ * count and models; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
69
137
  */
70
138
  async namespaces(options = {}) {
71
139
  const path = options.prefix ? `/namespaces?prefix=${encodeURIComponent(options.prefix)}` : "/namespaces";
72
140
  const body = await this.request("GET", path, undefined, options);
73
- return body.namespaces;
141
+ return body.namespaces.map((n) => ({
142
+ name: n.name,
143
+ documents: n.documents,
144
+ embeddingModel: n.embedding_model,
145
+ rerankModel: n.rerank_model,
146
+ }));
147
+ }
148
+ /**
149
+ * The organizations this key acts for, its own first. A multi-organization key lists each other one
150
+ * it still acts for; pass an `id` as the `organization` option of a client to act for it.
151
+ */
152
+ async organizations(options = {}) {
153
+ const body = await this.request("GET", "/organizations", undefined, options);
154
+ return body.organizations;
74
155
  }
75
- /** Embed texts. Use type "query" for search queries and "document" (default) for stored text. */
76
156
  async embed(input, options = {}) {
77
- const body = await this.request("POST", "/embed", { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" }, options);
157
+ const request = { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" };
158
+ if (options.outputDtype)
159
+ request.output_dtype = options.outputDtype;
160
+ const body = await this.request("POST", "/embed", request, options);
161
+ if (options.outputDtype === "int8") {
162
+ return { values: body.embeddings.map((v) => Int8Array.from(v)), scales: body.scales ?? [] };
163
+ }
78
164
  return body.embeddings;
79
165
  }
80
166
  /**
@@ -93,13 +179,13 @@ export class Conare {
93
179
  * the first answer and does nothing again. So every request is retried on 429, 5xx, 409
94
180
  * `idempotency_in_progress` (the first attempt is still running) and network errors.
95
181
  */
96
- async request(method, path, body, options = {}) {
182
+ async request(method, path, body, options = {}, headers = {}) {
97
183
  const key = method === "GET" ? undefined : (options.idempotencyKey ?? newIdempotencyKey());
98
184
  for (let attempt = 0;; attempt++) {
99
185
  let res;
100
186
  let text;
101
187
  try {
102
- [res, text] = await this.send(method, path, body, options, key);
188
+ [res, text] = await this.send(method, path, body, options, key, headers);
103
189
  }
104
190
  catch (err) {
105
191
  if (err instanceof ConareError && attempt < this.maxRetries) {
@@ -126,7 +212,7 @@ export class Conare {
126
212
  }
127
213
  }
128
214
  // One attempt, body included, under the timeout and the caller's signal.
129
- async send(method, path, body, options, idempotencyKey) {
215
+ async send(method, path, body, options, idempotencyKey, extra) {
130
216
  const controller = new AbortController();
131
217
  const timeout = options.timeout ?? this.timeout;
132
218
  const timer = setTimeout(() => controller.abort(), timeout);
@@ -144,6 +230,8 @@ export class Conare {
144
230
  Accept: "application/json",
145
231
  ...(body === undefined ? {} : { "Content-Type": raw ? "application/octet-stream" : "application/json" }),
146
232
  ...(idempotencyKey === undefined ? {} : { "Idempotency-Key": idempotencyKey }),
233
+ ...(this.organization === undefined ? {} : { "X-Conare-Org": this.organization }),
234
+ ...extra,
147
235
  },
148
236
  body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
149
237
  signal: controller.signal,
@@ -177,13 +265,14 @@ export class Namespace {
177
265
  return `/namespaces/${segment(this.name)}${suffix}`;
178
266
  }
179
267
  /**
180
- * Create the namespace before its first write. Only a namespace with a sparse (SPLADE) index
181
- * needs this: a write creates one without. Its index never changes: creating it again with the
182
- * other setting is a 409. Returns whether it has a sparse index.
268
+ * Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
269
+ * (one of your organization's models from `GET /models`) needs this: a write creates one with the
270
+ * default model. Its model never changes: creating it again with another one is a 409. Returns
271
+ * the model that embeds it.
183
272
  */
184
273
  async create(options = {}) {
185
- const body = await this.client.request("POST", "/namespaces", { name: this.name, sparse: options.sparse ?? false }, options);
186
- return { sparse: body.sparse };
274
+ const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel }, options);
275
+ return { embeddingModel: body.embedding_model };
187
276
  }
188
277
  /**
189
278
  * Add or replace documents. Accepts one or many; sends them in batches of 100. Returns the ids.
@@ -234,10 +323,19 @@ export class Namespace {
234
323
  return out;
235
324
  }
236
325
  /**
237
- * Store a PDF or an Excel workbook (.xlsx), at most 20 MiB: one document per PDF page with a
238
- * text layer (`<fileId>:page-3`) and Markdown tables per worksheet (`<fileId>:Sheet1-1`), each
239
- * with `file`, `file_id`, `file_type` and `page` or `sheet` metadata. `fileId` defaults to the
240
- * name in id characters; uploading the same one again replaces every document it made. Pages
326
+ * Store a PDF, a Word document (.docx), a PowerPoint deck (.pptx), an Excel workbook (.xlsx), a CSV or
327
+ * TSV, a text or Markdown file, or an image (PNG, JPEG, WebP, TIFF), at most 20 MiB. Say its type with
328
+ * `type`: it is read as that type, and bytes of another type are refused (415) rather than misread;
329
+ * without it the type comes from the bytes, then the name. One document per PDF page with a text
330
+ * layer (`<fileId>:page-3`), per image page (read by OCR), a CSV as Markdown tables with its header
331
+ * on every part and the rows each holds in `rows` metadata, a Word document as
332
+ * Markdown (`<fileId>:part-1`, more parts past 240 KiB), one per slide with text (`<fileId>:slide-2`:
333
+ * title, shapes in reading order, tables, speaker notes) and Markdown tables per worksheet
334
+ * (`<fileId>:Sheet1-1`), each with `file`, `file_id`, `file_type` and `page`, `part`, `slide` or
335
+ * `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
336
+ * name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
337
+ * such names do not collide); uploading the same one again replaces every document it made, and two
338
+ * uploads of one id run one at a time. Pages
241
339
  * without a text layer (scans, images) are read by OCR: by default after the answer
242
340
  * (`ocrPending`, stored within about a minute), with `wait: true` before it (`pagesOcr`). Pages
243
341
  * with no text even then are listed in `pagesWithoutText` and not stored.
@@ -245,42 +343,56 @@ export class Namespace {
245
343
  async uploadFile(file, name, options = {}) {
246
344
  const query = new URLSearchParams({
247
345
  name,
346
+ ...(options.type ? { type: options.type } : {}),
248
347
  ...(options.id ? { id: options.id } : {}),
249
348
  ...(options.wait ? { wait: "true" } : {}),
250
349
  });
251
350
  const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout: 120_000, ...options });
252
- return {
253
- fileId: body.file_id,
254
- type: body.type,
255
- ids: body.ids,
256
- pages: body.pages ?? null,
257
- sheets: body.sheets ?? null,
258
- pagesOcr: body.pages_ocr ?? 0,
259
- pagesWithoutText: body.pages_without_text ?? [],
260
- ocrPending: body.ocr_pending ?? [],
261
- };
351
+ return toFileUpload(body);
352
+ }
353
+ /**
354
+ * An upload's outcome: the last upload of `fileId` here in the last 7 days. While OCR reads after the
355
+ * answer, `ocrPending` lists its pages; once it ended, the pages it read are in `ids` and `pagesOcr`, and
356
+ * those it could not read in `pagesWithoutText`. A file id with no upload throws 404 `file_not_found`.
357
+ */
358
+ async getFile(fileId, options) {
359
+ const body = await this.client.request("GET", this.path(`/files/${segment(fileId)}`), undefined, options);
360
+ return { ...toFileUpload(body), name: body.name, uploadedAt: new Date(body.uploaded_at) };
262
361
  }
263
362
  /**
264
- * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
265
- * the search fuses (default `["vector", "keyword"]`); `"sparse"` needs a namespace created with
266
- * a sparse index. `rerankDepth` (1-100) has the reranker rank every passage among the first
267
- * that many in windows of 20 passages, then reads the best 20 of them together in one final
268
- * window that sets their order; unset, it reads one window of 20. `user` keeps the search to one user's documents and
269
- * `userPrefix` (ending in `:`) to a group's; both combine with `filter`.
363
+ * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
364
+ * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
365
+ * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-1000) is how many of the
366
+ * first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
367
+ * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
368
+ * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
270
369
  */
271
370
  async query(query, options = {}) {
272
- const body = await this.client.request("POST", this.path("/query"), {
273
- query,
274
- top_k: options.topK,
275
- filter: options.filter,
276
- rerank: options.rerank,
277
- rerank_depth: options.rerankDepth,
278
- retrievers: options.retrievers,
279
- user: options.user,
280
- user_prefix: options.userPrefix,
281
- }, options);
371
+ const body = await this.client.request("POST", this.path("/query"), queryBody(query, options), options);
282
372
  return body.results;
283
373
  }
374
+ /**
375
+ * A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
376
+ * or 5,000 on a custom model's engine) and yields them `topK` at a time. Later pages are read from
377
+ * that ranking (kept 15 minutes) without searching again, so they never repeat or skip a
378
+ * document; past `rerankDepth` results keep retrieval order (`reranked: false`). Pass a page's
379
+ * `nextCursor` as `cursor` to go on from it in another call (`query` is then ignored).
380
+ */
381
+ async *queryPages(query, options) {
382
+ let cursor = options.cursor ?? null;
383
+ let page = cursor
384
+ ? { results: [], next_cursor: cursor }
385
+ : await this.client.request("POST", this.path("/query"), { ...queryBody(query, options), max_results: options.maxResults }, options);
386
+ if (!cursor) {
387
+ cursor = page.next_cursor ?? null;
388
+ yield { results: page.results, nextCursor: cursor };
389
+ }
390
+ while (cursor) {
391
+ page = await this.client.request("POST", this.path("/query"), { cursor, top_k: options.topK }, options);
392
+ cursor = page.next_cursor ?? null;
393
+ yield { results: page.results, nextCursor: cursor };
394
+ }
395
+ }
284
396
  /** One document by id, or null if it does not exist. */
285
397
  async get(id, options) {
286
398
  try {
@@ -314,7 +426,10 @@ export class Namespace {
314
426
  async delete(id, options) {
315
427
  await this.client.request("DELETE", this.path(`/documents/${segment(id)}`), undefined, options);
316
428
  }
317
- /** Delete up to 1000 documents by id in one call. Ids that do not exist are skipped. Returns how many were deleted. */
429
+ /**
430
+ * Delete up to 1000 documents by id in one call. Ids that do not exist are skipped; a namespace that
431
+ * does not exist throws ConareError 404 `namespace_not_found`. Returns how many were deleted.
432
+ */
318
433
  async deleteMany(ids, options) {
319
434
  const out = await this.client.request("POST", this.path("/documents/delete"), { ids }, options);
320
435
  return out.deleted;
@@ -337,34 +452,67 @@ export class Namespace {
337
452
  }
338
453
  }
339
454
  // ---- Sources ---------------------------------------------------------------
340
- /** Apps connected through Conare that keep syncing into a namespace. */
455
+ /** Apps connected through Conare that keep syncing into a namespace, and custom sources you push to. */
341
456
  export class Sources {
342
457
  client;
458
+ /** The documents of a custom source. */
459
+ documents;
343
460
  constructor(client) {
344
461
  this.client = client;
462
+ this.documents = new SourceDocuments(client);
463
+ }
464
+ /**
465
+ * Create a custom source: a set of documents you push into `namespace`, keyed by your own ids.
466
+ * With `user`, `users.delete(user)` deletes it with the user's documents.
467
+ */
468
+ async create(params, options) {
469
+ const body = await this.client.request("POST", "/sources", { type: params.type, namespace: params.namespace, name: params.name, user: params.user }, options);
470
+ return toCustomSource(body);
345
471
  }
346
472
  /**
347
473
  * Start connecting an app. Send the app owner to `connectUrl`; they come back to `redirectUrl`.
348
474
  * For your own users, connect each one into their own namespace, e.g. "user-42".
475
+ * Twenty and Granola (`auth: "apiKey"` in `types()`) take `config` instead: `apiKey`, and for
476
+ * Twenty `baseUrl` when self-hosted. Conare checks the key, the source starts syncing at once,
477
+ * and `connectUrl` is null.
349
478
  */
350
479
  async connect(params, options) {
351
- const body = await this.client.request("POST", "/sources", { type: params.type, namespace: params.namespace, name: params.name, redirect_url: params.redirectUrl }, options);
352
- return { source: toSource(body.source), connectUrl: body.connect_url };
480
+ const body = await this.client.request("POST", "/sources", {
481
+ type: params.type,
482
+ namespace: params.namespace,
483
+ name: params.name,
484
+ redirect_url: params.redirectUrl,
485
+ sync_interval_s: params.syncIntervalSeconds,
486
+ config: params.config && { base_url: params.config.baseUrl, api_key: params.config.apiKey },
487
+ }, options);
488
+ return { source: toSource(body.source), connectUrl: body.connect_url ?? null };
489
+ }
490
+ /** Set how often a source syncs: seconds from 300 (5 minutes) to 2592000 (30 days), or null for automatic. */
491
+ async update(id, params, options) {
492
+ return toSource(await this.client.request("PATCH", `/sources/${segment(id)}`, { sync_interval_s: params.syncIntervalSeconds }, options));
353
493
  }
354
- /** Every connected source. */
494
+ /** Every source: the connected apps, then the custom sources (`kind: "custom"`). */
355
495
  async list(options) {
356
496
  const body = await this.client.request("GET", "/sources", undefined, options);
357
- return body.sources.map(toSource);
497
+ return body.sources.map(toAnySource);
358
498
  }
359
499
  /** One source by id. */
360
500
  async get(id, options) {
361
- return toSource(await this.client.request("GET", `/sources/${segment(id)}`, undefined, options));
501
+ return toAnySource(await this.client.request("GET", `/sources/${segment(id)}`, undefined, options));
362
502
  }
363
- /** Start a sync now. */
364
- async sync(id, options) {
365
- return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, undefined, options));
503
+ /**
504
+ * Start a sync now. `full: true` re-reads everything the app holds instead of what changed: documents
505
+ * that changed are rewritten and ones Conare no longer keeps are deleted. It is for Gmail and the apps
506
+ * Conare reads itself (other apps answer 400), and Gmail's rows are billed again (`cost.usdPerMillionRows`).
507
+ */
508
+ async sync(id, options = {}) {
509
+ const { full, ...request } = options;
510
+ return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, full ? { full: true } : undefined, request));
366
511
  }
367
- /** Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. */
512
+ /**
513
+ * Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. A custom
514
+ * source's documents are deleted by a run, which `runs.get` follows until the source is `deleted`.
515
+ */
368
516
  async delete(id, options = {}) {
369
517
  const qs = options.deleteDocuments ? "?delete_documents=true" : "";
370
518
  await this.client.request("DELETE", `/sources/${segment(id)}${qs}`, undefined, options);
@@ -372,9 +520,482 @@ export class Sources {
372
520
  /** The apps you can connect. */
373
521
  async types(options) {
374
522
  const body = await this.client.request("GET", "/sources/types", undefined, options);
375
- return body.types.map((t) => ({ type: t.type, name: t.name, logoUrl: t.logo_url }));
523
+ return body.types.map((t) => ({
524
+ type: t.type,
525
+ name: t.name,
526
+ logoUrl: t.logo_url,
527
+ ...(t.auth === "api_key" ? { auth: "apiKey" } : {}),
528
+ }));
529
+ }
530
+ }
531
+ // ---- Custom sources --------------------------------------------------------
532
+ /** The documents of a custom source, by source id. */
533
+ export class SourceDocuments {
534
+ client;
535
+ constructor(client) {
536
+ this.client = client;
537
+ }
538
+ /**
539
+ * Push documents (sent 100 at a time): what each write did, in order, once it is stored. Pushes
540
+ * of one source may run concurrently. With `runId`, they belong to that snapshot run.
541
+ */
542
+ async put(sourceId, documents, options = {}) {
543
+ const all = Array.isArray(documents) ? documents : [documents];
544
+ const out = [];
545
+ for (let i = 0; i < all.length; i += BATCH_SIZE) {
546
+ const body = await this.client.request("PUT", `/sources/${segment(sourceId)}/documents`, { run_id: options.runId, documents: all.slice(i, i + BATCH_SIZE).map(toWireCustomDocument) }, options);
547
+ out.push(...body.results.map(toPushResult));
548
+ }
549
+ return out;
550
+ }
551
+ /**
552
+ * Which documents need a push: `need` are those the source does not hold with that `tag`,
553
+ * `excluded` those deleted with `exclude`. With `runId`, each one counts as seen by the run.
554
+ */
555
+ async check(sourceId, documents, options = {}) {
556
+ const out = { need: [], excluded: [] };
557
+ for (let i = 0; i < documents.length; i += CHECK_BATCH) {
558
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/documents/check`, { run_id: options.runId, documents: documents.slice(i, i + CHECK_BATCH).map((d) => ({ external_id: d.externalId, tag: d.tag })) }, { ...options, idempotencyKey: stepKey(options.idempotencyKey, i / CHECK_BATCH) });
559
+ out.need.push(...body.need);
560
+ out.excluded.push(...body.excluded);
561
+ }
562
+ return out;
563
+ }
564
+ /** Every document of the source in key order, page by page. `limit` is the page size: 1-100, default 50. */
565
+ async *list(sourceId, options = {}) {
566
+ let cursor = null;
567
+ do {
568
+ const params = new URLSearchParams();
569
+ if (options.limit)
570
+ params.set("limit", String(options.limit));
571
+ if (cursor)
572
+ params.set("cursor", cursor);
573
+ const qs = params.toString();
574
+ const page = await this.client.request("GET", `/sources/${segment(sourceId)}/documents${qs ? `?${qs}` : ""}`, undefined, options);
575
+ yield* page.data.map(toCustomDocument);
576
+ cursor = page.next_cursor;
577
+ } while (cursor);
578
+ }
579
+ /** One document with its text and metadata, by its `key` (or an external id that is its own key), or null. */
580
+ async get(sourceId, key, options) {
581
+ try {
582
+ return toCustomDocument(await this.client.request("GET", `/sources/${segment(sourceId)}/documents/${segment(key)}`, undefined, options));
583
+ }
584
+ catch (err) {
585
+ if (err instanceof ConareError && err.status === 404 && err.code === "document_not_found")
586
+ return null;
587
+ throw err;
588
+ }
589
+ }
590
+ /**
591
+ * Delete documents by external id (1,000 a call). A tombstone at `seq` makes older pushes of each
592
+ * `stale` (one already writing too); one holding a higher `seq` is `kept`; `exclude` keeps it out until
593
+ * restored.
594
+ */
595
+ async delete(sourceId, externalIds, options = {}) {
596
+ const out = { deleted: 0, kept: 0, excluded: 0 };
597
+ for (let i = 0; i < externalIds.length; i += CHECK_BATCH) {
598
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/documents/delete`, { external_ids: externalIds.slice(i, i + CHECK_BATCH), exclude: options.exclude, seq: options.seq }, { ...options, idempotencyKey: stepKey(options.idempotencyKey, i / CHECK_BATCH) });
599
+ out.deleted += body.deleted;
600
+ out.kept += body.kept;
601
+ out.excluded += body.excluded;
602
+ }
603
+ return out;
604
+ }
605
+ /** Let excluded documents be pushed again. Returns how many were excluded. */
606
+ async restore(sourceId, externalIds, options) {
607
+ let restored = 0;
608
+ for (let i = 0; i < externalIds.length; i += CHECK_BATCH) {
609
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/documents/restore`, { external_ids: externalIds.slice(i, i + CHECK_BATCH) }, { ...options, idempotencyKey: stepKey(options?.idempotencyKey, i / CHECK_BATCH) });
610
+ restored += body.restored;
611
+ }
612
+ return restored;
613
+ }
614
+ }
615
+ /**
616
+ * An open snapshot run: push or check the source's whole set through it, then complete it. The
617
+ * documents it never saw are deleted, unless that is over 10% (and over 1,000) at once: then the run
618
+ * is `held` until a second run at least 24 h later agrees.
619
+ */
620
+ export class SnapshotRun {
621
+ client;
622
+ sourceId;
623
+ run;
624
+ constructor(client, sourceId, run) {
625
+ this.client = client;
626
+ this.sourceId = sourceId;
627
+ this.run = run;
628
+ }
629
+ get id() {
630
+ return this.run.id;
631
+ }
632
+ put(documents, options = {}) {
633
+ return this.client.sources.documents.put(this.sourceId, documents, { ...options, runId: this.run.id });
634
+ }
635
+ check(documents, options = {}) {
636
+ return this.client.sources.documents.check(this.sourceId, documents, { ...options, runId: this.run.id });
637
+ }
638
+ /**
639
+ * Stop taking pushes and sweep. Waits up to `wait` seconds (default 100) for the run to finish,
640
+ * then follows it until it did (`runs.get`); `allowMassDelete` applies a sweep of any size.
641
+ */
642
+ async complete(options = {}) {
643
+ const wait = options.wait ?? 100;
644
+ const body = await this.client.request("POST", `/runs/${segment(this.run.id)}/complete?wait=${wait}`, { allow_mass_delete: options.allowMassDelete }, { timeout: (wait + 30) * 1000, ...options });
645
+ let run = toRun(body.run);
646
+ while (!run.finishedAt) {
647
+ await sleep(options.poll ?? 5_000, options.signal);
648
+ run = await this.client.runs.get(run.id, options);
649
+ }
650
+ return run;
376
651
  }
377
652
  }
653
+ export class Runs {
654
+ client;
655
+ constructor(client) {
656
+ this.client = client;
657
+ }
658
+ /**
659
+ * Open a snapshot run of a custom source (one active run at a time). `expected`, your count of
660
+ * the set, blocks the sweep of a run that saw under 90% of it; a run with no push for
661
+ * `idleTimeoutS` (60-86,400, default 3,600) is canceled.
662
+ */
663
+ async open(sourceId, params = {}, options) {
664
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/runs`, { mode: "snapshot", expected: params.expected, idle_timeout_s: params.idleTimeoutS }, options);
665
+ return new SnapshotRun(this.client, sourceId, toRun(body));
666
+ }
667
+ async get(id, options) {
668
+ return toRun(await this.client.request("GET", `/runs/${segment(id)}`, undefined, options));
669
+ }
670
+ }
671
+ export class Imports {
672
+ client;
673
+ constructor(client) {
674
+ this.client = client;
675
+ }
676
+ /**
677
+ * Write a file of JSON lines (one `CustomDocumentInput` a line, snake_case, up to 1 GiB) into a
678
+ * custom source: it is uploaded in parts, each checked by its MD5, then imported by a run, which
679
+ * `runs.get` follows. `snapshot` also deletes what the file does not hold.
680
+ */
681
+ async create(sourceId, file, params = {}, options = {}) {
682
+ const bytes = typeof file === "string"
683
+ ? new TextEncoder().encode(file)
684
+ : file instanceof Uint8Array
685
+ ? file
686
+ : file instanceof ArrayBuffer
687
+ ? new Uint8Array(file)
688
+ : new Uint8Array(await file.arrayBuffer());
689
+ const upload = await this.client.request("POST", "/uploads", { bytes: bytes.length, filename: params.filename }, options);
690
+ // Each step is its own request: with the caller's key, its own key derived from it.
691
+ const key = options.idempotencyKey;
692
+ for (let n = 1; n <= upload.parts; n++) {
693
+ const part = bytes.subarray((n - 1) * upload.part_size, n * upload.part_size);
694
+ 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) });
695
+ }
696
+ await this.client.request("POST", `/uploads/${segment(upload.id)}/complete`, { purpose: "import" }, { ...options, idempotencyKey: stepKey(key, "complete") });
697
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/imports`, { upload: upload.id, mode: params.mode ?? "delta", expected: params.expected, allow_mass_delete: params.allowMassDelete }, { ...options, idempotencyKey: stepKey(key, "import") });
698
+ return toRun(body.run);
699
+ }
700
+ }
701
+ export class Files {
702
+ client;
703
+ constructor(client) {
704
+ this.client = client;
705
+ }
706
+ /**
707
+ * Upload a file: it is stored and parsed in the background into a document per page, sheet part,
708
+ * slide or Word part, each citing where it came from; pages without text are read by OCR. Declare
709
+ * its `type` when you know it: it is then parsed as that type, and bytes of another type are a
710
+ * ConareError 415 `type_mismatch`. Up to 64 MiB goes in one request, larger files (up to 512 MiB)
711
+ * in parts of 16 MiB. `wait` (seconds, at most 100) holds the answer until the file is ready.
712
+ */
713
+ async upload(params, options = {}) {
714
+ const f = params.file;
715
+ const bytes = typeof f === "string"
716
+ ? new TextEncoder().encode(f)
717
+ : f instanceof Uint8Array
718
+ ? f
719
+ : f instanceof ArrayBuffer
720
+ ? new Uint8Array(f)
721
+ : new Uint8Array(await f.arrayBuffer());
722
+ const timeout = options.timeout ?? 300_000;
723
+ if (bytes.length <= MAX_FILE_REQUEST_BYTES) {
724
+ const q = new URLSearchParams({ namespace: params.namespace, name: params.name });
725
+ if (params.user)
726
+ q.set("user", params.user);
727
+ if (params.id)
728
+ q.set("id", params.id);
729
+ if (params.type)
730
+ q.set("type", params.type);
731
+ if (params.metadata)
732
+ q.set("metadata", JSON.stringify(params.metadata));
733
+ if (params.wait !== undefined)
734
+ q.set("wait", String(params.wait));
735
+ return toFileQueued(await this.client.request("POST", `/files?${q}`, bytes, { ...options, timeout }));
736
+ }
737
+ const upload = await this.client.request("POST", "/uploads", { bytes: bytes.length, filename: params.name, purpose: "file" }, options);
738
+ const key = options.idempotencyKey;
739
+ for (let n = 1; n <= upload.parts; n++) {
740
+ const part = bytes.subarray((n - 1) * upload.part_size, n * upload.part_size);
741
+ 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) });
742
+ }
743
+ 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,
744
+ metadata: params.metadata, wait: params.wait }, { ...options, timeout, idempotencyKey: stepKey(key, "complete") }));
745
+ }
746
+ /** The files `ids` of a namespace (and user), or, without ids, its first 100 files. */
747
+ async status(params, options = {}) {
748
+ const q = new URLSearchParams({ namespace: params.namespace });
749
+ if (params.user)
750
+ q.set("user", params.user);
751
+ if (params.ids)
752
+ q.set("ids", params.ids.join(","));
753
+ else
754
+ q.set("limit", "100");
755
+ const body = await this.client.request("GET", `/files/status?${q}`, undefined, options);
756
+ return body.data.map(toStoredFile);
757
+ }
758
+ /** Parse a file again from its stored original. */
759
+ async reparse(id, params, options = {}) {
760
+ const q = new URLSearchParams({ namespace: params.namespace });
761
+ if (params.user)
762
+ q.set("user", params.user);
763
+ if (params.wait !== undefined)
764
+ q.set("wait", String(params.wait));
765
+ return toFileQueued(await this.client.request("POST", `/files/${segment(id)}/reparse?${q}`, undefined, { timeout: 300_000, ...options }));
766
+ }
767
+ /**
768
+ * Wait until every file of `ids` is ready or failed (polling `status` every `interval` ms), at most
769
+ * `timeout` ms (10 minutes by default): the files as they ended, or a ConareError `timeout`.
770
+ */
771
+ async waitUntilReady(params, options = {}) {
772
+ const deadline = Date.now() + (params.timeout ?? 600_000);
773
+ for (;;) {
774
+ const files = await this.status(params, options);
775
+ if (files.length === params.ids.length && files.every((f) => f.state === "ready" || f.state === "failed"))
776
+ return files;
777
+ if (Date.now() >= deadline)
778
+ throw new ConareError(0, "timeout", `Files still parsing after ${params.timeout ?? 600_000} ms.`);
779
+ await sleep(params.interval ?? 2_000, options.signal);
780
+ }
781
+ }
782
+ }
783
+ export class Users {
784
+ client;
785
+ constructor(client) {
786
+ this.client = client;
787
+ }
788
+ /**
789
+ * Delete everything Conare holds of a user: their documents in every namespace and their
790
+ * sources. A purge run does it (writes for the user are refused meanwhile); it finishes once a
791
+ * second check 10 minutes after the first finds nothing. Asking again returns the same run.
792
+ */
793
+ async delete(user, options) {
794
+ const body = await this.client.request("DELETE", `/users/${segment(user)}`, undefined, options);
795
+ return toRun(body.run);
796
+ }
797
+ /** `delete` for every user starting with `prefix` (at least 3 characters, ending in `:`). */
798
+ async deletePrefix(prefix, options) {
799
+ const body = await this.client.request("DELETE", `/users?prefix=${encodeURIComponent(prefix)}`, undefined, options);
800
+ return toRun(body.run);
801
+ }
802
+ }
803
+ export class Events {
804
+ client;
805
+ constructor(client) {
806
+ this.client = client;
807
+ }
808
+ /**
809
+ * The events after `cursor`, oldest first (100 by default, at most 1,000): `seq` counts up by one
810
+ * with no gap, so pass `nextCursor` as the next `cursor`. `types` takes groups such as `"run.*"`.
811
+ */
812
+ async list(params = {}, options) {
813
+ const q = new URLSearchParams();
814
+ if (params.cursor)
815
+ q.set("cursor", params.cursor);
816
+ if (params.types?.length)
817
+ q.set("types", params.types.join(","));
818
+ if (params.userPrefix)
819
+ q.set("user_prefix", params.userPrefix);
820
+ if (params.limit)
821
+ q.set("limit", String(params.limit));
822
+ const qs = q.toString();
823
+ const body = await this.client.request("GET", `/events${qs ? `?${qs}` : ""}`, undefined, options);
824
+ return {
825
+ data: body.data.map((e) => ({
826
+ id: e.id,
827
+ seq: e.seq,
828
+ type: e.type,
829
+ sourceId: e.source_id,
830
+ runId: e.run_id,
831
+ user: e.user,
832
+ data: e.data,
833
+ createdAt: new Date(e.created_at),
834
+ })),
835
+ nextCursor: body.next_cursor,
836
+ };
837
+ }
838
+ }
839
+ function toAnySource(s) {
840
+ return s.type === "custom" ? toCustomSource(s) : toSource(s);
841
+ }
842
+ function toCustomSource(s) {
843
+ return {
844
+ id: s.id,
845
+ kind: "custom",
846
+ type: "custom",
847
+ namespace: s.namespace,
848
+ user: s.user,
849
+ name: s.name,
850
+ status: s.status,
851
+ health: s.health,
852
+ display: s.display,
853
+ sync: { state: s.sync.state, runId: s.sync.run_id, phase: s.sync.phase },
854
+ documents: s.documents,
855
+ documentsVerifiedAt: s.documents_verified_at ? new Date(s.documents_verified_at) : null,
856
+ createdAt: new Date(s.created_at),
857
+ updatedAt: new Date(s.updated_at),
858
+ };
859
+ }
860
+ function toWireCustomDocument(d) {
861
+ return {
862
+ external_id: d.externalId,
863
+ text: d.text,
864
+ title: d.title,
865
+ url: d.url,
866
+ event_at: d.eventAt,
867
+ metadata: d.metadata,
868
+ user: d.user,
869
+ seq: d.seq,
870
+ tag: d.tag,
871
+ deleted: d.deleted,
872
+ };
873
+ }
874
+ function toPushResult(r) {
875
+ const out = { externalId: r.external_id, key: r.key, result: r.result };
876
+ if (r.code !== undefined)
877
+ out.code = r.code;
878
+ if (r.message !== undefined)
879
+ out.message = r.message;
880
+ if (r.stored_seq !== undefined)
881
+ out.storedSeq = r.stored_seq;
882
+ if (r.version !== undefined)
883
+ out.version = r.version;
884
+ if (r.chunks !== undefined)
885
+ out.chunks = r.chunks;
886
+ if (r.chunks_embedded !== undefined)
887
+ out.chunksEmbedded = r.chunks_embedded;
888
+ return out;
889
+ }
890
+ function toCustomDocument(d) {
891
+ const out = {
892
+ externalId: d.external_id,
893
+ key: d.key,
894
+ tag: d.tag,
895
+ seq: d.seq,
896
+ user: d.user,
897
+ version: d.version,
898
+ updatedAt: d.updated_at ? new Date(d.updated_at) : null,
899
+ };
900
+ if (d.text !== undefined)
901
+ out.text = d.text;
902
+ if (d.metadata !== undefined)
903
+ out.metadata = d.metadata;
904
+ return out;
905
+ }
906
+ function toRun(r) {
907
+ return {
908
+ id: r.id,
909
+ sourceId: r.source_id,
910
+ kind: r.kind,
911
+ state: r.state,
912
+ phase: r.phase,
913
+ attempt: r.attempt ?? 0,
914
+ sweep: r.sweep,
915
+ sweepReason: r.sweep_reason,
916
+ expected: r.expected,
917
+ counts: r.counts ?? {},
918
+ error: r.error,
919
+ progress: r.progress
920
+ ? { done: r.progress.done, expected: r.progress.expected, ratePerS: r.progress.rate_per_s, etaS: r.progress.eta_s }
921
+ : null,
922
+ createdAt: new Date(r.created_at),
923
+ startedAt: r.started_at ? new Date(r.started_at) : null,
924
+ finishedAt: r.finished_at ? new Date(r.finished_at) : null,
925
+ };
926
+ }
927
+ /** A random Idempotency-Key for one call (kept across its retries). */
928
+ function base64(bytes) {
929
+ let bin = "";
930
+ for (const b of bytes)
931
+ bin += String.fromCharCode(b);
932
+ return btoa(bin);
933
+ }
934
+ let nodeCrypto;
935
+ function contentMd5(data) {
936
+ if (nodeCrypto === undefined) {
937
+ try {
938
+ const p = globalThis.process;
939
+ nodeCrypto = p?.getBuiltinModule?.("node:crypto") ?? null;
940
+ }
941
+ catch {
942
+ nodeCrypto = null;
943
+ }
944
+ }
945
+ return nodeCrypto ? nodeCrypto.createHash("md5").update(data).digest("base64") : base64(md5(data));
946
+ }
947
+ // MD5 (RFC 1321) in JS, for runtimes without node:crypto.
948
+ const MD5_S = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
949
+ const MD5_K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
950
+ function md5(data) {
951
+ const padded = new Uint8Array(((data.length + 8) >> 6) * 64 + 64);
952
+ padded.set(data);
953
+ padded[data.length] = 0x80;
954
+ const view = new DataView(padded.buffer);
955
+ view.setUint32(padded.length - 8, (data.length * 8) >>> 0, true);
956
+ view.setUint32(padded.length - 4, Math.floor(data.length / 2 ** 29), true);
957
+ let a0 = 0x67452301, b0 = 0xefcdab89, c0 = 0x98badcfe, d0 = 0x10325476;
958
+ const m = new Uint32Array(16);
959
+ for (let off = 0; off < padded.length; off += 64) {
960
+ for (let j = 0; j < 16; j++)
961
+ m[j] = view.getUint32(off + j * 4, true);
962
+ let a = a0, b = b0, c = c0, d = d0;
963
+ for (let i = 0; i < 64; i++) {
964
+ // Plain assignments: destructuring allocates two arrays a round.
965
+ let f, g;
966
+ if (i < 16) {
967
+ f = (b & c) | (~b & d);
968
+ g = i;
969
+ }
970
+ else if (i < 32) {
971
+ f = (d & b) | (~d & c);
972
+ g = (5 * i + 1) % 16;
973
+ }
974
+ else if (i < 48) {
975
+ f = b ^ c ^ d;
976
+ g = (3 * i + 5) % 16;
977
+ }
978
+ else {
979
+ f = c ^ (b | ~d);
980
+ g = (7 * i) % 16;
981
+ }
982
+ const sum = (a + f + MD5_K[i] + m[g]) >>> 0;
983
+ const shift = MD5_S[(i >> 4) * 4 + (i % 4)];
984
+ a = d;
985
+ d = c;
986
+ c = b;
987
+ b = (b + ((sum << shift) | (sum >>> (32 - shift)))) >>> 0;
988
+ }
989
+ a0 = (a0 + a) >>> 0;
990
+ b0 = (b0 + b) >>> 0;
991
+ c0 = (c0 + c) >>> 0;
992
+ d0 = (d0 + d) >>> 0;
993
+ }
994
+ const out = new Uint8Array(16);
995
+ const ov = new DataView(out.buffer);
996
+ [a0, b0, c0, d0].forEach((w, i) => ov.setUint32(i * 4, w, true));
997
+ return out;
998
+ }
378
999
  function toSource(s) {
379
1000
  return {
380
1001
  id: s.id,
@@ -387,6 +1008,26 @@ function toSource(s) {
387
1008
  lastSyncedAt: s.last_synced_at ? new Date(s.last_synced_at) : null,
388
1009
  createdAt: new Date(s.created_at),
389
1010
  ...(s.progress ? { recordsPulled: s.progress.records_pulled } : {}),
1011
+ syncIntervalSeconds: s.sync_interval_s ?? null,
1012
+ syncIntervalAuto: s.sync_interval_auto ?? true,
1013
+ nextSyncAt: s.next_sync_at ? new Date(s.next_sync_at) : null,
1014
+ ...(s.resync ? { resyncNote: s.resync.message } : {}),
1015
+ cost: s.cost
1016
+ ? {
1017
+ rowsPerRun: s.cost.rows_per_run,
1018
+ windowSeconds: s.cost.window_s,
1019
+ reads: s.cost.reads,
1020
+ autoIntervalSeconds: s.cost.auto_interval_s,
1021
+ usdPerMillionRows: s.cost.usd_per_million_rows,
1022
+ options: s.cost.options.map((o) => ({
1023
+ intervalSeconds: o.interval_s,
1024
+ auto: o.auto,
1025
+ rowsMonth: o.rows_month,
1026
+ usdMonth: o.usd_month,
1027
+ })),
1028
+ rowsBilled: s.cost.rows_billed,
1029
+ }
1030
+ : null,
390
1031
  };
391
1032
  }
392
1033
  function toError(res, text) {
@@ -401,6 +1042,14 @@ function toError(res, text) {
401
1042
  return new ConareError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? (res.statusText || `HTTP ${res.status}`), error?.request_id ?? requestId);
402
1043
  }
403
1044
  const ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1045
+ /**
1046
+ * The Idempotency-Key of step `step` of a call that sends several requests, from the caller's
1047
+ * `key`: the key itself for the first (0), `<key>:<step>` after; none when the caller gave none
1048
+ * (each request then makes its own).
1049
+ */
1050
+ function stepKey(key, step) {
1051
+ return key && step !== 0 ? `${key}:${step}` : key;
1052
+ }
404
1053
  /** "idk_" and 32 random hex characters: one write call's Idempotency-Key. */
405
1054
  function newIdempotencyKey() {
406
1055
  const bytes = new Uint8Array(16);
@@ -429,11 +1078,16 @@ function sleep(ms, signal) {
429
1078
  return new Promise((resolve, reject) => {
430
1079
  if (signal?.aborted)
431
1080
  return reject(signal.reason);
432
- const timer = setTimeout(resolve, ms);
433
- signal?.addEventListener("abort", () => {
1081
+ const onAbort = () => {
434
1082
  clearTimeout(timer);
435
1083
  reject(signal.reason);
436
- }, { once: true });
1084
+ };
1085
+ // The caller's signal may live for the whole process: its listener goes when the timer fires.
1086
+ const timer = setTimeout(() => {
1087
+ signal?.removeEventListener("abort", onAbort);
1088
+ resolve();
1089
+ }, ms);
1090
+ signal?.addEventListener("abort", onAbort, { once: true });
437
1091
  });
438
1092
  }
439
1093
  function env(name) {