llm-large-files 0.7.0 → 0.8.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 (184) hide show
  1. package/CHANGELOG.md +319 -1
  2. package/README.md +10 -8
  3. package/dist/analyze.d.ts +3 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +109 -14
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts.map +1 -1
  8. package/dist/anthropic/adapter.js +4 -1
  9. package/dist/anthropic/adapter.js.map +1 -1
  10. package/dist/ask.d.ts +3 -3
  11. package/dist/ask.d.ts.map +1 -1
  12. package/dist/ask.js +72 -17
  13. package/dist/ask.js.map +1 -1
  14. package/dist/decode.d.ts +19 -0
  15. package/dist/decode.d.ts.map +1 -0
  16. package/dist/decode.js +97 -0
  17. package/dist/decode.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +65 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/events.d.ts +6 -0
  23. package/dist/events.d.ts.map +1 -1
  24. package/dist/events.js +5 -1
  25. package/dist/events.js.map +1 -1
  26. package/dist/evidence.d.ts.map +1 -1
  27. package/dist/evidence.js +6 -0
  28. package/dist/evidence.js.map +1 -1
  29. package/dist/extract.d.ts +7 -20
  30. package/dist/extract.d.ts.map +1 -1
  31. package/dist/extract.js +49 -751
  32. package/dist/extract.js.map +1 -1
  33. package/dist/gemini/adapter.d.ts.map +1 -1
  34. package/dist/gemini/adapter.js +9 -5
  35. package/dist/gemini/adapter.js.map +1 -1
  36. package/dist/gemini/endpoints.d.ts +5 -1
  37. package/dist/gemini/endpoints.d.ts.map +1 -1
  38. package/dist/gemini/endpoints.js +11 -2
  39. package/dist/gemini/endpoints.js.map +1 -1
  40. package/dist/gemini/generate.d.ts.map +1 -1
  41. package/dist/gemini/generate.js +20 -3
  42. package/dist/gemini/generate.js.map +1 -1
  43. package/dist/groups.d.ts +54 -0
  44. package/dist/groups.d.ts.map +1 -0
  45. package/dist/groups.js +136 -0
  46. package/dist/groups.js.map +1 -0
  47. package/dist/html.d.ts +11 -0
  48. package/dist/html.d.ts.map +1 -0
  49. package/dist/html.js +1112 -0
  50. package/dist/html.js.map +1 -0
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +1 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/library.d.ts.map +1 -1
  56. package/dist/library.js +48 -12
  57. package/dist/library.js.map +1 -1
  58. package/dist/limiter.d.ts +2 -1
  59. package/dist/limiter.d.ts.map +1 -1
  60. package/dist/limiter.js +3 -2
  61. package/dist/limiter.js.map +1 -1
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +8 -1
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts.map +1 -1
  66. package/dist/node/handlers.js +69 -15
  67. package/dist/node/handlers.js.map +1 -1
  68. package/dist/node/index.d.ts +2 -0
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +1 -0
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/ingest-child.d.ts +38 -0
  73. package/dist/node/ingest-child.d.ts.map +1 -0
  74. package/dist/node/ingest-child.js +42 -0
  75. package/dist/node/ingest-child.js.map +1 -0
  76. package/dist/node/isolated.d.ts +88 -0
  77. package/dist/node/isolated.d.ts.map +1 -0
  78. package/dist/node/isolated.js +381 -0
  79. package/dist/node/isolated.js.map +1 -0
  80. package/dist/office.d.ts +105 -0
  81. package/dist/office.d.ts.map +1 -0
  82. package/dist/office.js +1092 -0
  83. package/dist/office.js.map +1 -0
  84. package/dist/openai/adapter.d.ts.map +1 -1
  85. package/dist/openai/adapter.js +15 -1
  86. package/dist/openai/adapter.js.map +1 -1
  87. package/dist/pdf-pages.d.ts.map +1 -1
  88. package/dist/pdf-pages.js +2 -6
  89. package/dist/pdf-pages.js.map +1 -1
  90. package/dist/peers.d.ts +8 -0
  91. package/dist/peers.d.ts.map +1 -0
  92. package/dist/peers.js +32 -0
  93. package/dist/peers.js.map +1 -0
  94. package/dist/plan.d.ts.map +1 -1
  95. package/dist/plan.js +1 -1
  96. package/dist/plan.js.map +1 -1
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +4 -2
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/search.d.ts +99 -22
  101. package/dist/search.d.ts.map +1 -1
  102. package/dist/search.js +744 -140
  103. package/dist/search.js.map +1 -1
  104. package/dist/text-index.d.ts +3 -1
  105. package/dist/text-index.d.ts.map +1 -1
  106. package/dist/text-index.js +3 -1
  107. package/dist/text-index.js.map +1 -1
  108. package/dist/text.d.ts +27 -3
  109. package/dist/text.d.ts.map +1 -1
  110. package/dist/text.js +225 -23
  111. package/dist/text.js.map +1 -1
  112. package/dist/tools.d.ts.map +1 -1
  113. package/dist/tools.js +200 -12
  114. package/dist/tools.js.map +1 -1
  115. package/dist/types.d.ts +3 -3
  116. package/dist/types.d.ts.map +1 -1
  117. package/dist/word-styles.d.ts +102 -0
  118. package/dist/word-styles.d.ts.map +1 -0
  119. package/dist/word-styles.js +419 -0
  120. package/dist/word-styles.js.map +1 -0
  121. package/dist/xlsx.d.ts +23 -0
  122. package/dist/xlsx.d.ts.map +1 -0
  123. package/dist/xlsx.js +511 -0
  124. package/dist/xlsx.js.map +1 -0
  125. package/dist/xml-stream.d.ts +55 -0
  126. package/dist/xml-stream.d.ts.map +1 -0
  127. package/dist/xml-stream.js +235 -0
  128. package/dist/xml-stream.js.map +1 -0
  129. package/docs/README.md +8 -8
  130. package/docs/getting-started.md +1 -1
  131. package/docs/guides/costs-and-limits.md +7 -5
  132. package/docs/guides/deployment.md +95 -29
  133. package/docs/guides/errors-and-reliability.md +23 -10
  134. package/docs/guides/pdfs.md +127 -74
  135. package/docs/guides/storage.md +1 -1
  136. package/docs/guides/testing.md +5 -1
  137. package/docs/guides/web-app.md +10 -9
  138. package/docs/how-it-works.md +73 -50
  139. package/docs/reference/ask.md +26 -8
  140. package/docs/reference/errors-and-retries.md +5 -3
  141. package/docs/reference/events.md +14 -6
  142. package/docs/reference/gemini.md +6 -2
  143. package/docs/reference/library.md +205 -74
  144. package/docs/reference/node.md +200 -22
  145. package/docs/reference/openai.md +1 -1
  146. package/docs/reference/tools.md +170 -22
  147. package/docs/security.md +114 -69
  148. package/docs/troubleshooting.md +40 -20
  149. package/package.json +6 -2
  150. package/src/analyze.ts +117 -13
  151. package/src/anthropic/adapter.ts +4 -1
  152. package/src/ask.ts +73 -17
  153. package/src/decode.ts +89 -0
  154. package/src/errors.ts +108 -0
  155. package/src/events.ts +10 -1
  156. package/src/evidence.ts +6 -0
  157. package/src/extract.ts +52 -709
  158. package/src/gemini/adapter.ts +9 -5
  159. package/src/gemini/endpoints.ts +12 -2
  160. package/src/gemini/generate.ts +19 -3
  161. package/src/groups.ts +162 -0
  162. package/src/html.ts +1071 -0
  163. package/src/index.ts +2 -1
  164. package/src/library.ts +43 -12
  165. package/src/limiter.ts +6 -1
  166. package/src/model.ts +8 -1
  167. package/src/node/handlers.ts +66 -16
  168. package/src/node/index.ts +2 -0
  169. package/src/node/ingest-child.ts +61 -0
  170. package/src/node/isolated.ts +464 -0
  171. package/src/office.ts +1047 -0
  172. package/src/openai/adapter.ts +14 -1
  173. package/src/pdf-pages.ts +2 -5
  174. package/src/peers.ts +29 -0
  175. package/src/plan.ts +2 -0
  176. package/src/ranged.ts +4 -2
  177. package/src/search.ts +738 -146
  178. package/src/text-index.ts +4 -2
  179. package/src/text.ts +214 -23
  180. package/src/tools.ts +192 -12
  181. package/src/types.ts +3 -3
  182. package/src/word-styles.ts +420 -0
  183. package/src/xlsx.ts +478 -0
  184. package/src/xml-stream.ts +224 -0
