llm-large-files 0.8.2 → 0.9.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.
Files changed (201) hide show
  1. package/CHANGELOG.md +535 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +169 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +324 -591
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.js +3 -3
  60. package/dist/map-reduce.js.map +1 -1
  61. package/dist/model.d.ts +43 -2
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +63 -3
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts +226 -14
  66. package/dist/node/handlers.d.ts.map +1 -1
  67. package/dist/node/handlers.js +423 -181
  68. package/dist/node/handlers.js.map +1 -1
  69. package/dist/node/index.d.ts +3 -2
  70. package/dist/node/index.d.ts.map +1 -1
  71. package/dist/node/index.js +2 -1
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/node/ingest-child.d.ts +7 -1
  74. package/dist/node/ingest-child.d.ts.map +1 -1
  75. package/dist/node/ingest-child.js +18 -3
  76. package/dist/node/ingest-child.js.map +1 -1
  77. package/dist/node/isolated.d.ts +3 -1
  78. package/dist/node/isolated.d.ts.map +1 -1
  79. package/dist/node/isolated.js +11 -4
  80. package/dist/node/isolated.js.map +1 -1
  81. package/dist/node/originals.d.ts +19 -0
  82. package/dist/node/originals.d.ts.map +1 -0
  83. package/dist/node/originals.js +82 -0
  84. package/dist/node/originals.js.map +1 -0
  85. package/dist/node/spool.d.ts +102 -0
  86. package/dist/node/spool.d.ts.map +1 -0
  87. package/dist/node/spool.js +365 -0
  88. package/dist/node/spool.js.map +1 -0
  89. package/dist/node/sse.d.ts +4 -3
  90. package/dist/node/sse.d.ts.map +1 -1
  91. package/dist/node/sse.js +7 -6
  92. package/dist/node/sse.js.map +1 -1
  93. package/dist/pdf-layout.d.ts.map +1 -1
  94. package/dist/pdf-layout.js +71 -12
  95. package/dist/pdf-layout.js.map +1 -1
  96. package/dist/ranged.d.ts +15 -11
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +42 -11
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/retry.d.ts +3 -1
  101. package/dist/retry.d.ts.map +1 -1
  102. package/dist/retry.js +6 -2
  103. package/dist/retry.js.map +1 -1
  104. package/dist/scope.d.ts +25 -0
  105. package/dist/scope.d.ts.map +1 -0
  106. package/dist/scope.js +60 -0
  107. package/dist/scope.js.map +1 -0
  108. package/dist/source.d.ts +60 -0
  109. package/dist/source.d.ts.map +1 -0
  110. package/dist/source.js +170 -0
  111. package/dist/source.js.map +1 -0
  112. package/dist/stores.d.ts +120 -31
  113. package/dist/stores.d.ts.map +1 -1
  114. package/dist/stores.js +582 -139
  115. package/dist/stores.js.map +1 -1
  116. package/dist/testing/fake-fetch.d.ts +31 -0
  117. package/dist/testing/fake-fetch.d.ts.map +1 -0
  118. package/dist/testing/fake-fetch.js +66 -0
  119. package/dist/testing/fake-fetch.js.map +1 -0
  120. package/dist/testing/fake-model.d.ts +38 -0
  121. package/dist/testing/fake-model.d.ts.map +1 -0
  122. package/dist/testing/fake-model.js +62 -0
  123. package/dist/testing/fake-model.js.map +1 -0
  124. package/dist/testing/index.d.ts +7 -0
  125. package/dist/testing/index.d.ts.map +1 -0
  126. package/dist/testing/index.js +9 -0
  127. package/dist/testing/index.js.map +1 -0
  128. package/dist/testing/store-checks.d.ts +72 -0
  129. package/dist/testing/store-checks.d.ts.map +1 -0
  130. package/dist/testing/store-checks.js +619 -0
  131. package/dist/testing/store-checks.js.map +1 -0
  132. package/dist/tools.d.ts +25 -0
  133. package/dist/tools.d.ts.map +1 -1
  134. package/dist/tools.js +135 -13
  135. package/dist/tools.js.map +1 -1
  136. package/dist/types.d.ts +116 -13
  137. package/dist/types.d.ts.map +1 -1
  138. package/docs/README.md +17 -8
  139. package/docs/getting-started.md +18 -13
  140. package/docs/guides/anthropic.md +12 -8
  141. package/docs/guides/conversations.md +112 -47
  142. package/docs/guides/costs-and-limits.md +16 -7
  143. package/docs/guides/deployment.md +284 -83
  144. package/docs/guides/errors-and-reliability.md +161 -23
  145. package/docs/guides/own-adapter-and-loop.md +27 -10
  146. package/docs/guides/pdfs.md +123 -29
  147. package/docs/guides/storage.md +633 -145
  148. package/docs/guides/testing.md +78 -129
  149. package/docs/guides/vertex-and-gemini.md +10 -7
  150. package/docs/guides/web-app.md +312 -78
  151. package/docs/how-it-works.md +35 -8
  152. package/docs/measurements.md +43 -8
  153. package/docs/publishing.md +112 -36
  154. package/docs/reference/ask.md +154 -13
  155. package/docs/reference/errors-and-retries.md +166 -14
  156. package/docs/reference/events.md +53 -20
  157. package/docs/reference/gemini.md +70 -21
  158. package/docs/reference/library.md +706 -165
  159. package/docs/reference/node.md +624 -110
  160. package/docs/reference/testing.md +311 -0
  161. package/docs/reference/tools.md +15 -5
  162. package/docs/security.md +304 -67
  163. package/docs/troubleshooting.md +144 -65
  164. package/docs/upgrading-0.9.md +890 -0
  165. package/package.json +12 -3
  166. package/src/access.ts +144 -0
  167. package/src/ask.ts +230 -19
  168. package/src/cache.ts +20 -5
  169. package/src/encoding.ts +6 -4
  170. package/src/error-info.ts +255 -0
  171. package/src/errors.ts +129 -15
  172. package/src/events.ts +86 -21
  173. package/src/evidence.ts +14 -3
  174. package/src/extract.ts +50 -33
  175. package/src/gemini/adapter.ts +97 -11
  176. package/src/gemini/chat.ts +20 -6
  177. package/src/gemini/index.ts +1 -1
  178. package/src/index.ts +9 -6
  179. package/src/ingest.ts +927 -0
  180. package/src/library.ts +467 -601
  181. package/src/map-reduce.ts +3 -3
  182. package/src/model.ts +69 -5
  183. package/src/node/handlers.ts +630 -183
  184. package/src/node/index.ts +13 -2
  185. package/src/node/ingest-child.ts +23 -5
  186. package/src/node/isolated.ts +11 -4
  187. package/src/node/originals.ts +78 -0
  188. package/src/node/spool.ts +365 -0
  189. package/src/node/sse.ts +7 -6
  190. package/src/pdf-layout.ts +69 -11
  191. package/src/ranged.ts +34 -13
  192. package/src/retry.ts +6 -2
  193. package/src/scope.ts +63 -0
  194. package/src/source.ts +178 -0
  195. package/src/stores.ts +635 -140
  196. package/src/testing/fake-fetch.ts +80 -0
  197. package/src/testing/fake-model.ts +78 -0
  198. package/src/testing/index.ts +11 -0
  199. package/src/testing/store-checks.ts +660 -0
  200. package/src/tools.ts +150 -14
  201. package/src/types.ts +106 -13
