conare 0.13.0 → 0.14.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
@@ -42,12 +42,15 @@ const docs = conare.namespace("docs");
42
42
 
43
43
  await docs.add({ id, text, metadata }); // one document
44
44
  await docs.add([...]); // or many; sent 100 at a time. Returns the ids.
45
- await docs.get("refunds"); // { id, text, metadata, updatedAt } or null
45
+ await docs.write({ id, text, ifVersion: 7 }); // add, only if the document is at version 7 (0: only if
46
+ // it does not exist), else 409 version_conflict.
47
+ // Returns [{ id, version }]
48
+ await docs.get("refunds"); // { id, text, metadata, updatedAt, version } or null
46
49
  for await (const doc of docs.list()) {} // every document, page by page ({ limit } per page: 1-100, default 50)
47
50
  await docs.delete("refunds"); // 404 document_not_found if it does not exist
48
51
  await docs.deleteMany(["a", "b"]); // up to 1000 ids in one call; missing ids are skipped. Returns the count
49
52
  await docs.deleteWhere({ team: "support" }); // every document matching the filter, whole documents. Returns the count
50
- await docs.drop(); // delete the namespace and its documents (also succeeds if it is empty)
53
+ await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
51
54
  await docs.create({ sparse: true }); // create it with a sparse (SPLADE) index, before its first write
52
55
 
53
56
  await conare.namespaces(); // [{ name, documents }]
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.13.0";
1
+ export declare const VERSION = "0.14.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>;
@@ -34,17 +34,25 @@ export interface DocumentInput {
34
34
  id?: string;
35
35
  text: string;
36
36
  metadata?: Metadata;
37
+ /**
38
+ * Write only if the document holds this version (`0`: only if it does not exist), else a
39
+ * ConareError 409 `version_conflict`. Checked atomically with the write.
40
+ */
41
+ ifVersion?: number;
37
42
  }
38
43
  export interface Document {
39
44
  id: string;
40
45
  text: string;
41
46
  metadata: Metadata;
42
47
  updatedAt: Date;
48
+ /** Changes on every write of the document and only grows: pass it as `ifVersion`. */
49
+ version: number;
43
50
  }
44
51
  export interface DocumentSummary {
45
52
  id: string;
46
53
  metadata: Metadata;
47
54
  updatedAt: Date;
55
+ version: number;
48
56
  }
