llm-large-files 0.10.1 → 0.10.2

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/dist/ask.d.ts +16 -0
  3. package/dist/ask.d.ts.map +1 -1
  4. package/dist/ask.js +26 -2
  5. package/dist/ask.js.map +1 -1
  6. package/dist/cache.d.ts +27 -1
  7. package/dist/cache.d.ts.map +1 -1
  8. package/dist/cache.js +96 -21
  9. package/dist/cache.js.map +1 -1
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/ingest.d.ts +12 -1
  15. package/dist/ingest.d.ts.map +1 -1
  16. package/dist/ingest.js +146 -11
  17. package/dist/ingest.js.map +1 -1
  18. package/dist/library.d.ts +55 -5
  19. package/dist/library.d.ts.map +1 -1
  20. package/dist/library.js +74 -4
  21. package/dist/library.js.map +1 -1
  22. package/dist/stores.d.ts +38 -1
  23. package/dist/stores.d.ts.map +1 -1
  24. package/dist/stores.js +184 -6
  25. package/dist/stores.js.map +1 -1
  26. package/dist/testing/store-checks.d.ts +8 -3
  27. package/dist/testing/store-checks.d.ts.map +1 -1
  28. package/dist/testing/store-checks.js +74 -1
  29. package/dist/testing/store-checks.js.map +1 -1
  30. package/dist/types.d.ts +56 -0
  31. package/dist/types.d.ts.map +1 -1
  32. package/docs/guides/deployment.md +3 -3
  33. package/docs/guides/storage.md +62 -8
  34. package/docs/reference/ask.md +25 -3
  35. package/docs/reference/events.md +1 -1
  36. package/docs/reference/library.md +106 -11
  37. package/docs/reference/testing.md +10 -4
  38. package/docs/security.md +2 -1
  39. package/package.json +1 -1
  40. package/src/ask.ts +35 -2
  41. package/src/cache.ts +95 -19
  42. package/src/index.ts +2 -2
  43. package/src/ingest.ts +144 -12
  44. package/src/library.ts +122 -8
  45. package/src/stores.ts +174 -7
  46. package/src/testing/store-checks.ts +74 -3
  47. package/src/types.ts +55 -0
package/src/stores.ts CHANGED
@@ -4,8 +4,8 @@ import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, stat, unli
4
4
  import path from "node:path";
5
5
  import { DocumentScopeError } from "./errors.js";
6
6
  import { Limiter } from "./limiter.js";
7
- import { checkScope, MAX_SCOPE_SEGMENTS, scopeKey } from "./scope.js";
8
- import type { DocumentContext, DocumentMeta, DocumentScope, DocumentStore, StoredDocument } from "./types.js";
7
+ import { checkScope, MAX_SCOPE_SEGMENTS, sameScope, scopeKey } from "./scope.js";
8
+ import type { DocumentContext, DocumentMeta, DocumentScope, DocumentStore, MetaPatch, StoredDocument } from "./types.js";
9
9
 
10
10
  /** The shape of the document IDs the library makes: "doc_" and 32 hex digits. */
11
11
  export const DOCUMENT_ID_PATTERN = /^doc_[a-f0-9]{32}$/;
@@ -28,6 +28,29 @@ function expired(meta: DocumentMeta, now = new Date()): boolean {
28
28
  return Date.parse(meta.expiresAt) <= now.getTime();
29
29
  }
30
30
 
31
+ /**
32
+ * Whether `meta` is the document `patch` names: its `createdAt`, owner and scope (null and absent
33
+ * are none). A document stored again under the ID since, or by another owner, is not.
34
+ */
35
+ function patchedOne(meta: DocumentMeta, patch: MetaPatch): boolean {
36
+ if (meta.createdAt !== patch.createdAt || (meta.owner ?? undefined) !== (patch.owner ?? undefined)) return false;
37
+ const theirs: unknown = meta.scope ?? undefined;
38
+ const mine = patch.scope ?? undefined;
39
+ return theirs === undefined ? mine === undefined : Array.isArray(theirs) && sameScope(theirs as string[], mine);
40
+ }
41
+
42
+ /**
43
+ * The metadata with the fields of `patch` applied (`DocumentStore.patchMeta`): the later expiry,
44
+ * and `appData` replaced or removed. A copy.
45
+ */
46
+ function patched(meta: DocumentMeta, patch: MetaPatch): DocumentMeta {
47
+ const next = structuredClone(meta);
48
+ if (patch.expiresAt !== undefined && Date.parse(patch.expiresAt) > Date.parse(next.expiresAt)) next.expiresAt = patch.expiresAt;
49
+ if (patch.appData === null) delete next.appData;
50
+ else if (patch.appData !== undefined) next.appData = structuredClone(patch.appData);
51
+ return next;
52
+ }
53
+
31
54
  /** The documents of one scope in a `MemoryDocumentStore`, and the scope as it was given. */