package/dist/stores.js CHANGED
@@ -1,69 +1,175 @@
1
- import { randomUUID } from "node:crypto";
2
- import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
3
4
  import path from "node:path";
5
+ import { DocumentScopeError } from "./errors.js";
6
+ import { Limiter } from "./limiter.js";
7
+ import { checkScope, MAX_SCOPE_SEGMENTS, scopeKey } from "./scope.js";
8
+ /** The shape of the document IDs the library makes: "doc_" and 32 hex digits. */
4
9
  export const DOCUMENT_ID_PATTERN = /^doc_[a-f0-9]{32}$/;
10
+ /**
11
+ * The shape of a document ID an application may choose (`IngestInput.id`): lowercase letters,
12
+ * digits, "_" and "-", up to 64 characters, starting with a letter or a digit, and not a name
13
+ * Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0`-`com9`, `lpt0`-`lpt9`), which
14
+ * cannot name a file there. The IDs the library makes have it too. New in 0.9.0.
15
+ */
16
+ export const APP_DOCUMENT_ID_PATTERN = /^(?!(?:con|prn|aux|nul|com[0-9]|lpt[0-9])$)[a-z0-9][a-z0-9_-]{0,63}$/;
17
+ /**
18
+ * The version of `DocumentMeta` this package writes (`metaVersion`), and the highest it reads.
19
+ * New in 0.9.0: metadata without a version is that of an earlier version, and is read as before.
20
+ */
21
+ export const DOCUMENT_META_VERSION = 1;
5
22
  function expired(meta, now = new Date()) {
6
23
  return Date.parse(meta.expiresAt) <= now.getTime();
7
24
  }
8
- /** Keeps documents in process memory. Good for tests and single-process demos. */
25
+ /**
26
+ * Keeps documents in process memory. Good for tests and single-process demos.
27
+ *
28
+ * The documents of each scope (`DocumentContext.scope`) are kept apart: one ID in two scopes is two
29
+ * documents. Calls without a scope share the documents of no scope, as every call did before 0.9.0.
30
+ */
9
31
  export class MemoryDocumentStore {
32
+ /** The documents of no scope, by ID, as all documents were kept before 0.9.0. */
10
33
  documents = new Map();
34
+ /** The original files of the documents of no scope. */
11
35
  originals = new Map();
36
+ #unscoped = { scope: undefined, documents: this.documents, originals: this.originals };
37
+ /** The documents of each scope, by the key of the scope (`scopeKey`). */
38
+ #scoped = new Map();
12
39
  now;
13
40
  constructor(options = {}) {
14
41
  this.now = options.now ?? (() => new Date());
15
42
  }
43
+ #shelf(context, create = false) {
44
+ const scope = checkScope(context?.scope);
45
+ if (scope === undefined)
46
+ return this.#unscoped;
47
+ const key = scopeKey(scope);
48
+ let shelf = this.#scoped.get(key);
49
+ if (!shelf && create) {
50
+ shelf = { scope, documents: new Map(), originals: new Map() };
51
+ this.#scoped.set(key, shelf);
52
+ }
53
+ return shelf;
54
+ }
16
55
  // The metadata is copied on the way in and on the way out, as a store that writes it somewhere
17
56
  // does: an app that changes the metadata it was handed (deletes its owner before sending it to a
18
57
  // browser) must not change the document's owner or expiry.