@@ -79,10 +79,14 @@ function callsTurn(calls: ToolCall[]): GeminiContent {
79
79
  return { role: "model", parts: calls.map((call) => ({ functionCall: { name: call.name, args: call.args, ...(call.id ? { id: call.id } : {}) } })) };
80
80
  }
81
81
 
82
- const textTurn = (message: ModelTextMessage): GeminiContent => ({
83
- role: message.role === "user" ? "user" : "model",
84
- parts: message.parts.map((part) => (part.native !== undefined ? part.native as GeminiPart : { text: part.text ?? "" })),
85
- });
82
+ /**
83
+ * A turn of text, without its empty text parts: Vertex AI refuses an empty text parameter (a stored
84
+ * answer that came back empty is one). A native part stays, and a turn with no part left is none.
85
+ */
86
+ const textTurn = (message: ModelTextMessage): GeminiContent[] => {
87
+ const parts = message.parts.flatMap((part): GeminiPart[] => (part.native !== undefined ? [part.native as GeminiPart] : part.text ? [{ text: part.text }] : []));
88
+ return parts.length > 0 ? [{ role: message.role === "user" ? "user" : "model", parts }] : [];
89
+ };
86
90
 
87
91
  /**
88
92
  * Gemini `contents` as messages of `askWithFiles`: text parts as text, every other part (an image,
@@ -131,7 +135,7 @@ export function gemini(endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "hea
131
135
  }
132
136
  return turns;
133
137
  };
134
- const toContents = (messages: ModelMessage[]): GeminiContent[] => messages.flatMap((message) => (message.role === "tools" ? roundTurns(message) : [textTurn(message)]));
138
+ const toContents = (messages: ModelMessage[]): GeminiContent[] => messages.flatMap((message) => (message.role === "tools" ? roundTurns(message) : textTurn(message)));
135
139
  const bodyOf = (request: ModelRequest): Body => ({
136
140
  contents: toContents(request.messages),
137
141
  ...(request.system ? { systemInstruction: { parts: [{ text: request.system }] } } : {}),
@@ -54,8 +54,18 @@ export function geminiApi(options: {
54
54
  };
55
55
  }
56
56
 
57
- /** The host for a Vertex AI location: global, the us/eu multi-regions, or a single region. */
57
+ /** A Vertex AI location: "global", "us", "eu", or a region such as "europe-west4". */
58
+ const LOCATION = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
59
+
60
+ /**
61
+ * The host for a Vertex AI location: global, the us/eu multi-regions, or a single region. A location
62
+ * that is not one (with "/", "?", "#" or "@" it would name another host, which would get the access
63
+ * token) throws a TypeError.
64
+ */
58
65
  export function vertexHost(location: string): string {
66
+ if (typeof location !== "string" || !LOCATION.test(location)) {
67
+ throw new TypeError(`location must be a Vertex AI location such as "global", "us" or "europe-west4", and is ${JSON.stringify(location) ?? String(location)}.`);
68
+ }
59
69
  if (location === "global") return "https://aiplatform.googleapis.com";
60
70
  if (location === "us" || location === "eu") return `https://aiplatform.${location}.rep.googleapis.com`;
61
71
  return `https://${location}-aiplatform.googleapis.com`;
@@ -76,7 +86,7 @@ export function vertexAi(options: {
76
86
  apiVersion?: string;
77
87
  }): GeminiEndpoint {
78
88
  const location = options.location ?? "global";
79
- const models = `${vertexHost(location)}/${options.apiVersion ?? "v1"}/projects/${encodeURIComponent(options.project)}/locations/${location}/publishers/google/models/`;
89
+ const models = `${vertexHost(location)}/${options.apiVersion ?? "v1"}/projects/${encodeURIComponent(options.project)}/locations/${encodeURIComponent(location)}/publishers/google/models/`;
80
90
  const base = `${models}${encodeURIComponent(options.model)}`;
81
91
  const explorer = explorerOf(options);
82
92
  const token = options.accessToken;
@@ -1,9 +1,9 @@
1
1
  // Gemini (Generate Content REST) helpers. No SDK dependency: the caller supplies the URL and
2
2
  // auth headers, so this works with the Gemini API, Vertex AI, or an enterprise gateway.
3
3
  import type { ToolAnswer, ToolCall } from "../model.js";
4
- import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
4
+ import { completeWithinLimit, noTextReason, type LimitedReply } from "../output-limit.js";
5
5
  import { readJson } from "../http.js";
6
- import { retryAfterMs } from "../retry.js";
6
+ import { noteNoRetry, retryAfterMs } from "../retry.js";
7
7
  import type { GenerateText, GenerateUsage, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
8
8
  import { finishOfGemini, geminiFailure, notJson, unreachable } from "./errors.js";
9
9
 
@@ -116,6 +116,8 @@ export function createGeminiGenerateText(options: {
116
116
  const fetchImpl = options.fetchImpl ?? fetch;
117
117
  const { url } = options;
118
118
  return async ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
119
+ /** Set when Gemini blocked the prompt: sent again, it would be blocked again. */
120
+ let blocked = false;
119
121
  /** One request with an output limit: the text of the reply, why it ended, and what it thought. */
120
122
  const send = async (limit: number): Promise<LimitedReply> => {
121
123
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
@@ -142,6 +144,7 @@ export function createGeminiGenerateText(options: {
142
144
  error?: { message?: string };
143
145
  candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
144
146
  usageMetadata?: Record<string, unknown>;
147
+ promptFeedback?: { blockReason?: unknown };
145
148
  } | null;
146
149
  // An error may have no JSON body. A reply must: one whose body could not be read is a
147
150
  // connection that failed, and is sent again.
@@ -151,6 +154,13 @@ export function createGeminiGenerateText(options: {
151
154
  if (!response.ok) throw geminiFailure(response.status, data, retryAfterMs(response.headers, data), `The model returned HTTP ${response.status}.`);
152
155
  onUsage?.(usageOfGemini(data?.usageMetadata));
153
156
  const candidate = data?.candidates?.[0];
157
+ // A prompt Gemini blocked comes with 200, a reason and no candidate: the reply has no text,
158
+ // and says why ("The model returned no text (PROHIBITED_CONTENT).").
159
+ const blockReason = data?.promptFeedback?.blockReason;
160
+ if (!candidate && typeof blockReason === "string" && blockReason) {
161
+ blocked = true;
162
+ return { text: "", cutOff: false, stopped: true, reason: blockReason, thoughts: 0 };
163
+ }
154
164
  const text = (candidate?.content?.parts ?? [])
155
165
  .filter((part) => part.thought !== true && typeof part.text === "string")
156
166
  .map((part) => part.text as string)
@@ -165,6 +175,12 @@ export function createGeminiGenerateText(options: {
165
175
  thoughts: typeof thoughts === "number" ? thoughts : 0,
166
176
  };
167
177
  };
168
- return completeWithinLimit(url, maxOutputTokens, send, { signal, onTruncated });
178
+ try {
179
+ return await completeWithinLimit(url, maxOutputTokens, send, { signal, onTruncated });
180
+ } catch (error) {
181
+ // A blocked prompt is not worth sending again: `withRetry` does not.
182
+ if (blocked && noTextReason(error) !== undefined) noteNoRetry(error as object);
183
+ throw error;
184
+ }
169
185
  };
170
186
  }
package/src/groups.ts ADDED
@@ -0,0 +1,162 @@
1
+ import { logTemplate } from "./analyze.js";
2
+ import { sliceWhole } from "./text.js";
3
+
4
+ /**
5
+ * How `search_document` counts matching lines by group (`group_by`):
6
+ * - "capture": by the text of the regex's first group (`PAY-(\d+)` counts each code);
7
+ * - "minute", "hour", "day": by the first timestamp on the line, as written there;
8
+ * - "shape": by the line with its numbers, IDs, addresses and quoted values replaced by
9
+ * placeholders, as the log profile groups problems.
10
+ */
11
+ export type GroupBy = "capture" | "minute" | "hour" | "day" | "shape";
12
+
13
+ export const GROUP_BY_VALUES: readonly GroupBy[] = ["capture", "minute", "hour", "day", "shape"];
14
+
15
+ /** One group of matching lines. */
16
+ export type GroupCount = { key: string; count: number; firstLine: number; lastLine: number };
17
+
18
+ /** Distinct groups counted one by one, at most: lines of further groups are counted together, in `otherCount`. */
19
+ export const MAX_GROUP_KEYS = 10_000;
20
+ /** A key is cut to this many characters: a capture or a shape can be a whole line. */
21
+ const MAX_KEY_CHARACTERS = 120;
22
+
23
+ const MONTHS: Record<string, string> = {
24
+ jan: "01", feb: "02", mar: "03", apr: "04", may: "05", jun: "06",
25
+ jul: "07", aug: "08", sep: "09", oct: "10", nov: "11", dec: "12",
26
+ };
27
+
28
+ /**
29
+ * The timestamps a log line may start or hold, each with the parts it gives. The first that matches
30
+ * the line is used, at the first place it matches. The time is taken as written, in the zone the
31
+ * line was written in: an offset (`+02:00`, `Z`) is not applied.
32
+ */
33
+ const STAMPS: Array<{ pattern: RegExp; parts: (match: RegExpExecArray) => TimeParts | undefined }> = [
34
+ // 2026-11-10T14:03:17Z, 2026-11-10 14:03:17,123, 2026/11/10 14:03:17 (nginx's error log).
35
+ {
36
+ pattern: /(?<![\d.])(\d{4})[-/](\d{2})[-/](\d{2})[T ](\d{2}):(\d{2})/,
37
+ parts: (match) => ({ year: match[1]!, month: match[2]!, day: match[3]!, hour: match[4]!, minute: match[5]! }),
38
+ },
39
+ // 10/Nov/2026:14:03:17 +0000 (the access logs of Apache and nginx).
40
+ {
41
+ pattern: /(?<!\d)(\d{2})\/([A-Z][a-z]{2})\/(\d{4}):(\d{2}):(\d{2})/,
42
+ parts: (match) => {
43
+ const month = MONTHS[match[2]!.toLowerCase()];
44
+ return month ? { year: match[3]!, month, day: match[1]!, hour: match[4]!, minute: match[5]! } : undefined;
45
+ },
46
+ },
47
+ // "time":1731247397123 or "ts":1731247397 (pino, bunyan and other JSON logs give epoch time).
48
+ {
49
+ pattern: /"(?:time|ts|timestamp|@timestamp)"\s*:\s*(\d{10}(?:\d{3})?)(?![\d.])/,
50
+ parts: (match) => {
51
+ const value = Number(match[1]!);
52
+ const date = new Date(match[1]!.length === 13 ? value : value * 1_000);
53
+ if (Number.isNaN(date.getTime())) return undefined;
54
+ const iso = date.toISOString();
55
+ return { year: iso.slice(0, 4), month: iso.slice(5, 7), day: iso.slice(8, 10), hour: iso.slice(11, 13), minute: iso.slice(14, 16) };
56
+ },
57
+ },
58
+ // 10.11.2026 14:03 and 10/11/2026 14:03: day and month as written, as the order cannot be told.
59
+ {
60
+ pattern: /(?<![\d.])(\d{1,2})([./])(\d{1,2})\2(\d{4})[ T,]+(\d{1,2}):(\d{2})/,
61
+ parts: (match) => ({ year: match[4]!, month: match[3]!.padStart(2, "0"), day: match[1]!.padStart(2, "0"), hour: match[5]!.padStart(2, "0"), minute: match[6]!, order: match[2] === "." ? "dmy" : "as-written" }),
62
+ },
63
+ // Nov 10 14:03:17 (syslog), with no year.
64
+ {
65
+ pattern: /(?<![A-Za-z])([A-Z][a-z]{2}) {1,2}(\d{1,2}) (\d{2}):(\d{2}):\d{2}/,
66
+ parts: (match) => {
67
+ const month = MONTHS[match[1]!.toLowerCase()];
68
+ return month ? { month, day: match[2]!.padStart(2, "0"), hour: match[3]!, minute: match[4]! } : undefined;
69
+ },
70
+ },
71
+ // I1110 14:03:17.123456 (klog, glog): the level letter, month and day, with no year.
72
+ {
73
+ pattern: /^[IWEF](\d{2})(\d{2}) (\d{2}):(\d{2}):\d{2}/,
74
+ parts: (match) => ({ month: match[1]!, day: match[2]!, hour: match[3]!, minute: match[4]! }),
75
+ },
76
+ ];
77
+
78
+ type TimeParts = { year?: string; month: string; day: string; hour: string; minute: string; order?: "dmy" | "as-written" };
79
+
80
+ /** The date of a timestamp's parts as a key: "2026-11-10", "11-10" without a year, "10/11/2026" when day and month cannot be told apart. */
81
+ function dateKey(parts: TimeParts): string {
82
+ if (parts.order === "as-written") return `${parts.day}/${parts.month}/${parts.year}`;
83
+ return parts.year ? `${parts.year}-${parts.month}-${parts.day}` : `${parts.month}-${parts.day}`;
84
+ }
85
+
86
+ /**
87
+ * The group of a line by its first timestamp: "2026-11-10" for a day, "2026-11-10 14:00" for an
88
+ * hour, "2026-11-10 14:03" for a minute. Undefined for a line without a timestamp.
89
+ */
90
+ export function timeKey(line: string, unit: "minute" | "hour" | "day"): string | undefined {
91
+ for (const { pattern, parts: partsOf } of STAMPS) {
92
+ const match = pattern.exec(line);
93
+ if (!match) continue;
94
+ const parts = partsOf(match);
95
+ if (!parts) continue;
96
+ const date = dateKey(parts);
97
+ return unit === "day" ? date : `${date} ${parts.hour}:${unit === "hour" ? "00" : parts.minute}`;
98
+ }
99
+ return undefined;
100
+ }
101
+
102
+ /** What `GroupCounter.result()` gives. */
103
+ export type GroupResult = {
104
+ /** The groups, largest first; by time, the order of their first lines. */
105
+ groups: GroupCount[];
106
+ /** Distinct groups counted, at most `MAX_GROUP_KEYS`. */
107
+ totalGroups: number;
108
+ /** Matching lines of further groups, past `MAX_GROUP_KEYS`. */
109
+ otherCount: number;
110
+ /** Matching lines that have no key: no timestamp, or a regex group that took part in no match. */
111
+ ungrouped: number;
112
+ };
113
+
114
+ /** Counts matching lines by group, one line at a time. */
115
+ export class GroupCounter {
116
+ private readonly groups = new Map<string, GroupCount>();
117
+ private otherCount = 0;
118
+ private ungrouped = 0;
119
+
120
+ constructor(readonly by: GroupBy) {}
121
+
122
+ /** A matching line, and for "capture" the text of the regex's first group, if it took part. */
123
+ add(line: number, text: string, capture?: string): void {
124
+ this.addKey(line, this.keyOf(text, capture));
125
+ }
126
+
127
+ /**
128
+ * A matching line by its key, worked out before with `keyOf`. A regex search works the keys out
129
+ * within its time limit, which can stop it anywhere, and adds them after: a stop never leaves a
130
+ * count half done.
131
+ */
132
+ addKey(line: number, key: string | undefined): void {
133
+ if (key === undefined) {
134
+ this.ungrouped++;
135
+ return;
136
+ }
137
+ const group = this.groups.get(key);
138
+ if (group) {
139
+ group.count++;
140
+ group.lastLine = line;
141
+ } else if (this.groups.size < MAX_GROUP_KEYS) {
142
+ this.groups.set(key, { key, count: 1, firstLine: line, lastLine: line });
143
+ } else {
144
+ this.otherCount++;
145
+ }
146
+ }
147
+
148
+ /** The group of a matching line: undefined for a line without one (see `GroupResult.ungrouped`). */
149
+ keyOf(text: string, capture: string | undefined): string | undefined {
150
+ if (this.by === "capture") return capture === undefined ? undefined : sliceWhole(capture, MAX_KEY_CHARACTERS);
151
+ if (this.by === "shape") return sliceWhole(logTemplate(text), MAX_KEY_CHARACTERS) || undefined;
152
+ return timeKey(text, this.by);
153
+ }
154
+
155
+ result(): GroupResult {
156
+ const byTime = this.by === "minute" || this.by === "hour" || this.by === "day";
157
+ const groups = [...this.groups.values()].sort(byTime
158
+ ? (left, right) => left.firstLine - right.firstLine
159
+ : (left, right) => right.count - left.count || left.firstLine - right.firstLine);
160
+ return { groups, totalGroups: this.groups.size, otherCount: this.otherCount, ungrouped: this.ungrouped };
161
+ }
162
+ }