32
55
  type Shelf = { scope: DocumentScope | undefined; documents: Map<string, StoredDocument>; originals: Map<string, Uint8Array> };
33
56
 
@@ -112,6 +135,22 @@ export class MemoryDocumentStore implements DocumentStore {
112
135
  return removed;
113
136
  }
114
137
 
138
+ /** The metadata of the documents of the scope of `context`, or of no scope when it has none, expired ones left out. New in 0.10.2. */
139
+ async list(context?: DocumentContext): Promise<DocumentMeta[]> {
140
+ const shelf = this.#shelf(context);
141
+ if (!shelf) return [];
142
+ const now = this.now();
143
+ return [...shelf.documents.values()].filter((document) => !expired(document.meta, now)).map((document) => structuredClone(document.meta));
144
+ }
145
+
146
+ /** Changes the fields of `patch` in the metadata of the document of that `createdAt`, and keeps its text. New in 0.10.2. */
147
+ async patchMeta(id: string, patch: MetaPatch, context?: DocumentContext): Promise<DocumentMeta | undefined> {
148
+ const document = this.#shelf(context)?.documents.get(id);
149
+ if (!document || expired(document.meta, this.now()) || !patchedOne(document.meta, patch)) return undefined;
150
+ document.meta = patched(document.meta, patch);
151
+ return structuredClone(document.meta);
152
+ }
153
+
115
154
  async putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void> {
116
155
  // A copy: the caller may reuse its buffer after the upload.
117
156
  this.#shelf(context, true).originals.set(id, bytes.slice());
@@ -582,9 +621,13 @@ export class FileDocumentStore implements DocumentStore {
582
621
  if (!fileId(document.meta.id)) throw new Error("Invalid document ID.");
583
622
  const place = await this.#make(context);
584
623
  const files = filesOf(place.folder, document.meta.id);
585
- await this.#write(place, files.text, document.text);
586
- // Write metadata last: a document without metadata is treated as absent.
587
- await this.#write(place, files.meta, JSON.stringify(document.meta));
624
+ // In the turn of the document's changes (since 0.10.2): a patchMeta of this store never writes
625
+ // the metadata of the document it read over this one.
626
+ await this.#inTurn(files.meta, async () => {
627
+ await this.#write(place, files.text, document.text);
628
+ // Write metadata last: a document without metadata is treated as absent.
629
+ await this.#write(place, files.meta, JSON.stringify(document.meta));
630
+ });
588
631
  }
589
632
 
590
633
  /** The metadata of a document in `place`, or undefined. An expired one is removed, as far as that works. */