19
- async put(document) {
20
- this.documents.set(document.meta.id, { meta: structuredClone(document.meta), text: document.text });
58
+ async put(document, context) {
59
+ this.#shelf(context, true).documents.set(document.meta.id, { meta: structuredClone(document.meta), text: document.text });
21
60
  }
22
- async get(id) {
23
- const document = this.documents.get(id);
61
+ async get(id, context) {
62
+ const document = this.#shelf(context)?.documents.get(id);
24
63
  if (document && expired(document.meta, this.now())) {
25
- await this.delete(id);
64
+ await this.delete(id, context);
26
65
  return undefined;
27
66
  }
28
67
  return document && { meta: structuredClone(document.meta), text: document.text };
29
68
  }
30
- async getMeta(id) {
31
- return (await this.get(id))?.meta;
69
+ async getMeta(id, context) {
70
+ return (await this.get(id, context))?.meta;
32
71
  }
33
- async delete(id) {
34
- this.originals.delete(id);
35
- return this.documents.delete(id);
72
+ async delete(id, context) {
73
+ const shelf = this.#shelf(context);
74
+ if (!shelf)
75
+ return false;
76
+ shelf.originals.delete(id);
77
+ const existed = shelf.documents.delete(id);
78
+ // A scope with nothing left takes no memory: one for each chat would add up.
79
+ if (shelf !== this.#unscoped && shelf.documents.size === 0 && shelf.originals.size === 0)
80
+ this.#scoped.delete(scopeKey(shelf.scope));
81
+ return existed;
36
82
  }
37
- async sweep(now = this.now()) {
83
+ /** Removes expired documents: those of the scope of `context`, or those of every scope when it has none. */
84
+ async sweep(now = this.now(), context) {
85
+ const shelves = context?.scope === undefined ? [this.#unscoped, ...this.#scoped.values()] : [this.#shelf(context)];
38
86
  let removed = 0;
39
- for (const [id, document] of this.documents) {
40
- if (expired(document.meta, now)) {
41
- await this.delete(id);
42
- removed++;
87
+ for (const shelf of shelves) {
88
+ if (!shelf)
89
+ continue;
90
+ for (const [id, document] of shelf.documents) {
91
+ if (expired(document.meta, now)) {
92
+ await this.delete(id, shelf.scope === undefined ? undefined : { scope: shelf.scope });
93
+ removed++;
94
+ }
43
95
  }
44
96
  }
45
97
  return removed;
46
98
  }
47
- async putOriginal(id, bytes) {
99
+ async putOriginal(id, bytes, context) {
48
100
  // A copy: the caller may reuse its buffer after the upload.
49
- this.originals.set(id, bytes.slice());
101
+ this.#shelf(context, true).originals.set(id, bytes.slice());
50
102
  }
51
- async getOriginal(id) {
52
- return await this.get(id) ? this.originals.get(id) : undefined;
103
+ async getOriginal(id, context) {
104
+ // A copy too, new in 0.9.0: a caller that changed the bytes it was handed changed the stored file.
105
+ return await this.get(id, context) ? this.#shelf(context)?.originals.get(id)?.slice() : undefined;
53
106
  }
54
107
  }
55
- /** The files of a document, and the temporary files written on the way to them. */
56
- const FILE_NAME = /^(doc_[a-f0-9]{32})\.(json|txt|bin|idx)(\.[a-f0-9]{8}\.tmp)?$/;
57
108
  /**
58
- * Errors a rename can meet on Windows while another process (a reader, an antivirus scanner) has
59
- * the file open for a moment. Retried with growing pauses for up to about three seconds, as
60
- * graceful-fs does.
109
+ * The files of a document, and the temporary files written on the way to them. Since 0.9.0 the ID
110
+ * may be an application's (`APP_DOCUMENT_ID_PATTERN`), which the IDs the library makes fit too.
111
+ */
112
+ const FILE_NAME = /^([a-z0-9][a-z0-9_-]{0,63})\.(json|txt|bin|idx)(\.[a-f0-9]{8}\.tmp)?$/;
113
+ /**
114
+ * Names Windows keeps for devices, with or without an extension: `con.json` is the console, not a
115
+ * file. Refused as scope segments and as file names, since a volume may be shared with Windows.
61
116
  */
62
- const RETRY_RENAME = new Set(["EPERM", "EACCES", "EBUSY"]);
63
- const RENAME_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
117
+ const DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/;
118
+ /** A name of one folder of a scope (`isSafeScopeSegment`): the shape of an application's document ID. */
119
+ const SAFE_SEGMENT = /^[a-z0-9][a-z0-9_-]{0,63}$/;
120
+ /** A name of the store's own folder in each scope's folder (`scopes.folder`). */
121
+ const FOLDER_NAME = /^[A-Za-z0-9._-]{1,64}$/;
122
+ /**
123
+ * Errors a rename or a removal can meet on Windows while another process (a reader, an antivirus
124
+ * scanner) has the file open for a moment. Tried again after each of these pauses, as graceful-fs
125
+ * does: ten more tries, and 2,630 ms of pauses in all, so about 2.6 seconds.
126
+ */
127
+ const RETRY_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
128
+ const RETRY_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
64
129
  const code = (error) => error?.code;
65
130
  /** There is no such file. Every other failure (a volume that does not answer, too many open files) says nothing about the file. */
66
131
  const missing = (error) => code(error) === "ENOENT";
132
+ /** There is no such file or folder, or a part of its path is a file. */
133
+ const absent = (error) => code(error) === "ENOENT" || code(error) === "ENOTDIR";
134
+ /** The file is a link, which a read does not follow (READ_FLAGS): Linux and macOS say ELOOP, FreeBSD EMLINK. */
135
+ const linked = (error) => code(error) === "ELOOP" || code(error) === "EMLINK";
136
+ /**
137
+ * How a document's file is opened for reading: without following a link at its name, where the
138
+ * platform can (`O_NOFOLLOW`; Windows has none). Folders are checked by their real path instead.
139
+ */
140
+ const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0);
141
+ /** The refusal of a folder of a scope that is a link, or under one. */
142
+ const LINKED_FOLDER = "The folder of the scope is a link, or inside one: this store follows no folder links below its directory.";
143
+ /**
144
+ * How long a read takes a folder of a scope that passed its check as still checked, and how many
145
+ * such folders a store remembers. Writes, deletes and removals always check again.
146
+ */
147
+ const CHECK_KEPT_MS = 1_000;
148
+ const CHECKS_KEPT = 4_096;
149
+ /**
150
+ * Whether `value` can name a folder of a scope in a `FileDocumentStore` with `scopes`: lowercase
151
+ * letters, digits, "_" and "-", 1 to 64 characters, starting with a letter or a digit, and not a
152
+ * name Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0`-`com9`, `lpt0`-`lpt9`). Lower
153
+ * case only, because SMB and Azure Files ignore case: `Alice` and `alice` would be one folder. Use
154
+ * `hashedScopeSegment` for an ID that does not pass. New in 0.9.0.
155
+ */
156
+ export function isSafeScopeSegment(value) {
157
+ return typeof value === "string" && SAFE_SEGMENT.test(value) && !DEVICE_NAME.test(value);
158
+ }
159
+ /**
160
+ * A segment that `isSafeScopeSegment` accepts, made from any string: "h" and the first 40 hex
161
+ * digits of its SHA-256. For user or chat IDs in mixed case, or in Hebrew. The same value always
162
+ * gives the same segment, and two values almost surely two. Use it for every value of that level of
163
+ * the scope, not only for those that would not pass, and pass the result as the scope's segment:
164
+ * the store never hashes on its own. New in 0.9.0.
165
+ */
166
+ export function hashedScopeSegment(value) {
167
+ if (typeof value !== "string" || value.length === 0)
168
+ throw new TypeError("hashedScopeSegment needs a string that is not empty.");
169
+ return `h${createHash("sha256").update(value, "utf8").digest("hex").slice(0, 40)}`;
170
+ }
171
+ /** An ID that may become a file name: an application's ID shape, and not a device name. */
172
+ const fileId = (id) => typeof id === "string" && APP_DOCUMENT_ID_PATTERN.test(id) && !DEVICE_NAME.test(id);
67
173
  /** Metadata as it was written, or undefined for text that is not that: cut short, or damaged. */
68
174
  function parseMeta(raw) {
69
175
  try {
@@ -74,35 +180,71 @@ function parseMeta(raw) {
74
180
  return undefined;
75
181
  }
76
182
  }
183
+ /** Runs `task`, and again after each pause of RETRY_PAUSES_MS while it fails with a code of RETRY_CODES. */
184
+ async function retried(task) {
185
+ for (let attempt = 0;; attempt++) {
186
+ try {
187
+ return await task();
188
+ }
189
+ catch (error) {
190
+ if (attempt >= RETRY_PAUSES_MS.length || !RETRY_CODES.has(code(error)))
191
+ throw error;
192
+ await new Promise((resolve) => setTimeout(resolve, RETRY_PAUSES_MS[attempt]));
193
+ }
194
+ }
195
+ }
196
+ /**
197
+ * Removes a file, trying again as a rename is (Node's own `rm` retries neither `EACCES` nor a file
198
+ * without `recursive`). True when it was there, false when it was not.
199
+ */
200
+ async function removeFile(file) {
201
+ try {
202
+ await retried(() => unlink(file));
203
+ return true;
204
+ }
205
+ catch (error) {
206
+ if (missing(error))
207
+ return false;
208
+ throw error;
209
+ }
210
+ }
77
211
  /**
78
212
  * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
79
213
  * renamed. A server reading a shared volume never sees half of a file another server is writing.
214
+ * The temporary file is made with `mode`, and the rename keeps it.
80
215
  */
81
- async function writeWhole(target, data) {
216
+ async function writeWhole(target, data, mode) {
82
217
  const temporary = `${target}.${randomUUID().slice(0, 8)}.tmp`;
83
218
  try {
84
- await writeFile(temporary, data);
85
- for (let attempt = 0;; attempt++) {
86
- try {
87
- await rename(temporary, target);
88
- return;
89
- }
90
- catch (error) {
91
- if (attempt >= RENAME_PAUSES_MS.length || !RETRY_RENAME.has(code(error)))
92
- throw error;
93
- await new Promise((resolve) => setTimeout(resolve, RENAME_PAUSES_MS[attempt]));
94
- }
95
- }
219
+ await writeFile(temporary, data, { mode });
220
+ await retried(() => rename(temporary, target));
96
221
  }
97
222
  catch (error) {
98
223
  await rm(temporary, { force: true }).catch(() => undefined);
99
224
  throw error;
100
225
  }
101
226
  }
227
+ /** The files of a document in `folder`. */
228
+ function filesOf(folder, id) {
229
+ const file = (extension) => path.join(folder, `${id}.${extension}`);
230
+ return { text: file("txt"), meta: file("json"), original: file("bin"), index: file("idx") };
231
+ }
232
+ function checkMode(name, value, fallback) {
233
+ if (value === undefined)
234
+ return fallback;
235
+ if (!Number.isInteger(value) || value < 0 || value > 0o777)
236
+ throw new TypeError(`${name} must be a file mode from 0 to 0o777, such as 0o640.`);
237
+ return value;
238
+ }
102
239
  /**
103
240
  * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
104
241
  * server restart, its line index as `<id>.idx`, and its original file as `<id>.bin` when one is
105
- * kept. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
242
+ * kept. Only IDs matching APP_DOCUMENT_ID_PATTERN (which leaves out names Windows keeps for
243
+ * devices) ever reach the file system. Those names, for every ID it is given, are the store's: keep
244
+ * files of your own in a subfolder. A read does not follow a link at a file name, except on Windows.
245
+ *
246
+ * With `scopes`, the documents of each scope are kept in a folder of their own:
247
+ * `<directory>/<userId>/<chatId>/.llm-large-files/<id>.json`. New in 0.9.0.
106
248
  *
107
249
  * Several servers may share the directory (a network volume): every file is written whole under
108
250
  * a temporary name and then renamed, a tool call reads only the lines it needs (`readTextRange`),
@@ -112,38 +254,235 @@ export class FileDocumentStore {
112
254
  directory;
113
255
  now;
114
256
  orphanAgeMs;
257
+ #scopes;
258
+ #fileMode;
259
+ #directoryMode;
260
+ #sweepConcurrency;
261
+ /** The directory, with links resolved, once it was found. */
262
+ #realDirectory;
263
+ /** The folders of scopes that passed `#checkReal`, and when (`Date.now()`), the oldest first. */
264
+ #checked = new Map();
115
265
  constructor(directory, options = {}) {
116
266
  this.directory = directory;
117
267
  this.now = options.now ?? (() => new Date());
118
268
  this.orphanAgeMs = options.orphanAgeMs ?? 60 * 60 * 1000;
269
+ this.#fileMode = checkMode("fileMode", options.fileMode, 0o600);
270
+ this.#directoryMode = checkMode("directoryMode", options.directoryMode, 0o700);
271
+ const concurrency = options.sweepConcurrency ?? 16;
272
+ if (!Number.isInteger(concurrency) || concurrency < 1)
273
+ throw new TypeError("sweepConcurrency must be a whole number of 1 or more.");
274
+ this.#sweepConcurrency = concurrency;
275
+ const scopes = options.scopes;
276
+ if (scopes === undefined) {
277
+ this.#scopes = undefined;
278
+ return;
279
+ }
280
+ if (!Number.isInteger(scopes.depth) || scopes.depth < 1 || scopes.depth > MAX_SCOPE_SEGMENTS) {
281
+ throw new TypeError(`scopes.depth must be a whole number from 1 to ${MAX_SCOPE_SEGMENTS}.`);
282
+ }
283
+ const folder = scopes.folder ?? ".llm-large-files";
284
+ if (folder !== "" && (!FOLDER_NAME.test(folder) || folder === "." || folder === "..")) {
285
+ throw new TypeError('scopes.folder must be "" or the name of one folder: letters, digits, ".", "_" and "-", such as ".llm-large-files".');
286
+ }
287
+ const unscoped = scopes.unscoped ?? "refuse";
288
+ if (unscoped !== "refuse" && unscoped !== "root")
289
+ throw new TypeError('scopes.unscoped must be "refuse" or "root".');
290
+ this.#scopes = { depth: scopes.depth, folder, createScopeFolders: scopes.createScopeFolders === true, unscoped };
119
291
  }
120
- paths(id) {
121
- if (!DOCUMENT_ID_PATTERN.test(id))
122
- return undefined;
123
- const file = (extension) => path.join(this.directory, `${id}.${extension}`);
124
- return { text: file("txt"), meta: file("json"), original: file("bin"), index: file("idx") };
292
+ /** The scope of a call, checked against the rules of this store, or undefined for none. */
293
+ #scopeOf(context) {
294
+ const scope = checkScope(context?.scope);
295
+ if (scope === undefined || this.#scopes === undefined)
296
+ return scope;
297
+ if (scope.length !== this.#scopes.depth) {
298
+ throw new DocumentScopeError("scope_invalid", `This store keeps scopes of ${this.#scopes.depth} segments (scopes.depth); the scope has ${scope.length}.`);
299
+ }
300
+ scope.forEach((segment, index) => {
301
+ if (!isSafeScopeSegment(segment)) {
302
+ throw new DocumentScopeError("scope_invalid", `scope segment ${index + 1} cannot name a folder: use lowercase letters, digits, "_" and "-", up to 64 characters, and no name Windows keeps for a device (isSafeScopeSegment), or hashedScopeSegment(value).`);
303
+ }
304
+ });
305
+ return scope;
306
+ }
307
+ /** The directory itself: that of a store without scopes, or of a call without a scope under `unscoped: "root"`. */
308
+ #root() {
309
+ if (this.#scopes && this.#scopes.unscoped !== "root")
310
+ throw new DocumentScopeError("scope_required");
311
+ return { folder: this.directory, shared: true, scoped: false };
312
+ }
313
+ /** The folder of a scope, and that of the store in it. */
314
+ #folders(scope) {
315
+ const scopeFolder = path.join(this.directory, ...scope);
316
+ return { scope: scopeFolder, documents: this.#scopes.folder ? path.join(scopeFolder, this.#scopes.folder) : scopeFolder };
317
+ }
318
+ /**
319
+ * Checks that `folder` is where its path says, with no link on the way below the directory, and
320
+ * so inside the directory. Throws its error when it is not there. A folder that passes is
321
+ * remembered for CHECK_KEPT_MS, for reads (`#find`); one that fails is forgotten.
322
+ */
323
+ async #checkReal(folder) {
324
+ try {
325
+ const real = await realpath(folder);
326
+ this.#realDirectory ??= realpath(this.directory);
327
+ let directory;
328
+ try {
329
+ directory = await this.#realDirectory;
330
+ }
331
+ catch (error) {
332
+ this.#realDirectory = undefined;
333
+ throw error;
334
+ }
335
+ if (real !== path.join(directory, path.relative(this.directory, folder)))
336
+ throw new DocumentScopeError("scope_invalid", LINKED_FOLDER);
337
+ }
338
+ catch (error) {
339
+ this.#checked.delete(folder);
340
+ throw error;
341
+ }
342
+ this.#checked.delete(folder);
343
+ this.#checked.set(folder, Date.now());
344
+ if (this.#checked.size > CHECKS_KEPT)
345
+ this.#checked.delete(this.#checked.keys().next().value);
346
+ }
347
+ /** Whether `folder` passed `#checkReal` less than CHECK_KEPT_MS ago. A clock set back counts as not. */
348
+ #checkedRecently(folder) {
349
+ const at = this.#checked.get(folder);
350
+ if (at === undefined)
351
+ return false;
352
+ const age = Date.now() - at;
353
+ if (age >= 0 && age < CHECK_KEPT_MS)
354
+ return true;
355
+ this.#checked.delete(folder);
356
+ return false;
357
+ }
358
+ /**
359
+ * Whether a read's error means that the file is not there to read: missing, or a link, which is
360
+ * not followed. A file that is missing makes the next call check its folder again.
361
+ */
362
+ #unreadable(place, error) {
363
+ if (absent(error)) {
364
+ if (place.scoped)
365
+ this.#checked.delete(place.folder);
366
+ return true;
367
+ }
368
+ return linked(error);
369
+ }
370
+ /**
371
+ * The folder of the documents of a call, or undefined when it is not there, and so neither are
372
+ * they. A read (`fresh` false) takes a folder checked less than CHECK_KEPT_MS ago as it was; a
373
+ * delete or a sweep checks it again.
374
+ */
375
+ async #find(context, fresh = false) {
376
+ if (!this.#scopes)
377
+ return { folder: this.directory, shared: true, scoped: false };
378
+ const scope = this.#scopeOf(context);
379
+ if (scope === undefined)
380
+ return this.#root();
381
+ const folders = this.#folders(scope);
382
+ if (fresh || !this.#checkedRecently(folders.documents)) {
383
+ try {
384
+ await this.#checkReal(folders.documents);
385
+ }
386
+ catch (error) {
387
+ if (absent(error))
388
+ return undefined;
389
+ throw error;
390
+ }
391
+ }
392
+ return { folder: folders.documents, shared: this.#scopes.folder === "", scoped: true };
393
+ }
394
+ /**
395
+ * Makes the folders of a scope (`createScopeFolders`) one level at a time. Each is made, or found,
396
+ * as a folder and not a link before the next is made in it, so nothing is made where a link
397
+ * points. A file where a folder should be stops it: the check that follows finds the scope missing.
398
+ */
399
+ async #makeScopeFolders(scope) {
400
+ await mkdir(this.directory, { recursive: true, mode: this.#directoryMode });
401
+ let level = this.directory;
402
+ for (const segment of scope) {
403
+ level = path.join(level, segment);
404
+ await mkdir(level, { mode: this.#directoryMode }).catch((error) => {
405
+ if (code(error) !== "EEXIST")
406
+ throw error;
407
+ });
408
+ const info = await lstat(level);
409
+ if (info.isSymbolicLink())
410
+ throw new DocumentScopeError("scope_invalid", LINKED_FOLDER);
411
+ if (!info.isDirectory())
412
+ return;
413
+ }
414
+ }
415
+ /** The folder of the documents of a call, made when it is not there yet. */
416
+ async #make(context) {
417
+ const scope = this.#scopes ? this.#scopeOf(context) : undefined;
418
+ if (scope === undefined) {
419
+ const place = this.#scopes ? this.#root() : { folder: this.directory, shared: true, scoped: false };
420
+ await mkdir(this.directory, { recursive: true, mode: this.#directoryMode });
421
+ return place;
422
+ }
423
+ const scopes = this.#scopes;
424
+ const folders = this.#folders(scope);
425
+ const place = { folder: folders.documents, shared: scopes.folder === "", scoped: true };
426
+ try {
427
+ await this.#checkReal(folders.documents);
428
+ return place;
429
+ }
430
+ catch (error) {
431
+ if (!absent(error))
432
+ throw error;
433
+ }
434
+ try {
435
+ // Made only when asked to: the application may have removed the folder of a chat it deleted.
436
+ if (scopes.createScopeFolders)
437
+ await this.#makeScopeFolders(scope);
438
+ await this.#checkReal(folders.scope);
439
+ if (folders.documents !== folders.scope) {
440
+ // Not recursive: if the scope's folder went in the meantime, it is not made again.
441
+ await mkdir(folders.documents, { mode: this.#directoryMode }).catch((error) => {
442
+ if (code(error) !== "EEXIST")
443
+ throw error;
444
+ });
445
+ await this.#checkReal(folders.documents);
446
+ }
447
+ }
448
+ catch (error) {
449
+ if (absent(error))
450
+ throw new DocumentScopeError("scope_missing", undefined, { cause: error });
451
+ throw error;
452
+ }
453
+ return place;
454
+ }
455
+ /** Writes one file of a document whole. A scope's folder that went while it was written is "scope_missing". */
456
+ async #write(place, target, data) {
457
+ try {
458
+ await writeWhole(target, data, this.#fileMode);
459
+ }
460
+ catch (error) {
461
+ if (place.scoped && absent(error))
462
+ throw new DocumentScopeError("scope_missing", undefined, { cause: error });
463
+ throw error;
464
+ }
125
465
  }
126
- async put(document) {
127
- const paths = this.paths(document.meta.id);
128
- if (!paths)
466
+ async put(document, context) {
467
+ if (!fileId(document.meta.id))
129
468
  throw new Error("Invalid document ID.");
130
- await mkdir(this.directory, { recursive: true });
131
- await writeWhole(paths.text, document.text);
469
+ const place = await this.#make(context);
470
+ const files = filesOf(place.folder, document.meta.id);
471
+ await this.#write(place, files.text, document.text);
132
472
  // Write metadata last: a document without metadata is treated as absent.
133
- await writeWhole(paths.meta, JSON.stringify(document.meta));
473
+ await this.#write(place, files.meta, JSON.stringify(document.meta));
134
474
  }
135
- async getMeta(id) {
136
- const paths = this.paths(id);
137
- if (!paths)
138
- return undefined;
475
+ /** The metadata of a document in `place`, or undefined. An expired one is removed, as far as that works. */
476
+ async #meta(place, id) {
139
477
  let raw;
140
478
  try {
141
- raw = await readFile(paths.meta, "utf8");
479
+ raw = await readFile(filesOf(place.folder, id).meta, { encoding: "utf8", flag: READ_FLAGS });
142
480
  }
143
481
  catch (error) {
144
- // Only a file that is not there means that the document is not there. A read that failed for
145
- // another reason is thrown, so that a busy volume is not taken for a deleted document.
146
- if (missing(error))
482
+ // Only a file that is not there (or a link, not followed) means that the document is not
483
+ // there. A read that failed for another reason is thrown, so that a busy volume is not taken
484
+ // for a deleted document.
485
+ if (this.#unreadable(place, error))
147
486
  return undefined;
148
487
  throw error;
149
488
  }
@@ -152,35 +491,49 @@ export class FileDocumentStore {
152
491
  if (!meta)
153
492
  return undefined;
154
493
  if (expired(meta, this.now())) {
155
- await this.delete(id);
494
+ // Expired is missing, whether or not its files could be removed now: sweep tries again. The
495
+ // folder is checked again first: a read may have taken it as checked a moment ago.
496
+ await (place.scoped ? this.#checkReal(place.folder) : Promise.resolve())
497
+ .then(() => this.#remove(place, id))
498
+ .catch(() => undefined);
156
499
  return undefined;
157
500
  }
158
501
  return meta;
159
502
  }
160
- async get(id) {
161
- const meta = await this.getMeta(id);
162
- const paths = this.paths(id);
163
- if (!meta || !paths)
503
+ async getMeta(id, context) {
504
+ if (!fileId(id))
505
+ return undefined;
506
+ const place = await this.#find(context);
507
+ return place && this.#meta(place, id);
508
+ }
509
+ async get(id, context) {
510
+ if (!fileId(id))
511
+ return undefined;
512
+ const place = await this.#find(context);
513
+ const meta = place && await this.#meta(place, id);
514
+ if (!place || !meta)
164
515
  return undefined;
165
516
  try {
166
- return { meta, text: await readFile(paths.text, "utf8") };
517
+ return { meta, text: await readFile(filesOf(place.folder, id).text, { encoding: "utf8", flag: READ_FLAGS }) };
167
518
  }
168
519
  catch (error) {
169
- if (missing(error))
520
+ if (this.#unreadable(place, error))
170
521
  return undefined;
171
522
  throw error;
172
523
  }
173
524
  }
174
- async readTextRange(id, start, end) {
175
- const paths = this.paths(id);
176
- if (!paths)
525
+ async readTextRange(id, start, end, context) {
526
+ if (!fileId(id))
527
+ return undefined;
528
+ const place = await this.#find(context);
529
+ if (!place)
177
530
  return undefined;
178
531
  let handle;
179
532
  try {
180
- handle = await open(paths.text, "r");
533
+ handle = await open(filesOf(place.folder, id).text, READ_FLAGS);
181
534
  }
182
535
  catch (error) {
183
- if (code(error) === "ENOENT")
536
+ if (this.#unreadable(place, error))
184
537
  return undefined;
185
538
  throw error;
186
539
  }
@@ -200,62 +553,71 @@ export class FileDocumentStore {
200
553
  await handle.close();
201
554
  }
202
555
  }
203
- async putIndex(id, index) {
204
- const paths = this.paths(id);
205
- if (!paths)
556
+ async putIndex(id, index, context) {
557
+ if (!fileId(id))
206
558
  throw new Error("Invalid document ID.");
207
- await mkdir(this.directory, { recursive: true });
208
- await writeWhole(paths.index, index);
559
+ const place = await this.#make(context);
560
+ await this.#write(place, filesOf(place.folder, id).index, index);
209
561
  }
210
- async getIndex(id) {
211
- const paths = this.paths(id);
212
- if (!paths)
562
+ async getIndex(id, context) {
563
+ if (!fileId(id))
564
+ return undefined;
565
+ const place = await this.#find(context);
566
+ if (!place)
213
567
  return undefined;
214
568
  try {
215
- const file = await readFile(paths.index);
569
+ const file = await readFile(filesOf(place.folder, id).index, { flag: READ_FLAGS });
216
570
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
217
571
  }
218
- catch {
572
+ catch (error) {
573
+ this.#unreadable(place, error);
219
574
  return undefined;
220
575
  }
221
576
  }
222
- async delete(id) {
223
- const paths = this.paths(id);
224
- if (!paths)
225
- return false;
226
- const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
227
- // The metadata first: a document is there while its metadata is. If that file cannot be removed,
228
- // nothing else is, and the document stays whole. The other way round, a document whose text is
229
- // gone would still be listed.
230
- await rm(paths.meta, { force: true });
231
- await Promise.all([paths.text, paths.original, paths.index].map((file) => rm(file, { force: true })));
577
+ /**
578
+ * Removes the metadata, then the other files. When the metadata cannot be removed, the error is
579
+ * thrown and nothing else is touched: the document stays whole. Once it is gone, the document is
580
+ * gone: a text, index or original that cannot be removed now is left for `sweep`.
581
+ */
582
+ async #remove(place, id) {
583
+ const files = filesOf(place.folder, id);
584
+ const existed = await removeFile(files.meta);
585
+ await Promise.allSettled([files.text, files.original, files.index].map(removeFile));
232
586
  return existed;
233
587
  }
234
- async putOriginal(id, bytes) {
235
- const paths = this.paths(id);
236
- if (!paths)
588
+ async delete(id, context) {
589
+ if (!fileId(id))
590
+ return false;
591
+ const place = await this.#find(context, true);
592
+ return place ? this.#remove(place, id) : false;
593
+ }
594
+ async putOriginal(id, bytes, context) {
595
+ if (!fileId(id))
237
596
  throw new Error("Invalid document ID.");
238
- await mkdir(this.directory, { recursive: true });
597
+ const place = await this.#make(context);
239
598
  // Written before the metadata (see put): until that exists, the document is treated as absent.
240
- await writeWhole(paths.original, bytes);
599
+ await this.#write(place, filesOf(place.folder, id).original, bytes);
241
600
  }
242
- async getOriginal(id) {
243
- const paths = this.paths(id);
244
- // The metadata decides whether the document is still there. getMeta also removes an expired one.
245
- if (!paths || !await this.getMeta(id))
601
+ async getOriginal(id, context) {
602
+ if (!fileId(id))
603
+ return undefined;
604
+ const place = await this.#find(context);
605
+ // The metadata decides whether the document is still there, and removes an expired one.
606
+ if (!place || !await this.#meta(place, id))
246
607
  return undefined;
247
608
  try {
248
- const file = await readFile(paths.original);
609
+ const file = await readFile(filesOf(place.folder, id).original, { flag: READ_FLAGS });
249
610
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
250
611
  }
251
612
  catch (error) {
252
- if (missing(error))
613
+ if (this.#unreadable(place, error))
253
614
  return undefined;
254
615
  throw error;
255
616
  }
256
617
  }
257
618
  /**
258
- * Removes expired documents and returns how many. Also removes files that belong to no
619
+ * Removes expired documents and returns how many: those whose metadata this sweep removed, so
620
+ * that two sweeps at once count each document once. Also removes files that belong to no
259
621
  * document, and temporary files, once they are older than `orphanAgeMs`. A document whose
260
622
  * metadata is not valid is removed only when that file is that old too: it may be being
261
623
  * written by a server of an older version, which does not write whole files.
@@ -263,59 +625,140 @@ export class FileDocumentStore {
263
625
  * A document whose metadata could not be read at all (the volume did not answer, too many files
264
626
  * were open) is left alone, whatever its age: the next sweep looks at it again. A document that
265
627
  * cannot be removed is left for the next sweep too, and does not stop this one.
628
+ *
629
+ * With `scopes`: with a scope in `context`, the folder of that scope only. Without one, every
630
+ * scope's: it goes down exactly `scopes.depth` levels of folders, into folders whose names pass
631
+ * `isSafeScopeSegment` only, and follows no link. With `unscoped: "root"`, the directory itself too.
632
+ * Without `scopes`, the context is not used.
266
633
  */
267
- async sweep(now = this.now()) {
634
+ async sweep(now = this.now(), context) {
635
+ const slots = new Limiter(this.#sweepConcurrency);
636
+ const pool = async (task) => {
637
+ const release = await slots.acquire();
638
+ try {
639
+ return await task();
640
+ }
641
+ finally {
642
+ release();
643
+ }
644
+ };
645
+ const scopes = this.#scopes;
646
+ if (!scopes)
647
+ return this.#sweepFolder({ folder: this.directory, shared: true, scoped: false }, now, pool);
648
+ const scope = this.#scopeOf(context);
649
+ if (scope !== undefined) {
650
+ const place = await this.#find({ scope }, true);
651
+ return place ? this.#sweepFolder(place, now, pool) : 0;
652
+ }
653
+ let removed = scopes.unscoped === "root" ? await this.#sweepFolder({ folder: this.directory, shared: true, scoped: false }, now, pool) : 0;
654
+ // The folders of the scopes, a few at a time: one pool bounds the file system calls of all of them.
655
+ const running = new Set();
656
+ for await (const folder of this.#scopeFolders(pool)) {
657
+ const sweeping = this.#sweepFolder({ folder, shared: scopes.folder === "", scoped: true }, now, pool)
658
+ .then((count) => { removed += count; }, () => undefined)
659
+ .finally(() => running.delete(sweeping));
660
+ running.add(sweeping);
661
+ if (running.size >= this.#sweepConcurrency)
662
+ await Promise.race(running);
663
+ }
664
+ await Promise.all(running);
665
+ return removed;
666
+ }
667
+ /** The folders of the store in every scope's folder, found one level at a time, depth first. */
668
+ async *#scopeFolders(pool) {
669
+ const scopes = this.#scopes;
670
+ const walk = async function* (folder, level) {
671
+ let entries;
672
+ try {
673
+ entries = await pool(() => readdir(folder, { withFileTypes: true }));
674
+ }
675
+ catch {
676
+ return;
677
+ }
678
+ for (const entry of entries) {
679
+ // A link is not a directory here: it is never followed. Nor is a folder the application
680
+ // keeps beside the scopes, whose name is not one a scope may have.
681
+ if (!entry.isDirectory() || !isSafeScopeSegment(entry.name))
682
+ continue;
683
+ const next = path.join(folder, entry.name);
684
+ if (level + 1 < scopes.depth) {
685
+ yield* walk(next, level + 1);
686
+ continue;
687
+ }
688
+ if (!scopes.folder) {
689
+ yield next;
690
+ continue;
691
+ }
692
+ const documents = path.join(next, scopes.folder);
693
+ const info = await pool(() => lstat(documents)).catch(() => undefined);
694
+ if (info?.isDirectory())
695
+ yield documents;
696
+ }
697
+ };
698
+ yield* walk(this.directory, 0);
699
+ }
700
+ /** Sweeps one folder. Never throws: a folder that cannot be listed gives 0. */
701
+ async #sweepFolder(place, now, pool) {
268
702
  let entries;
269
703
  try {
270
- entries = await readdir(this.directory);
704
+ entries = await pool(() => readdir(place.folder, { withFileTypes: true }));
271
705
  }
272
706
  catch {
273
707
  return 0;
274
708
  }
275
709
  const files = new Map();
276
710
  for (const entry of entries) {
277
- const match = FILE_NAME.exec(entry);
711
+ const match = entry.isFile() ? FILE_NAME.exec(entry.name) : null;
278
712
  if (!match)
279
713
  continue;
280
714
  const list = files.get(match[1]) ?? [];
281
- list.push(entry);
715
+ list.push(entry.name);
282
716
  files.set(match[1], list);
283
717
  }
718
+ const counts = await Promise.all([...files].map(([id, names]) => this.#sweepDocument(place, id, names, now, pool)));
719
+ return counts.reduce((sum, count) => sum + count, 0);
720
+ }
721
+ /** Sweeps the files of one ID in a folder: 1 when it removed an expired or broken document. */
722
+ async #sweepDocument(place, id, names, now, pool) {
284
723
  const old = async (entry) => {
285
- const info = await stat(path.join(this.directory, entry)).catch(() => undefined);
724
+ const info = await pool(() => stat(path.join(place.folder, entry))).catch(() => undefined);
286
725
  return info !== undefined && now.getTime() - info.mtimeMs >= this.orphanAgeMs;
287
726
  };
288
- let removed = 0;
289
- for (const [id, names] of files) {
290
- const metaFile = `${id}.json`;
291
- if (names.includes(metaFile)) {
292
- let raw;
293
- try {
294
- raw = await readFile(path.join(this.directory, metaFile), "utf8");
295
- }
296
- catch (error) {
297
- // Not read is not the same as not valid: nothing of this document is touched.
298
- if (!missing(error))
299
- continue;
300
- }
301
- if (raw !== undefined) {
302
- const meta = parseMeta(raw);
303
- if (meta ? expired(meta, now) : await old(metaFile)) {
304
- if (await this.delete(id).then(() => true, () => false))
305
- removed++;
306
- continue;
307
- }
308
- }
727
+ // In a folder of the store's own, every file named like a document's is the store's. In one the
728
+ // application shares, a file of an application's ID is, only when its metadata names it.
729
+ const ours = !place.shared || DOCUMENT_ID_PATTERN.test(id);
730
+ const metaFile = `${id}.json`;
731
+ const hasMeta = names.includes(metaFile);
732
+ if (hasMeta) {
733
+ let raw;
734
+ try {
735
+ raw = await pool(() => readFile(path.join(place.folder, metaFile), { encoding: "utf8", flag: READ_FLAGS }));
309
736
  }
310
- // Temporary files of this document, and every file of one without metadata, once they are old.
311
- for (const entry of names) {
312
- if (entry === metaFile || (!entry.endsWith(".tmp") && names.includes(metaFile)))
313
- continue;
314
- if (await old(entry))
315
- await rm(path.join(this.directory, entry), { force: true }).catch(() => undefined);
737
+ catch (error) {
738
+ // Not read is not the same as not valid: nothing of this document is touched.
739
+ if (!missing(error))
740
+ return 0;
741
+ }
742
+ if (raw !== undefined) {
743
+ const meta = parseMeta(raw);
744
+ const known = meta !== undefined && (ours || meta.id === id);
745
+ if (known ? expired(meta, now) : ours && await old(metaFile)) {
746
+ // 1 only when this sweep removed the metadata: another sweep at the same time may have.
747
+ // On Windows both unlinks of one file can succeed (the file goes when the last handle
748
+ // closes), and both sweeps count it: claiming it by a rename first would tell them apart.
749
+ return await pool(() => this.#remove(place, id)).then((existed) => (existed ? 1 : 0), () => 0);
750
+ }
316
751
  }
317
752
  }
318
- return removed;
753
+ // Temporary files of this ID, and, when they are the store's, the files of a document without
754
+ // metadata, once they are old.
755
+ for (const entry of names) {
756
+ if (entry === metaFile || (!entry.endsWith(".tmp") && (hasMeta || !ours)))
757
+ continue;
758
+ if (await old(entry))
759
+ await pool(() => rm(path.join(place.folder, entry), { force: true })).catch(() => undefined);
760
+ }
761
+ return 0;
319
762
  }
320
763
  }
321
764
  //# sourceMappingURL=stores.js.map