49
57
  export interface QueryResult {
50
58
  id: string;
@@ -161,6 +169,16 @@ export declare class Namespace {
161
169
  * A document without an id gets one here, so a retried batch replaces instead of duplicating.
162
170
  */
163
171
  add(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<string[]>;
172
+ /**
173
+ * `add` that returns each document's new version, to pass as `ifVersion` on its next write.
174
+ * A conditional write retried after a lost response can answer 409 `version_conflict` for its
175
+ * own first attempt: `get()` the document to tell. `version` is null when the server did not
176
+ * answer one (a server older than versions): never pass it as `ifVersion`.
177
+ */
178
+ write(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<{
179
+ id: string;
180
+ version: number | null;
181
+ }[]>;
164
182
  /**
165
183
  * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
166
184
  * the search fuses (default `["vector", "keyword"]`); `"sparse"` needs a namespace created with
@@ -184,7 +202,7 @@ export declare class Namespace {
184
202
  deleteMany(ids: string[], options?: RequestOptions): Promise<number>;
185
203
  /** Delete every document matching filter (at least one condition), calling until none match. Returns how many were deleted. */
186
204
  deleteWhere(filter: Filter, options?: RequestOptions): Promise<number>;
187
- /** Delete the namespace and every document in it. Succeeds as well when it holds no documents (already deleted or never written). */
205
+ /** Delete the namespace and every document in it. Succeeds as well when it was already deleted or emptied; throws ConareError 404 `namespace_not_found` for a name never written. */
188
206
  drop(options?: RequestOptions): Promise<void>;
189
207
  }
190
208
  /** Apps connected through Conare that keep syncing into a namespace. */
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.13.0";
2
+ export const VERSION = "0.14.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  // ---- Errors ----------------------------------------------------------------
@@ -16,6 +16,18 @@ export class ConareError extends Error {
16
16
  this.requestId = requestId;
17
17
  }
18
18
  }
19
+ /**
20
+ * One path segment (a namespace, document id or source id), percent-encoded. A value holding "/"
21
+ * or "\\", or one that is "." or "..", is refused here: the API's ingress decodes %2F and resolves
22
+ * dot segments before routing, so such a value would reach another route, even another namespace.
23
+ * No valid name or id contains them.
24
+ */
25
+ function segment(value) {
26
+ if (/[\\/]/.test(value) || value === "." || value === "..") {
27
+ throw new ConareError(400, "invalid_id", `${JSON.stringify(value)} cannot be a path segment: it holds "/" or "\\" or is a dot segment.`);
28
+ }
29
+ return encodeURIComponent(value);
30
+ }
19
31
  // ---- Client ----------------------------------------------------------------
20
32
  /**
21
33
  * The Conare client.
@@ -148,7 +160,7 @@ export class Namespace {
148
160
  this.name = name;
149
161
  }
150
162
  path(suffix = "") {
151
- return `/namespaces/${encodeURIComponent(this.name)}${suffix}`;
163
+ return `/namespaces/${segment(this.name)}${suffix}`;
152
164
  }
153
165
  /**
154
166
  * Create the namespace before its first write. Only a namespace with a sparse (SPLADE) index
@@ -164,14 +176,30 @@ export class Namespace {
164
176
  * A document without an id gets one here, so a retried batch replaces instead of duplicating.
165
177
  */
166
178
  async add(documents, options) {
179
+ return (await this.write(documents, options)).map((d) => d.id);
180
+ }
181
+ /**
182
+ * `add` that returns each document's new version, to pass as `ifVersion` on its next write.
183
+ * A conditional write retried after a lost response can answer 409 `version_conflict` for its
184
+ * own first attempt: `get()` the document to tell. `version` is null when the server did not
185
+ * answer one (a server older than versions): never pass it as `ifVersion`.
186
+ */
187
+ async write(documents, options) {
167
188
  const all = Array.isArray(documents) ? documents : [documents];
168
- const ids = [];
189
+ const out = [];
169
190
  for (let i = 0; i < all.length; i += BATCH_SIZE) {
170
191
  const batch = all.slice(i, i + BATCH_SIZE);
171
- const body = await this.client.request("POST", this.path("/documents"), { documents: batch.map((d) => ({ id: d.id ?? newDocumentId(), text: d.text, metadata: d.metadata })) }, options, true);
172
- ids.push(...body.ids);
192
+ const body = await this.client.request("POST", this.path("/documents"), {
193
+ documents: batch.map((d) => ({
194
+ id: d.id ?? newDocumentId(),
195
+ text: d.text,
196
+ metadata: d.metadata,
197
+ if_version: d.ifVersion,
198
+ })),
199
+ }, options, true);
200
+ body.ids.forEach((id, j) => out.push({ id, version: body.versions?.[j] ?? null }));
173
201
  }
174
- return ids;
202
+ return out;
175
203
  }
176
204
  /**
177
205
  * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
@@ -185,8 +213,8 @@ export class Namespace {
185
213
  /** One document by id, or null if it does not exist. */
186
214
  async get(id, options) {
187
215
  try {
188
- const d = await this.client.request("GET", this.path(`/documents/${encodeURIComponent(id)}`), undefined, options);
189
- return { id: d.id, text: d.text, metadata: d.metadata, updatedAt: new Date(d.updated_at) };
216
+ const d = await this.client.request("GET", this.path(`/documents/${segment(id)}`), undefined, options);
217
+ return { id: d.id, text: d.text, metadata: d.metadata, updatedAt: new Date(d.updated_at), version: d.version };
190
218
  }
191
219
  catch (err) {
192
220
  if (err instanceof ConareError && err.status === 404)
@@ -206,14 +234,14 @@ export class Namespace {
206
234
  const qs = params.toString();
207
235
  const page = await this.client.request("GET", this.path(`/documents${qs ? `?${qs}` : ""}`), undefined, options);
208
236
  for (const d of page.documents) {
209
- yield { id: d.id, metadata: d.metadata, updatedAt: new Date(d.updated_at) };
237
+ yield { id: d.id, metadata: d.metadata, updatedAt: new Date(d.updated_at), version: d.version };
210
238
  }
211
239
  cursor = page.next_cursor;
212
240
  } while (cursor);
213
241
  }
214
242
  /** Delete one document. Throws a ConareError with status 404 (`document_not_found`) if it does not exist. */
215
243
  async delete(id, options) {
216
- await this.client.request("DELETE", this.path(`/documents/${encodeURIComponent(id)}`), undefined, options);
244
+ await this.client.request("DELETE", this.path(`/documents/${segment(id)}`), undefined, options);
217
245
  }
218
246
  /** Delete up to 1000 documents by id in one call. Ids that do not exist are skipped. Returns how many were deleted. */
219
247
  async deleteMany(ids, options) {
@@ -230,7 +258,7 @@ export class Namespace {
230
258
  return deleted;
231
259
  }
232
260
  }
233
- /** Delete the namespace and every document in it. Succeeds as well when it holds no documents (already deleted or never written). */
261
+ /** Delete the namespace and every document in it. Succeeds as well when it was already deleted or emptied; throws ConareError 404 `namespace_not_found` for a name never written. */
234
262
  async drop(options) {
235
263
  await this.client.request("DELETE", this.path(), undefined, options);
236
264
  }
@@ -257,16 +285,16 @@ export class Sources {
257
285
  }
258
286
  /** One source by id. */
259
287
  async get(id, options) {
260
- return toSource(await this.client.request("GET", `/sources/${encodeURIComponent(id)}`, undefined, options));
288
+ return toSource(await this.client.request("GET", `/sources/${segment(id)}`, undefined, options));
261
289
  }
262
290
  /** Start a sync now. */
263
291
  async sync(id, options) {
264
- return toSource(await this.client.request("POST", `/sources/${encodeURIComponent(id)}/sync`, undefined, options, true));
292
+ return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, undefined, options, true));
265
293
  }
266
294
  /** Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. */
267
295
  async delete(id, options = {}) {
268
296
  const qs = options.deleteDocuments ? "?delete_documents=true" : "";
269
- await this.client.request("DELETE", `/sources/${encodeURIComponent(id)}${qs}`, undefined, options);
297
+ await this.client.request("DELETE", `/sources/${segment(id)}${qs}`, undefined, options);
270
298
  }
271
299
  /** The apps you can connect. */
272
300
  async types(options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",