@@ -716,7 +759,105 @@ export class FileDocumentStore implements DocumentStore {
716
759
  async delete(id: string, context?: DocumentContext): Promise<boolean> {
717
760
  if (!fileId(id)) return false;
718
761
  const place = await this.#find(context, true);
719
- return place ? this.#remove(place, id) : false;
762
+ // In the turn of the document's changes, as put (0.10.2).
763
+ return place ? this.#inTurn(filesOf(place.folder, id).meta, () => this.#remove(place, id)) : false;
764
+ }
765
+
766
+ /**
767
+ * The metadata of the documents in the folder of the scope of `context` (in the directory, without
768
+ * `scopes`), without the expired ones. It reads every metadata file of the folder,
769
+ * `sweepConcurrency` at a time: a folder of one chat holds few, but the directory of a store
770
+ * without scopes may hold many. Only metadata that names its own file counts (the application's
771
+ * `notes.json` in a folder it shares is not a document), and nothing is removed: that is
772
+ * `sweep`'s. A folder that is not there gives none. New in 0.10.2.
773
+ */
774
+ async list(context?: DocumentContext): Promise<DocumentMeta[]> {
775
+ const place = await this.#find(context);
776
+ if (!place) return [];
777
+ let entries: Dirent[];
778
+ try {
779
+ entries = await readdir(place.folder, { withFileTypes: true });
780
+ } catch (error) {
781
+ if (this.#unreadable(place, error)) return [];
782
+ throw error;
783
+ }
784
+ const ids = entries.flatMap((entry) => {
785
+ const match = entry.isFile() ? FILE_NAME.exec(entry.name) : null;
786
+ return match && match[2] === "json" && match[3] === undefined && fileId(match[1]!) ? [match[1]!] : [];
787
+ });
788
+ const now = this.now();
789
+ const slots = new Limiter(this.#sweepConcurrency);
790
+ const metas = await Promise.all(ids.map(async (id) => {
791
+ const release = await slots.acquire();
792
+ try {
793
+ const raw = await readFile(filesOf(place.folder, id).meta, { encoding: "utf8", flag: READ_FLAGS });
794
+ const meta = parseMeta(raw);
795
+ return meta && meta.id === id && !expired(meta, now) ? meta : undefined;
796
+ } catch (error) {
797
+ // Gone since the listing, or a link: not listed. In a folder the application shares, a
798
+ // file of a name the library does not make that it may not read is the application's, and
799
+ // is skipped, as sweep leaves it. Any other failure is the volume's.
800
+ if (this.#unreadable(place, error) || (place.shared && !DOCUMENT_ID_PATTERN.test(id) && (code(error) === "EACCES" || code(error) === "EPERM"))) return undefined;
801
+ throw error;
802
+ } finally {
803
+ release();
804
+ }
805
+ }));
806
+ return metas.filter((meta): meta is DocumentMeta => meta !== undefined);
807
+ }
808
+
809
+ /**
810
+ * Changes the fields of `patch` in the metadata of the document `id` whose `createdAt` is
811
+ * `patch.createdAt` (`DocumentStore.patchMeta`): the metadata is read, changed and written whole
812
+ * under a temporary name and then renamed, as `put` writes it, and no other file is touched.
813
+ * Changes of one document by this store take turns with each other and with its `put` and
814
+ * `delete`, so two at once both stay, and a document deleted and stored again meanwhile is never
815
+ * written over. Across servers sharing the folder nothing makes them take turns: a change on one
816
+ * server at the moment of a delete and a new `put` on another can still write the old metadata
817
+ * over the new document, or leave metadata without text (reads take it as missing, `getMeta` and
818
+ * `list` still show it until `sweep` removes it). The later write wins. Undefined when the document is not there, has expired, or is another one
819
+ * stored under the ID since, and nothing is written. A delete that ends between the read and the
820
+ * write would leave metadata without text: the text is looked for after the write, and without it
821
+ * the metadata is removed again and the answer is undefined (a delete on another server at the
822
+ * same moment can still leave it, which reads take as missing and `sweep` removes). New in 0.10.2.
823
+ */
824
+ async patchMeta(id: string, patch: MetaPatch, context?: DocumentContext): Promise<DocumentMeta | undefined> {
825
+ if (!fileId(id)) return undefined;
826
+ // A write, and maybe a removal: the folder of the scope is checked again, as for delete.
827
+ const place = await this.#find(context, true);
828
+ if (!place) return undefined;
829
+ const files = filesOf(place.folder, id);
830
+ return this.#inTurn(files.meta, async () => {
831
+ const meta = await this.#meta(place, id);
832
+ if (!meta || !patchedOne(meta, patch)) return undefined;
833
+ const next = patched(meta, patch);
834
+ const written = JSON.stringify(next);
835
+ await this.#write(place, files.meta, written);
836
+ const text = await lstat(files.text).catch((error: unknown) => (absent(error) ? undefined : null));
837
+ if (text === undefined) {
838
+ // A delete on another server ended meanwhile: the metadata just written is removed again,
839
+ // only while it is still what this call wrote (a document stored since is left alone).
840
+ const now = await readFile(files.meta, { encoding: "utf8", flag: READ_FLAGS }).catch(() => undefined);
841
+ if (now === written) await this.#remove(place, id).catch(() => undefined);
842
+ return undefined;
843
+ }
844
+ return next;
845
+ });
846
+ }
847
+
848
+ /** The changes of one file of this store, one at a time (`patchMeta`). */
849
+ readonly #turns = new Map<string, Promise<unknown>>();
850
+
851
+ async #inTurn<T>(key: string, work: () => Promise<T>): Promise<T> {
852
+ const before = this.#turns.get(key) ?? Promise.resolve();
853
+ const mine = before.catch(() => undefined).then(work);
854
+ const settled = mine.catch(() => undefined);
855
+ this.#turns.set(key, settled);
856
+ try {
857
+ return await mine;
858
+ } finally {
859
+ if (this.#turns.get(key) === settled) this.#turns.delete(key);
860
+ }
720
861
  }
721
862
 
722
863
  async putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void> {
@@ -866,7 +1007,10 @@ export class FileDocumentStore implements DocumentStore {
866
1007
  if (raw !== undefined) {
867
1008
  const meta = parseMeta(raw);
868
1009
  const known = meta !== undefined && (ours || meta.id === id);
869
- if (known ? expired(meta!, now) : ours && await old(metaFile)) {
1010
+ // Since 0.10.2, metadata whose text is gone is removed too, once it is old: a document
1011
+ // changed on one server while another deleted it can be left so, and reads take it as missing.
1012
+ const textless = known && ours && !names.includes(`${id}.txt`) && await old(metaFile);
1013
+ if (known ? expired(meta!, now) || textless : ours && await old(metaFile)) {
870
1014
  // 1 only when this sweep removed the metadata: another sweep at the same time may have.
871
1015
  return await pool(() => this.#remove(place, id)).then((existed) => (existed ? 1 : 0), () => 0);
872
1016
  }
@@ -881,3 +1025,26 @@ export class FileDocumentStore implements DocumentStore {
881
1025
  return 0;
882
1026
  }
883
1027
  }
1028
+
1029
+ /** The methods of a store that tell how it reads and writes a document: a subclass that changes one changes them all. */
1030
+ const CORE_METHODS = ["put", "get", "getMeta", "delete"] as const;
1031
+
1032
+ /**
1033
+ * The store's `list` or `patchMeta`, when the library may use it (0.10.2). A subclass of
1034
+ * `MemoryDocumentStore` or `FileDocumentStore` written for 0.10.1 that changes how documents are
1035
+ * read or written (its own `put`, `get`, `getMeta` or `delete`: a key prefix, encryption) inherits
1036
+ * the built-in `list` and `patchMeta`, which would go past those changes: they are not used for it,
1037
+ * as if it had none, until it has its own. Any other store's method is used as it is.
1038
+ */
1039
+ export function usableStoreMethod<K extends "list" | "patchMeta">(store: DocumentStore, name: K): DocumentStore[K] | undefined {
1040
+ const method = store[name];
1041
+ if (typeof method !== "function") return undefined;
1042
+ for (const Base of [MemoryDocumentStore, FileDocumentStore] as const) {
1043
+ if (!(store instanceof Base)) continue;
1044
+ const own = Base.prototype as unknown as DocumentStore;
1045
+ // The subclass's own: used.
1046
+ if (method !== own[name]) return method;
1047
+ return CORE_METHODS.some((core) => store[core] !== own[core]) ? undefined : method;
1048
+ }
1049
+ return method;
1050
+ }
@@ -4,6 +4,7 @@
4
4
  // (node:test), as the documentation of documentStoreChecks shows.
5
5
  import { DocumentScopeError } from "../errors.js";
6
6
  import { createLargeFiles, type LargeFiles } from "../library.js";
7
+ import { usableStoreMethod } from "../stores.js";
7
8
  import { MemoryDocumentStore } from "../stores.js";
8
9
  import type { DocumentContext, DocumentMeta, DocumentScope, DocumentStore } from "../types.js";
9
10
  import { serviceLog, utf8 } from "./fake-model.js";
@@ -29,7 +30,7 @@ export type StoreCheckEnvironment = {
29
30
  };
30
31
 
31
32
  /** A part of the store a check needs, which `skip` leaves out. */
32
- export type StoreCheckPart = "originals" | "ranges" | "index" | "sweep" | "shared";
33
+ export type StoreCheckPart = "originals" | "ranges" | "index" | "sweep" | "shared" | "list" | "meta";
33
34
 
34
35
  export type DocumentStoreChecksOptions = {
35
36
  /** A new store over new, empty storage, named by `environment.storage`. */
@@ -53,7 +54,10 @@ export type DocumentStoreChecksOptions = {
53
54
  * The parts the store does not have: "originals" (`putOriginal`, `getOriginal`), "ranges"
54
55
  * (`readTextRange`), "index" (`putIndex`, `getIndex`), "sweep", or "shared" for a store whose
55
56
  * storage two stores cannot share (`MemoryDocumentStore`). A check of a part the store lacks, and
56
- * that is not skipped, fails and says so.
57
+ * that is not skipped, fails and says so. Since 0.10.2, "list" (`list`) and "meta" (`patchMeta`):
58
+ * those are checked only when the store has them, so a store written for 0.10.1 passes as before
59
+ * (a subclass of a built-in store with its own put, get, getMeta or delete is checked only for
60
+ * a list or patchMeta of its own, as the library uses only those).
57
61
  */
58
62
  skip?: readonly StoreCheckPart[];
59
63
  };
@@ -234,7 +238,9 @@ let checksMade = 0;
234
238
  * ```
235
239
  *
236
240
  * Each check makes its own store with `create`, over storage of its own, and gives it to `dispose`
237
- * at the end. Checks are only added in minor versions. New in 0.9.0.
241
+ * at the end. A check a patch release adds runs only for a method the store did not have before
242
+ * (0.10.2: `list` and `patchMeta`, when the store has them), so a patch never fails a store that
243
+ * passed. New in 0.9.0.
238
244
  */
239
245
  export function documentStoreChecks(options: DocumentStoreChecksOptions): DocumentStoreCheck[] {
240
246
  if (typeof options?.create !== "function") throw new TypeError("documentStoreChecks needs a create function that makes a store.");
@@ -495,6 +501,71 @@ export function documentStoreChecks(options: DocumentStoreChecksOptions): Docume
495
501
  }));
496
502
  }
497
503
 
504
+ if (!skip.has("list")) {
505
+ checks.push(check("lists the documents of a scope, without the deleted, as copies (when it has list)", async ({ store, raw, start, context }) => {
506
+ // A store whose list the library would not use (a subclass of a built-in store with its own
507
+ // put, get, getMeta or delete, which inherits the built-in list) is not checked either.
508
+ if (!usableStoreMethod(raw, "list")) return;
509
+ const put = (id: string, expiresAt: number, which: "a" | "b" = "a") => must(() => store.put({ meta: metaFor(id, TEXT, start, expiresAt, { scope: [...scopes[which]], owner: `owner-${which}` }), text: TEXT }, context(which)), "put");
510
+ await put("check-list-1", start + DAY);
511
+ await put("check-list-2", start + 2 * DAY);
512
+ await put("check-list-gone", start + DAY);
513
+ await put("check-list-other", start + DAY, "b");
514
+ await must(() => store.delete("check-list-gone", context()), "delete");
515
+ // An expired document may be listed or not, by the store's clock: the library leaves it out.
516
+ const listed = await must(() => store.list!(context()), "list");
517
+ if (!Array.isArray(listed)) fail("list must give an array of metadata.");
518
+ const ids = listed.map((meta) => meta.id).sort();
519
+ for (const id of ["check-list-1", "check-list-2"]) if (!ids.includes(id)) fail(`list left out ${id}, a document of the scope.`);
520
+ if (ids.includes("check-list-gone")) fail("list gave check-list-gone, deleted.");
521
+ if (isolates && ids.includes("check-list-other")) fail("list gave a document of another scope: a store that keeps scopes apart (isolatesScopes) lists one scope.");
522
+ const first = listed.find((meta) => meta.id === "check-list-1")!;
523
+ same(first, metaFor("check-list-1", TEXT, start, start + DAY, { scope: [...scopes.a], owner: "owner-a" }), "the metadata list gave");
524
+ first.name = "changed.txt";
525
+ same((await store.getMeta("check-list-1", context()))?.name, "notes.txt", "getMeta(id).name after the caller changed the metadata list gave");
526
+ }));
527
+ }
528
+
529
+ if (!skip.has("meta")) {
530
+ checks.push(check("changes the fields of patchMeta alone, of the document of that createdAt, owner and scope only (when it has patchMeta)", async ({ store, raw, start, context }) => {
531
+ if (!usableStoreMethod(raw, "patchMeta")) return;
532
+ const meta = metaFor("check-meta", TEXT, start, start + DAY, { scope: [...scopes.a], owner: "owner-a", appData: { row: "1" } });
533
+ await must(() => store.put({ meta, text: TEXT }, context()), "put");
534
+ const later = new Date(start + 3 * DAY).toISOString();
535
+ const expected = { ...meta, expiresAt: later, appData: { row: "42", tags: ["a"] } };
536
+ same(await must(() => store.patchMeta!("check-meta", { createdAt: meta.createdAt, owner: "owner-a", scope: [...scopes.a], expiresAt: later, appData: { row: "42", tags: ["a"] } }, context()), "patchMeta"), expected, "what patchMeta gave for a document that is there");
537
+ same(await store.getMeta("check-meta", context()), expected, "getMeta(id) after patchMeta");
538
+ same((await store.get("check-meta", context()))?.text, TEXT, "get(id).text after patchMeta, which must not change");
539
+ // An earlier expiry is not taken: the later of the two stays. appData: null removes it.
540
+ const { appData: _removed, ...withoutData } = expected;
541
+ same(await must(() => store.patchMeta!("check-meta", { createdAt: meta.createdAt, owner: "owner-a", scope: [...scopes.a], expiresAt: new Date(start + DAY).toISOString(), appData: null }, context()), "patchMeta"), withoutData, "patchMeta with an earlier expiry and appData: null");
542
+ // Another createdAt is another document, stored under the ID since: nothing is changed.
543
+ same(await must(() => store.patchMeta!("check-meta", { createdAt: new Date(start + 1).toISOString(), owner: "owner-a", scope: [...scopes.a], appData: { row: "x" } }, context()), "patchMeta"), undefined, "patchMeta for another createdAt");
544
+ same(await store.getMeta("check-meta", context()), withoutData, "getMeta(id) after patchMeta for another createdAt, which must change nothing");
545
+ // Another owner, or no owner, is another document, even of the same createdAt.
546
+ same(await must(() => store.patchMeta!("check-meta", { createdAt: meta.createdAt, owner: "owner-b", scope: [...scopes.a], appData: { row: "x" } }, context()), "patchMeta"), undefined, "patchMeta for another owner");
547
+ same(await must(() => store.patchMeta!("check-meta", { createdAt: meta.createdAt, scope: [...scopes.a], appData: { row: "x" } }, context()), "patchMeta"), undefined, "patchMeta for no owner, of a document that has one");
548
+ same(await store.getMeta("check-meta", context()), withoutData, "getMeta(id) after patchMeta for another owner, which must change nothing");
549
+ same(await must(() => store.patchMeta!("check-meta-unknown", { createdAt: meta.createdAt, owner: "owner-a", scope: [...scopes.a], appData: { row: "x" } }, context()), "patchMeta"), undefined, "patchMeta of an unknown ID");
550
+ same(await store.getMeta("check-meta-unknown", context()), undefined, "getMeta(id) after patchMeta of an unknown ID, which must write nothing");
551
+ await store.delete("check-meta", context());
552
+ same(await must(() => store.patchMeta!("check-meta", { createdAt: meta.createdAt, owner: "owner-a", scope: [...scopes.a], expiresAt: later }, context()), "patchMeta"), undefined, "patchMeta after delete");
553
+ same(await store.getMeta("check-meta", context()), undefined, "getMeta(id) after patchMeta of a deleted document");
554
+ }));
555
+
556
+ checks.push(check("keeps both of two patchMeta calls made at once (when it has patchMeta)", async ({ store, raw, start, context }) => {
557
+ if (!usableStoreMethod(raw, "patchMeta")) return;
558
+ const meta = metaFor("check-meta-both", TEXT, start, start + DAY, { scope: [...scopes.a], owner: "owner-a" });
559
+ await must(() => store.put({ meta, text: TEXT }, context()), "put");
560
+ const later = new Date(start + 2 * DAY).toISOString();
561
+ await Promise.all([
562
+ must(() => store.patchMeta!("check-meta-both", { createdAt: meta.createdAt, owner: "owner-a", scope: [...scopes.a], expiresAt: later }, context()), "patchMeta"),
563
+ must(() => store.patchMeta!("check-meta-both", { createdAt: meta.createdAt, owner: "owner-a", scope: [...scopes.a], appData: { row: "7" } }, context()), "patchMeta"),
564
+ ]);
565
+ same(await store.getMeta("check-meta-both", context()), { ...meta, expiresAt: later, appData: { row: "7" } }, "getMeta(id) after two patchMeta calls at once, the expiry of one and the appData of the other");
566
+ }));
567
+ }
568
+
498
569
  checks.push(check("keeps documents under the IDs an application may choose", async ({ store, start, context }) => {
499
570
  const ids = ["a", "0", "upload-3f9a", "a_b-c", `x${"0".repeat(63)}`, `doc_${"0123456789abcdef".repeat(2)}`];
500
571
  for (const id of ids) await must(() => store.put({ meta: metaFor(id, `${TEXT} ${id}`, start, start + DAY), text: `${TEXT} ${id}` }, context()), `put of the ID "${id}"`);
package/src/types.ts CHANGED
@@ -130,6 +130,42 @@ export type DocumentMeta = {
130
130
  scripts?: Array<{ script: string; percent: number }>;
131
131
  createdAt: string;
132
132
  expiresAt: string;
133
+ /**
134
+ * The application's own data about the document (`IngestInput.appData`, `files.update`): a JSON
135
+ * object of at most `MAX_APP_DATA_BYTES` (16 KB) as JSON, such as the ID of its row in your
136
+ * database or a label. The library keeps it with the metadata and does nothing else with it: it
137
+ * is never sent to the model, nor in a summary. An event holds it only with
138
+ * `AskOptions.eventResults: true`, in the full plan of `run.finish` and `run.error`. New in 0.10.2.
139
+ */
140
+ appData?: AppData;
141
+ };
142
+
143
+ /** A value JSON can hold: what `DocumentMeta.appData` is made of. New in 0.10.2. */
144
+ export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
145
+
146
+ /** The application's own data about a document (`DocumentMeta.appData`): a JSON object. New in 0.10.2. */
147
+ export type AppData = { [key: string]: JsonValue };
148
+
149
+ /**
150
+ * What `DocumentStore.patchMeta` changes in the metadata of one document. New in 0.10.2.
151
+ */
152
+ export type MetaPatch = {
153
+ /**
154
+ * The `createdAt` of the document to change. A document stored again under the same ID since
155
+ * (deleted, then ingested again) has another, and is not changed.
156
+ */
157
+ createdAt: string;
158
+ /**
159
+ * The owner of the document to change, absent for none: a document of another owner, even of the
160
+ * same `createdAt`, is not changed. Compare as `owner ?? undefined` (null is none).
161
+ */
162
+ owner?: string;
163
+ /** The scope of the document to change, absent for none, compared segment by segment, as `owner` is. */
164
+ scope?: DocumentScope;
165
+ /** A later expiry: the stored `expiresAt` becomes the later of the two, as ISO 8601 dates compare. */
166
+ expiresAt?: string;
167
+ /** The application's own data: replaces `appData` whole, or removes it when null. */
168
+ appData?: AppData | null;
133
169
  };
134
170
 
135
171
  export type StoredDocument = { meta: DocumentMeta; text: string };
@@ -192,6 +228,25 @@ export interface DocumentStore {
192
228
  putIndex?(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
193
229
  /** The index kept by `putIndex`, or undefined. A damaged one is noticed and built again. */
194
230
  getIndex?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
231
+ /**
232
+ * The metadata of the documents of the scope of `context`, in any order: those stored without a
233
+ * scope when it has none. A store that keeps no scopes apart gives every document it has. It may
234
+ * leave out the expired ones, or give them: the library leaves them out. Optional:
235
+ * `files.list()` and `ingest({ dedupe })` need it. A store of many documents should answer
236
+ * from an index (a database query on the scope), not by reading each one. New in 0.10.2.
237
+ */
238
+ list?(context?: DocumentContext): Promise<DocumentMeta[]>;
239
+ /**
240
+ * Changes the fields of `patch` in the metadata of the document `id` whose `createdAt`, owner and
241
+ * scope are `patch`'s, and nothing else: its other fields, its text, line index and original stay
242
+ * as they are. Returns the metadata as it is after the change, or undefined when no such document
243
+ * is there (unknown, deleted, expired, or another one stored under the ID since), and nothing was
244
+ * written. Apply the fields to what is stored at the time of the write, not to a copy read
245
+ * before: two changes at once (a `touch` and an `update`) must both stay. A database does it in
246
+ * one conditional update (`$max` on the expiry, `$set`/`$unset` on `appData`). Optional:
247
+ * `files.touch()`, `files.update()` and `ingest({ dedupe })` use it. New in 0.10.2.
248
+ */
249
+ patchMeta?(id: string, patch: MetaPatch, context?: DocumentContext): Promise<DocumentMeta | undefined>;
195
250
  }
196
251
 
197
252
  export type ExtractedText = {