@jibone/todotxt-core 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/dist/index.d.ts +83 -5
- package/dist/index.js +69 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -133,6 +133,7 @@ await todos.createdAfter("2024-01-01"); // TodoRecord[]
|
|
|
133
133
|
await todos.notProject("Garden"); // TodoRecord[]
|
|
134
134
|
await todos.count(); // number
|
|
135
135
|
await todos.first(); // TodoRecord | undefined
|
|
136
|
+
await todos.summary(); // TodoSummary
|
|
136
137
|
```
|
|
137
138
|
|
|
138
139
|
Filters compose, so they can be combined in any order:
|
|
@@ -293,6 +294,57 @@ await todos.sortBy("priority").first(); // first (A) task
|
|
|
293
294
|
await todos.project("Missing").first(); // undefined
|
|
294
295
|
```
|
|
295
296
|
|
|
297
|
+
### Aggregates and counts
|
|
298
|
+
|
|
299
|
+
`summary()` returns top-level totals plus per-name counts in one query, and
|
|
300
|
+
`countsByProject()` / `countsByContext()` return the per-name counts alone:
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
const summary = await todos.summary();
|
|
304
|
+
// {
|
|
305
|
+
// total: 19, pending: 12, completed: 7,
|
|
306
|
+
// projects: [
|
|
307
|
+
// { name: "GarageSale", counts: { pending: 3, completed: 1, total: 4 } },
|
|
308
|
+
// { name: "Garden", counts: { pending: 2, completed: 0, total: 2 } },
|
|
309
|
+
// { name: "Moving", counts: { pending: 1, completed: 1, total: 2 } },
|
|
310
|
+
// { name: "OpenSource", counts: { pending: 2, completed: 2, total: 4 } },
|
|
311
|
+
// { name: "TodoTxt", counts: { pending: 2, completed: 2, total: 4 } },
|
|
312
|
+
// { name: "TodoTxtTouch", counts: { pending: 0, completed: 1, total: 1 } },
|
|
313
|
+
// ],
|
|
314
|
+
// contexts: [
|
|
315
|
+
// { name: "archive", counts: { pending: 0, completed: 2, total: 2 } },
|
|
316
|
+
// { name: "computer", counts: { pending: 2, completed: 2, total: 4 } },
|
|
317
|
+
// { name: "errands", counts: { pending: 2, completed: 1, total: 3 } },
|
|
318
|
+
// { name: "github", counts: { pending: 1, completed: 2, total: 3 } },
|
|
319
|
+
// { name: "hardware", counts: { pending: 2, completed: 0, total: 2 } },
|
|
320
|
+
// { name: "home", counts: { pending: 3, completed: 1, total: 4 } },
|
|
321
|
+
// { name: "phone", counts: { pending: 2, completed: 1, total: 3 } },
|
|
322
|
+
// ],
|
|
323
|
+
// }
|
|
324
|
+
|
|
325
|
+
await todos.countsByProject(); // summary.projects on its own
|
|
326
|
+
await todos.countsByContext(); // summary.contexts on its own
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Aggregates respect filter chains, so they can be scoped like any other query:
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
await todos.pending().summary(); // pending records only
|
|
333
|
+
await todos.project("GarageSale").summary(); // one project's dashboard
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
The counting rules:
|
|
337
|
+
|
|
338
|
+
- A record tagged with several names counts once per name, so per-name
|
|
339
|
+
totals do **not** sum to the top-level `total`: multi-tag records make the
|
|
340
|
+
sum larger and untagged records make it smaller.
|
|
341
|
+
- Names are unique and alphabetically sorted, matching `projects()` and
|
|
342
|
+
`contexts()`. Completed-only records still contribute their names; use
|
|
343
|
+
`pending().summary()` (or `pending().countsByProject()`) to count pending
|
|
344
|
+
work only.
|
|
345
|
+
- `sortBy` steps are ignored, like the name plucks.
|
|
346
|
+
- Aggregates load through the cache like every other query.
|
|
347
|
+
|
|
296
348
|
### Case-insensitive matching
|
|
297
349
|
|
|
298
350
|
Name matching is exact by default. Change the default for a whole client, or
|
package/dist/index.d.ts
CHANGED
|
@@ -161,6 +161,51 @@ interface TodoMatchOptions {
|
|
|
161
161
|
/** Compare case-sensitively (or, for search, insensitively) for this call. */
|
|
162
162
|
caseSensitive?: boolean;
|
|
163
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* Pending/completed/total counts for one bucket of records.
|
|
166
|
+
*
|
|
167
|
+
* `total` is always `pending + completed`.
|
|
168
|
+
*/
|
|
169
|
+
interface TodoCount {
|
|
170
|
+
/** Records that are not completed. */
|
|
171
|
+
pending: number;
|
|
172
|
+
/** Records marked completed. */
|
|
173
|
+
completed: number;
|
|
174
|
+
/** Every record in the bucket. */
|
|
175
|
+
total: number;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* One named bucket with its counts, from the aggregate query methods.
|
|
179
|
+
*
|
|
180
|
+
* The name is the project or context exactly as parsed, without the `+` or
|
|
181
|
+
* `@` prefix and with its original casing.
|
|
182
|
+
*/
|
|
183
|
+
interface TodoNameCount {
|
|
184
|
+
/** Project or context name from the matching records. */
|
|
185
|
+
name: string;
|
|
186
|
+
/** Counts over the matching records that carry the name. */
|
|
187
|
+
counts: TodoCount;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Result of {@link TodoQuery.summary}: totals for the matching records plus
|
|
191
|
+
* per-name counts.
|
|
192
|
+
*
|
|
193
|
+
* Per-name totals count multi-tag records once per name, so they do not sum
|
|
194
|
+
* to the top-level `total` when multi-tag records or untagged records
|
|
195
|
+
* exist.
|
|
196
|
+
*/
|
|
197
|
+
interface TodoSummary {
|
|
198
|
+
/** Every record matching the query. */
|
|
199
|
+
total: number;
|
|
200
|
+
/** Matching records that are not completed. */
|
|
201
|
+
pending: number;
|
|
202
|
+
/** Matching records that are completed. */
|
|
203
|
+
completed: number;
|
|
204
|
+
/** Per-project counts over the matching records. */
|
|
205
|
+
projects: TodoNameCount[];
|
|
206
|
+
/** Per-context counts over the matching records. */
|
|
207
|
+
contexts: TodoNameCount[];
|
|
208
|
+
}
|
|
164
209
|
/**
|
|
165
210
|
* A lazy query over parsed todo records.
|
|
166
211
|
*
|
|
@@ -171,6 +216,8 @@ interface TodoMatchOptions {
|
|
|
171
216
|
* `project(["A", "B"])` matches either name while `project("A").project("B")`
|
|
172
217
|
* requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}
|
|
173
218
|
* are terminal plucks that resolve to unique, alphabetically sorted names;
|
|
219
|
+
* {@link TodoQuery.summary}, {@link TodoQuery.countsByProject}, and
|
|
220
|
+
* {@link TodoQuery.countsByContext} are terminal aggregates; and
|
|
174
221
|
* {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.
|
|
175
222
|
*/
|
|
176
223
|
interface TodoQuery extends PromiseLike<TodoRecord[]> {
|
|
@@ -251,6 +298,30 @@ interface TodoQuery extends PromiseLike<TodoRecord[]> {
|
|
|
251
298
|
projects: () => Promise<string[]>;
|
|
252
299
|
/** Unique context names in the current result, alphabetically sorted. */
|
|
253
300
|
contexts: () => Promise<string[]>;
|
|
301
|
+
/**
|
|
302
|
+
* Aggregate counts for the records matching this query.
|
|
303
|
+
*
|
|
304
|
+
* `total`, `pending`, and `completed` count matching records, while
|
|
305
|
+
* `projects` and `contexts` count each matching record once per distinct
|
|
306
|
+
* name it carries, so a record tagged `+A +B` adds one to each name.
|
|
307
|
+
* Per-name totals therefore do not sum to the top-level `total` when
|
|
308
|
+
* multi-tag records or untagged records exist. Names are unique, keep
|
|
309
|
+
* their original casing, and sort alphabetically like
|
|
310
|
+
* {@link TodoQuery.projects}; completed-only records still contribute
|
|
311
|
+
* their names. A `sortBy` step is ignored, and the summary loads through
|
|
312
|
+
* the cache like every other query.
|
|
313
|
+
*/
|
|
314
|
+
summary: () => Promise<TodoSummary>;
|
|
315
|
+
/**
|
|
316
|
+
* Unique project names in the current result with their counts; see
|
|
317
|
+
* {@link TodoQuery.summary} for the counting rules.
|
|
318
|
+
*/
|
|
319
|
+
countsByProject: () => Promise<TodoNameCount[]>;
|
|
320
|
+
/**
|
|
321
|
+
* Unique context names in the current result with their counts; see
|
|
322
|
+
* {@link TodoQuery.summary} for the counting rules.
|
|
323
|
+
*/
|
|
324
|
+
countsByContext: () => Promise<TodoNameCount[]>;
|
|
254
325
|
/** Number of records in the current result; equal to `(await query).length`. */
|
|
255
326
|
count: () => Promise<number>;
|
|
256
327
|
/**
|
|
@@ -306,6 +377,12 @@ interface TodoTxtClient {
|
|
|
306
377
|
projects: () => Promise<string[]>;
|
|
307
378
|
/** List unique context names from the cached snapshot, alphabetically sorted. */
|
|
308
379
|
contexts: () => Promise<string[]>;
|
|
380
|
+
/** Aggregate counts for the cached snapshot; see {@link TodoQuery.summary}. */
|
|
381
|
+
summary: () => Promise<TodoSummary>;
|
|
382
|
+
/** Per-project counts for the cached snapshot; see {@link TodoQuery.countsByProject}. */
|
|
383
|
+
countsByProject: () => Promise<TodoNameCount[]>;
|
|
384
|
+
/** Per-context counts for the cached snapshot; see {@link TodoQuery.countsByContext}. */
|
|
385
|
+
countsByContext: () => Promise<TodoNameCount[]>;
|
|
309
386
|
}
|
|
310
387
|
/**
|
|
311
388
|
* Create a todo.txt client backed by consumer-supplied file hooks.
|
|
@@ -326,10 +403,11 @@ interface TodoTxtClient {
|
|
|
326
403
|
*
|
|
327
404
|
* Every line is parsed into a {@link TodoRecord} when the cache is populated.
|
|
328
405
|
* Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}
|
|
329
|
-
* operate on that array of JSON records,
|
|
330
|
-
* {@link TodoQuery.projects} return unique, alphabetically sorted names
|
|
331
|
-
*
|
|
332
|
-
*
|
|
406
|
+
* operate on that array of JSON records, plucks such as
|
|
407
|
+
* {@link TodoQuery.projects} return unique, alphabetically sorted names, and
|
|
408
|
+
* aggregates such as {@link TodoQuery.summary} count pending and completed
|
|
409
|
+
* records per name. Returned records are copies, so callers may mutate them
|
|
410
|
+
* without affecting the cache.
|
|
333
411
|
*/
|
|
334
412
|
export declare function createTodoTxt(options: TodoClientOptions): TodoTxtClient;
|
|
335
413
|
/**
|
|
@@ -370,4 +448,4 @@ export declare function parseLine(line: string, onWarning: ParseWarningHandler):
|
|
|
370
448
|
export declare function parseDocument(contents: string, options?: ParseOptions): TodoRecord[];
|
|
371
449
|
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
372
450
|
export declare function parseDocument(contents: string, onWarning: ParseWarningHandler): TodoRecord[];
|
|
373
|
-
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoFileHooks, TodoHooks, TodoLogger, TodoMatchOptions, TodoQuery, TodoRecord, TodoSortDirection, TodoSortField, TodoTxtClient };
|
|
451
|
+
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoCount, TodoFileHooks, TodoHooks, TodoLogger, TodoMatchOptions, TodoNameCount, TodoQuery, TodoRecord, TodoSortDirection, TodoSortField, TodoSummary, TodoTxtClient };
|
package/dist/index.js
CHANGED
|
@@ -337,12 +337,69 @@ function pluckNames(load, state, pick) {
|
|
|
337
337
|
sort: void 0
|
|
338
338
|
}).then((records) => uniqueSorted(records.flatMap(pick)));
|
|
339
339
|
}
|
|
340
|
+
/**
|
|
341
|
+
* Count pending/completed/total per unique name over `records`.
|
|
342
|
+
*
|
|
343
|
+
* Each record contributes at most once per name, so a record tagged
|
|
344
|
+
* `+A +A` counts `A` once. Names keep their original casing and sort
|
|
345
|
+
* like the name plucks, so buckets line up with `projects()`/`contexts()`.
|
|
346
|
+
*/
|
|
347
|
+
function countNames(records, pick) {
|
|
348
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
349
|
+
for (const record of records) for (const name of new Set(pick(record))) {
|
|
350
|
+
const bucket = buckets.get(name);
|
|
351
|
+
if (bucket === void 0) buckets.set(name, {
|
|
352
|
+
pending: record.completed ? 0 : 1,
|
|
353
|
+
completed: record.completed ? 1 : 0,
|
|
354
|
+
total: 1
|
|
355
|
+
});
|
|
356
|
+
else if (record.completed) {
|
|
357
|
+
bucket.completed += 1;
|
|
358
|
+
bucket.total += 1;
|
|
359
|
+
} else {
|
|
360
|
+
bucket.pending += 1;
|
|
361
|
+
bucket.total += 1;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return [...buckets].map(([name, counts]) => ({
|
|
365
|
+
name,
|
|
366
|
+
counts
|
|
367
|
+
})).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
368
|
+
}
|
|
340
369
|
function resolveCount(load, state) {
|
|
341
370
|
return resolveRaw(load, {
|
|
342
371
|
...state,
|
|
343
372
|
sort: void 0
|
|
344
373
|
}).then((records) => records.length);
|
|
345
374
|
}
|
|
375
|
+
/**
|
|
376
|
+
* Aggregate the current result into a summary.
|
|
377
|
+
*
|
|
378
|
+
* Sorting never applies to aggregates; they count records, not order them.
|
|
379
|
+
*/
|
|
380
|
+
async function resolveSummary(load, state) {
|
|
381
|
+
const records = await resolveRaw(load, {
|
|
382
|
+
...state,
|
|
383
|
+
sort: void 0
|
|
384
|
+
});
|
|
385
|
+
let pending = 0;
|
|
386
|
+
let completed = 0;
|
|
387
|
+
for (const record of records) if (record.completed) completed += 1;
|
|
388
|
+
else pending += 1;
|
|
389
|
+
return {
|
|
390
|
+
total: records.length,
|
|
391
|
+
pending,
|
|
392
|
+
completed,
|
|
393
|
+
projects: countNames(records, (todo) => todo.projects),
|
|
394
|
+
contexts: countNames(records, (todo) => todo.contexts)
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function resolveCountsBy(load, state, pick) {
|
|
398
|
+
return resolveRaw(load, {
|
|
399
|
+
...state,
|
|
400
|
+
sort: void 0
|
|
401
|
+
}).then((records) => countNames(records, pick));
|
|
402
|
+
}
|
|
346
403
|
async function resolveFirst(load, state) {
|
|
347
404
|
const first = (await resolveRaw(load, state))[0];
|
|
348
405
|
return first === void 0 ? void 0 : cloneRecord(first);
|
|
@@ -440,6 +497,9 @@ function createTodoQuery(load, state = {
|
|
|
440
497
|
}),
|
|
441
498
|
projects: () => pluckNames(load, state, (todo) => todo.projects),
|
|
442
499
|
contexts: () => pluckNames(load, state, (todo) => todo.contexts),
|
|
500
|
+
summary: () => resolveSummary(load, state),
|
|
501
|
+
countsByProject: () => resolveCountsBy(load, state, (todo) => todo.projects),
|
|
502
|
+
countsByContext: () => resolveCountsBy(load, state, (todo) => todo.contexts),
|
|
443
503
|
count: () => resolveCount(load, state),
|
|
444
504
|
first: () => resolveFirst(load, state),
|
|
445
505
|
then: (onfulfilled, onrejected) => resolveRecords(load, state).then(onfulfilled, onrejected)
|
|
@@ -465,10 +525,11 @@ function createTodoQuery(load, state = {
|
|
|
465
525
|
*
|
|
466
526
|
* Every line is parsed into a {@link TodoRecord} when the cache is populated.
|
|
467
527
|
* Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}
|
|
468
|
-
* operate on that array of JSON records,
|
|
469
|
-
* {@link TodoQuery.projects} return unique, alphabetically sorted names
|
|
470
|
-
*
|
|
471
|
-
*
|
|
528
|
+
* operate on that array of JSON records, plucks such as
|
|
529
|
+
* {@link TodoQuery.projects} return unique, alphabetically sorted names, and
|
|
530
|
+
* aggregates such as {@link TodoQuery.summary} count pending and completed
|
|
531
|
+
* records per name. Returned records are copies, so callers may mutate them
|
|
532
|
+
* without affecting the cache.
|
|
472
533
|
*/
|
|
473
534
|
function createTodoTxt(options) {
|
|
474
535
|
let cache;
|
|
@@ -537,7 +598,10 @@ function createTodoTxt(options) {
|
|
|
537
598
|
count: query.count,
|
|
538
599
|
first: query.first,
|
|
539
600
|
projects: query.projects,
|
|
540
|
-
contexts: query.contexts
|
|
601
|
+
contexts: query.contexts,
|
|
602
|
+
summary: query.summary,
|
|
603
|
+
countsByProject: query.countsByProject,
|
|
604
|
+
countsByContext: query.countsByContext
|
|
541
605
|
};
|
|
542
606
|
}
|
|
543
607
|
export { createTodoTxt, parseDocument, parseLine };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/date.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n const copy: TodoRecord = {\n completed: todo.completed,\n priority: todo.priority,\n completedAt: todo.completedAt,\n createdAt: todo.createdAt,\n description: todo.description,\n projects: [...todo.projects],\n contexts: [...todo.contexts],\n data: { ...todo.data },\n };\n\n if (todo.line !== undefined) {\n copy.line = todo.line;\n }\n\n if (todo.raw !== undefined) {\n copy.raw = todo.raw;\n }\n\n return copy;\n}\n\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\n}\n","const DATE_SHAPE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYear(year: number): boolean {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\n/**\n * True when `value` is a real calendar date in `YYYY-MM-DD` form.\n *\n * The check is purely arithmetic so it does not depend on the host timezone and\n * does not let JavaScript's `Date` roll invalid values over (for example,\n * `2011-02-30` must not become March 2).\n */\nexport function isValidDate(value: string): boolean {\n const match = DATE_SHAPE_PATTERN.exec(value);\n if (!match) {\n return false;\n }\n\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n\n if (month < 1 || month > 12 || day < 1) {\n return false;\n }\n\n const maxDay =\n month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);\n\n return day <= maxDay;\n}\n","import type { ParseWarningHandler } from \"./types.ts\";\n\nconst EXTENSION_PATTERN = /^([^:\\s]+):([^:\\s]+)$/;\n\n/** Metadata collected from a task's text. */\nexport interface TodoMetadata {\n projects: string[];\n contexts: string[];\n data: Record<string, string>;\n}\n\n/** Everything derived from a task's text in one token pass. */\nexport interface TodoText extends TodoMetadata {\n description: string;\n}\n\nfunction tokenize(text: string): string[] {\n const trimmed = text.trim();\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(/\\s+/);\n}\n\n/**\n * True when a whitespace-delimited token is inline metadata.\n *\n * Inline metadata is a project (`+name`), a context (`@name`), or a\n * `key:value` extension. Bare `+`/`@` tokens and values containing another\n * colon are not metadata.\n */\nexport function isMetadataToken(token: string): boolean {\n if (token.startsWith(\"+\") && token.length > 1) {\n return true;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n return true;\n }\n\n return EXTENSION_PATTERN.test(token);\n}\n\n/**\n * Collect a task's description, projects, contexts, and extensions in one pass.\n *\n * Previous versions tokenized the text once for metadata and again to strip it;\n * doing both here keeps parsing to a single split per line.\n *\n * When a `key:value` key is repeated, `onWarning` receives a\n * `duplicate-metadata-key` warning and the last value wins.\n */\nexport function parseText(\n text: string,\n onWarning?: ParseWarningHandler,\n): TodoText {\n const projects: string[] = [];\n const contexts: string[] = [];\n const data: Record<string, string> = {};\n const descriptionTokens: string[] = [];\n\n for (const token of tokenize(text)) {\n if (token.startsWith(\"+\") && token.length > 1) {\n projects.push(token.slice(1));\n continue;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n contexts.push(token.slice(1));\n continue;\n }\n\n const extension = EXTENSION_PATTERN.exec(token);\n const key = extension?.[1];\n const value = extension?.[2];\n if (key !== undefined && value !== undefined) {\n if (Object.hasOwn(data, key)) {\n onWarning?.({\n code: \"duplicate-metadata-key\",\n message: `Duplicate metadata key \"${key}\"; the last value wins.`,\n meta: { key, previousValue: data[key], value },\n });\n }\n\n data[key] = value;\n continue;\n }\n\n descriptionTokens.push(token);\n }\n\n return {\n description: descriptionTokens.join(\" \"),\n projects,\n contexts,\n data,\n };\n}\n\n/** Collect projects, contexts, and extensions from task text. */\nexport function parseMetadata(text: string): TodoMetadata {\n const { projects, contexts, data } = parseText(text);\n return { projects, contexts, data };\n}\n\n/**\n * Remove inline metadata from task text.\n *\n * Remaining tokens are rejoined with single spaces, so repeated whitespace can\n * be normalized.\n */\nexport function stripMetadata(text: string): string {\n return parseText(text).description;\n}\n","import { isValidDate } from \"./date.ts\";\nimport { parseText } from \"./metadata.ts\";\nimport type {\n ParseOptions,\n ParseWarningHandler,\n TodoRecord,\n} from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\ntype LeadingDate =\n | { kind: \"absent\"; rest: string }\n | { kind: \"valid\"; date: string; rest: string }\n | { kind: \"invalid\"; value: string; rest: string };\n\n/**\n * Inspect a `YYYY-MM-DD` token at the start of `input`.\n *\n * A value with the right shape that does not exist on the calendar is reported\n * as `invalid`. In that case `rest` is the original input, so callers leave the\n * token in the description instead of consuming it.\n */\nfunction takeLeadingDate(input: string): LeadingDate {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return { kind: \"absent\", rest: input };\n }\n\n const date = match[1];\n if (date === undefined) {\n return { kind: \"absent\", rest: input };\n }\n\n if (!isValidDate(date)) {\n return { kind: \"invalid\", value: date, rest: input };\n }\n\n return { kind: \"valid\", date, rest: input.slice(match[0]!.length) };\n}\n\nfunction warnInvalidDate(\n value: string,\n field: \"completedAt\" | \"createdAt\",\n onWarning?: ParseWarningHandler,\n): void {\n const label = field === \"completedAt\" ? \"completion\" : \"creation\";\n\n onWarning?.({\n code: \"invalid-date\",\n message: `Invalid ${label} date \"${value}\"; treating it as text.`,\n meta: { value, field },\n });\n}\n\n/**\n * Accept either a {@link ParseWarningHandler} (deprecated) or\n * {@link ParseOptions} as the second argument.\n */\nfunction normalizeParseOptions(\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): ParseOptions {\n if (typeof onWarningOrOptions === \"function\") {\n return { onWarning: onWarningOrOptions };\n }\n\n return onWarningOrOptions ?? {};\n}\n\n/** Remove one trailing `\\r`, so `raw` has no carriage return for CRLF input. */\nfunction stripTrailingCarriageReturn(line: string): string {\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.\n *\n * The parser follows the todo.txt format rules:\n *\n * - Completed tasks start with `x `, optionally followed by a completion date\n * and then a creation date.\n * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional\n * creation date.\n * - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but\n * nonexistent date is treated as text.\n * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `options.onWarning` when supplied;\n * parsing still produces a record.\n *\n * With `options.includeSource`, the record carries `raw` (the exact input\n * line, minus a trailing `\\r`) and `line` (the number supplied via\n * `options.line`, when given).\n */\nexport function parseLine(\n line: string,\n options?: ParseOptions,\n): TodoRecord;\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseLine(\n line: string,\n onWarning: ParseWarningHandler,\n): TodoRecord;\nexport function parseLine(\n line: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord {\n const options = normalizeParseOptions(onWarningOrOptions);\n let rest = line;\n let completed = false;\n let priority: string | null = null;\n let completedAt: string | null = null;\n let createdAt: string | null = null;\n\n if (rest.startsWith(\"x \")) {\n completed = true;\n rest = rest.slice(2);\n\n const completedDate = takeLeadingDate(rest);\n if (completedDate.kind === \"valid\") {\n completedAt = completedDate.date;\n rest = completedDate.rest;\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n } else if (completedDate.kind === \"invalid\") {\n // The same token cannot also be a creation date, so only warn once.\n warnInvalidDate(completedDate.value, \"completedAt\", options.onWarning);\n }\n } else {\n const priorityMatch = PRIORITY_PATTERN.exec(rest);\n if (priorityMatch) {\n priority = priorityMatch[1]!;\n rest = rest.slice(priorityMatch[0]!.length);\n }\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(\n text,\n options.onWarning,\n );\n\n const record: TodoRecord = {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\n\n if (options.includeSource) {\n if (options.line !== undefined) {\n record.line = options.line;\n }\n\n record.raw = stripTrailingCarriageReturn(line);\n }\n\n return record;\n}\n\n/**\n * Parse the contents of a todo.txt file.\n *\n * Lines are split on `\\n` or `\\r\\n`; blank and whitespace-only lines are\n * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are\n * annotated with the 1-based physical line number.\n *\n * With `options.includeSource`, every record carries `raw` (the exact line,\n * minus a trailing `\\r`) and `line` (the 1-based physical line number,\n * counting blank lines).\n */\nexport function parseDocument(\n contents: string,\n options?: ParseOptions,\n): TodoRecord[];\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseDocument(\n contents: string,\n onWarning: ParseWarningHandler,\n): TodoRecord[];\nexport function parseDocument(\n contents: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord[] {\n const { includeSource, onWarning } = normalizeParseOptions(onWarningOrOptions);\n const records: TodoRecord[] = [];\n let lineNumber = 0;\n\n for (const line of contents.split(/\\r?\\n/)) {\n lineNumber += 1;\n\n if (line.trim() !== \"\") {\n records.push(\n parseLine(line, {\n includeSource,\n line: lineNumber,\n onWarning: onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n }),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecord, cloneRecords } from \"./clone.ts\";\nimport { isValidDate } from \"./date.ts\";\nimport type { TodoRecord } from \"./types.ts\";\n\n/** A predicate applied to every record in a query. */\nexport type TodoFilter = (todo: TodoRecord) => boolean;\n\n/** Loads and parses every todo.txt record. */\nexport type LoadRecords = () => Promise<TodoRecord[]>;\n\n/** Fields that {@link TodoQuery.sortBy} can order results by. */\nexport type TodoSortField =\n | \"priority\"\n | \"createdAt\"\n | \"completedAt\"\n | \"description\"\n | \"due\";\n\n/** Sort direction for {@link TodoQuery.sortBy}. Default: `\"asc\"`. */\nexport type TodoSortDirection = \"asc\" | \"desc\";\n\n/**\n * Per-call matching options.\n *\n * `caseSensitive` overrides the client-level default for one call. The default\n * differs per method: project and context matching is exact and case-sensitive\n * unless the option says otherwise, while search is case-insensitive unless the\n * option says otherwise.\n */\nexport interface TodoMatchOptions {\n /** Compare case-sensitively (or, for search, insensitively) for this call. */\n caseSensitive?: boolean;\n}\n\n/** One ordering step appended by {@link TodoQuery.sortBy}. */\nexport interface TodoSortSpec {\n field: TodoSortField;\n direction: TodoSortDirection;\n}\n\n/** Internal query state: AND-composed filters plus one optional sort step. */\nexport interface TodoQueryState {\n filters: TodoFilter[];\n sort?: TodoSortSpec;\n /**\n * Client-level default for name matching. Search is unaffected: it stays\n * case-insensitive by default no matter what this says.\n */\n caseSensitive: boolean;\n}\n\n/**\n * A lazy query over parsed todo records.\n *\n * Filters return a new query and perform no IO. Awaiting a query resolves\n * through the supplied loader; the client caches parsed records, so only the\n * first query reads the file. Filters compose with AND: every predicate added\n * to the chain must match. Array arguments are OR within a single call, so\n * `project([\"A\", \"B\"])` matches either name while `project(\"A\").project(\"B\")`\n * requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}\n * are terminal plucks that resolve to unique, alphabetically sorted names;\n * {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.\n */\nexport interface TodoQuery extends PromiseLike<TodoRecord[]> {\n /** Only records that are not completed. */\n pending: () => TodoQuery;\n /** Only records that are completed. */\n completed: () => TodoQuery;\n /**\n * Only records tagged with the project `name`.\n *\n * An array matches any listed name (OR); repeated calls require every name\n * (AND). An empty array matches nothing. Matching is exact and\n * case-sensitive unless the client-level `caseSensitive` option or the\n * per-call override says otherwise; case-insensitive comparison uses\n * `toLowerCase()`, which is not full Unicode case folding.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records not tagged with the project `name`.\n *\n * An array excludes every listed name; an empty array excludes nothing.\n * This is not a replacement for `pending()`/`completed()`.\n */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with priority `letter`.\n *\n * Matching is exact against the uppercase letter the parser stores, so\n * `priority(\"a\")` matches nothing. An array matches any listed letter.\n */\n priority: (letter: string | string[]) => TodoQuery;\n /**\n * Only records whose description contains `text` as a substring.\n *\n * Case-insensitive by default, independently of the client-level matching\n * option. Only `description` is searched; projects, contexts, and metadata\n * have their own filters.\n */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with the metadata `key`.\n *\n * With a `value`, the record's value must match it exactly.\n */\n meta: (key: string, value?: string) => TodoQuery;\n /** Only records that have the metadata `key`, whatever its value. */\n hasMeta: (key: string) => TodoQuery;\n /**\n * Only records created strictly after `date`.\n *\n * The argument must be a real calendar date in `YYYY-MM-DD` form; anything\n * else throws a `TypeError` when the query is built, before any IO.\n * Records without a creation date never match.\n */\n createdAfter: (date: string) => TodoQuery;\n /** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /**\n * Sort the filtered records by `field`; default direction is `\"asc\"`.\n *\n * The sort is stable: records with equal keys keep file order. Missing\n * values (`null` priorities or dates, and missing or invalid `due` values)\n * sort last in both directions; `\"desc\"` reverses only the value\n * comparison, never the missing-value placement. Calling `sortBy` twice\n * keeps only the last call. Description ordering uses `localeCompare`, so\n * it follows the host locale for equal-ignoring-case ties.\n */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Unique project names in the current result, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** Unique context names in the current result, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /** Number of records in the current result; equal to `(await query).length`. */\n count: () => Promise<number>;\n /**\n * The first record of the filtered (and sorted) result, or `undefined`\n * when nothing matches. The record is a copy, so mutating it cannot affect\n * the client's cache.\n */\n first: () => Promise<TodoRecord | undefined>;\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Build a name-matching predicate for projects or contexts.\n *\n * Case-insensitive comparison normalizes both sides with `toLowerCase()`,\n * which is deterministic across machines and locales but not full Unicode\n * case folding. `invert` turns the predicate into a negation filter.\n */\nfunction nameFilter(\n pick: (todo: TodoRecord) => string[],\n names: string[],\n caseSensitive: boolean,\n invert: boolean,\n): TodoFilter {\n const wanted = caseSensitive\n ? names\n : names.map((name) => name.toLowerCase());\n\n const matches = (todo: TodoRecord): boolean =>\n pick(todo).some((value) =>\n wanted.includes(caseSensitive ? value : value.toLowerCase()),\n );\n\n return invert ? (todo) => !matches(todo) : matches;\n}\n\n/**\n * Validate a date-filter argument at query-build time.\n *\n * Invalid arguments throw instead of silently matching nothing, so a typo in\n * a bound cannot hide behind an empty result.\n */\nfunction requireValidDate(date: string, method: string): string {\n if (!isValidDate(date)) {\n throw new TypeError(\n `${method}() expected a real calendar date in YYYY-MM-DD form, got \"${date}\".`,\n );\n }\n\n return date;\n}\n\n/**\n * Build a date-comparison predicate on a record date field.\n *\n * Records with `null` dates never match; validated `YYYY-MM-DD` values\n * compare correctly as plain strings.\n */\nfunction dateFilter(\n field: \"createdAt\" | \"completedAt\",\n date: string,\n method: string,\n keep: (recordDate: string, bound: string) => boolean,\n): TodoFilter {\n const bound = requireValidDate(date, method);\n\n return (todo) => {\n const recordDate = todo[field];\n return recordDate !== null && keep(recordDate, bound);\n };\n}\n\n/** Read `data.due` when it is a real calendar date; otherwise `null`. */\nfunction dueDateOf(todo: TodoRecord): string | null {\n const due = todo.data[\"due\"];\n return due !== undefined && isValidDate(due) ? due : null;\n}\n\ntype NullableSortField = Exclude<TodoSortField, \"description\">;\n\n/** Extract the nullable sort key for every field except `description`. */\nfunction sortKey(todo: TodoRecord, field: NullableSortField): string | null {\n switch (field) {\n case \"priority\":\n return todo.priority;\n case \"createdAt\":\n return todo.createdAt;\n case \"completedAt\":\n return todo.completedAt;\n case \"due\":\n return dueDateOf(todo);\n }\n}\n\n/**\n * Compare nullable keys with missing values last in both directions.\n *\n * `desc` negates only the value comparison, never the missing-value\n * placement; equal keys compare as `0` so the stable sort keeps file order.\n */\nfunction compareNullableKeys(\n a: string | null,\n b: string | null,\n direction: TodoSortDirection,\n): number {\n if (a === null) {\n return b === null ? 0 : 1;\n }\n\n if (b === null) {\n return -1;\n }\n\n const result = a < b ? -1 : a > b ? 1 : 0;\n return direction === \"asc\" ? result : -result;\n}\n\n/** Build the sort comparator for one ordering step. */\nfunction makeComparator(\n spec: TodoSortSpec,\n): (a: TodoRecord, b: TodoRecord) => number {\n if (spec.field === \"description\") {\n return (a, b) => {\n const result = a.description.localeCompare(b.description);\n return spec.direction === \"asc\" ? result : -result;\n };\n }\n\n const field: NullableSortField = spec.field;\n\n return (a, b) =>\n compareNullableKeys(\n sortKey(a, field),\n sortKey(b, field),\n spec.direction,\n );\n}\n\n/**\n * Sort in place and return the same array.\n *\n * `Array#sort` is stable, so records with equal keys keep file order.\n */\nfunction applySort(records: TodoRecord[], sort: TodoSortSpec): TodoRecord[] {\n return records.sort(makeComparator(sort));\n}\n\n/**\n * Load, filter, and sort records without cloning them.\n *\n * The returned array is safe to sort because it is always a fresh copy when\n * a sort step exists; without one the loader's own array is returned as-is.\n */\nasync function resolveRaw(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (state.sort === undefined) {\n if (state.filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n }\n\n // Never sort the loader's array in place: the client's cache must keep\n // file order for later queries.\n const matches =\n state.filters.length === 0\n ? records.slice()\n : records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n\n return applySort(matches, state.sort);\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, state));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n // Sorting never applies to name plucks; they alphabetize themselves.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\n}\n\nfunction resolveCount(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<number> {\n return resolveRaw(load, { ...state, sort: undefined }).then(\n (records) => records.length,\n );\n}\n\nasync function resolveFirst(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord | undefined> {\n const first = (await resolveRaw(load, state))[0];\n return first === undefined ? undefined : cloneRecord(first);\n}\n\n/**\n * Create a lazy query over the records loaded by `load`.\n *\n * Each filter method appends a predicate, so chained calls compose with AND,\n * while array arguments match any listed value. `sortBy` appends an ordering\n * step instead of a predicate; the last `sortBy` call wins. For example,\n * `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`, and\n * `pending().sortBy(\"priority\")` lists them A first.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n state: TodoQueryState = { filters: [], caseSensitive: true },\n): TodoQuery {\n const nameOptions = (options?: TodoMatchOptions): boolean =>\n options?.caseSensitive ?? state.caseSensitive;\n\n return {\n pending: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => !todo.completed],\n }),\n completed: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => todo.completed],\n }),\n project: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n context: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n notProject: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n notContext: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n priority: (letter) => {\n const letters = toArray(letter);\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => todo.priority !== null && letters.includes(todo.priority),\n ],\n });\n },\n search: (text, options) => {\n const caseSensitive = options?.caseSensitive ?? false;\n const needle = caseSensitive ? text : text.toLowerCase();\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => {\n const haystack = caseSensitive\n ? todo.description\n : todo.description.toLowerCase();\n return haystack.includes(needle);\n },\n ],\n });\n },\n meta: (key, value) => {\n const filter: TodoFilter =\n value === undefined\n ? (todo) => Object.hasOwn(todo.data, key)\n : (todo) => todo.data[key] === value;\n\n return createTodoQuery(load, { ...state, filters: [...state.filters, filter] });\n },\n hasMeta: (key) =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)],\n }),\n createdAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdAfter\", (a, b) => a > b),\n ],\n }),\n createdBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdBefore\", (a, b) => a < b),\n ],\n }),\n completedAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedAfter\", (a, b) => a > b),\n ],\n }),\n completedBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedBefore\", (a, b) => a < b),\n ],\n }),\n sortBy: (field, direction = \"asc\") =>\n createTodoQuery(load, { ...state, sort: { field, direction } }),\n projects: () => pluckNames(load, state, (todo) => todo.projects),\n contexts: () => pluckNames(load, state, (todo) => todo.contexts),\n count: () => resolveCount(load, state),\n first: () => resolveFirst(load, state),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, state).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type {\n TodoMatchOptions,\n TodoQuery,\n TodoSortDirection,\n TodoSortField,\n} from \"./query.ts\";\nimport type {\n TodoClientOptions,\n TodoLogger,\n TodoRecord,\n} from \"./types.ts\";\n\n/** The read interface returned by {@link createTodoTxt}. */\nexport interface TodoTxtClient {\n /** Read fresh todo.txt contents, replace the cache, and return every record. */\n all: () => Promise<TodoRecord[]>;\n /** Query only records that are not completed, using the cached snapshot. */\n pending: () => TodoQuery;\n /** Query only records that are completed, using the cached snapshot. */\n completed: () => TodoQuery;\n /**\n * Query records tagged with the project `name`, using the cache.\n *\n * An array matches any listed name; see {@link TodoQuery.project}.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the priority `letter`; see {@link TodoQuery.priority}. */\n priority: (letter: string | string[]) => TodoQuery;\n /** Query records whose description contains `text`; see {@link TodoQuery.search}. */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the metadata `key`; see {@link TodoQuery.meta}. */\n meta: (key: string, value?: string) => TodoQuery;\n /** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */\n hasMeta: (key: string) => TodoQuery;\n /** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */\n createdAfter: (date: string) => TodoQuery;\n /** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Count records in the cached snapshot; see {@link TodoQuery.count}. */\n count: () => Promise<number>;\n /** First record of the cached snapshot; see {@link TodoQuery.first}. */\n first: () => Promise<TodoRecord | undefined>;\n /** List unique project names from the cached snapshot, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** List unique context names from the cached snapshot, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `options.read` is responsible for\n * producing the file contents and `options.write` will be used by the write\n * APIs once they are implemented. `options.logger` is optional and silent by\n * default; when supplied, it receives read lifecycle and parse warning\n * diagnostics. With `options.includeSource`, every record also carries the\n * 1-based `line` number and the exact `raw` line it was parsed from. With\n * `options.caseSensitive: false`, project and context matching compares\n * names through `toLowerCase()`; the default is exact matching.\n *\n * Parsed records are cached in memory per client. The first query loads and\n * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}\n * always reads fresh contents and replaces the cache, so it can be used to\n * refresh after the underlying file changes.\n *\n * Every line is parsed into a {@link TodoRecord} when the cache is populated.\n * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}\n * operate on that array of JSON records, and plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names.\n * Returned records are copies, so callers may mutate them without affecting the\n * cache.\n */\nexport function createTodoTxt(options: TodoClientOptions): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = options.logger;\n\n const log: TodoLogger = (level, message, meta) => {\n if (!logger) {\n return;\n }\n\n try {\n const result = logger(level, message, meta);\n\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n void Promise.resolve(result).catch(() => {});\n }\n } catch {\n // Logging is best-effort and must never break reads or queries.\n }\n };\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n\n log(\"debug\", \"Reading todo file\");\n const contents = await options.read();\n const records = parseDocument(contents, {\n includeSource: options.includeSource,\n onWarning: (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\n });\n },\n });\n log(\"debug\", \"Parsed todo file\", { records: records.length });\n\n if (currentGeneration === generation) {\n cache = records;\n }\n\n return records;\n };\n\n const refresh = (): Promise<TodoRecord[]> => {\n const promise = readFresh();\n inFlight = promise;\n\n void promise\n .finally(() => {\n if (inFlight === promise) {\n inFlight = undefined;\n }\n })\n .catch(() => {});\n\n return promise;\n };\n\n const loadCached = (): Promise<TodoRecord[]> => {\n if (inFlight) {\n return inFlight;\n }\n\n if (cache) {\n return Promise.resolve(cache);\n }\n\n return refresh();\n };\n\n const all = async (): Promise<TodoRecord[]> =>\n cloneRecords(await refresh());\n\n const query = createTodoQuery(loadCached, {\n filters: [],\n caseSensitive: options.caseSensitive ?? true,\n });\n\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n notProject: query.notProject,\n notContext: query.notContext,\n priority: query.priority,\n search: query.search,\n meta: query.meta,\n hasMeta: query.hasMeta,\n createdAfter: query.createdAfter,\n createdBefore: query.createdBefore,\n completedAfter: query.completedAfter,\n completedBefore: query.completedBefore,\n sortBy: query.sortBy,\n count: query.count,\n first: query.first,\n projects: query.projects,\n contexts: query.contexts,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,MAAM,OAAmB;EACvB,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,MAAM,EAAE,GAAG,KAAK,KAAK;CACvB;CAEA,IAAI,KAAK,SAAS,KAAA,GAChB,KAAK,OAAO,KAAK;CAGnB,IAAI,KAAK,QAAQ,KAAA,GACf,KAAK,MAAM,KAAK;CAGlB,OAAO;AACT;;AAGA,SAAgB,aAAa,SAA8C;CACzE,OAAO,QAAQ,IAAI,WAAW;AAChC;;AC7BA,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;CAAC;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;AAAE;AAErE,SAAS,WAAW,MAAuB;CACzC,OAAQ,OAAO,MAAM,KAAK,OAAO,QAAQ,KAAM,OAAO,QAAQ;AAChE;;;;;;;;AASA,SAAgB,YAAY,OAAwB;CAClD,MAAM,QAAQ,mBAAmB,KAAK,KAAK;CAC3C,IAAI,CAAC,OACH,OAAO;CAGT,MAAM,OAAO,OAAO,MAAM,EAAE;CAC5B,MAAM,QAAQ,OAAO,MAAM,EAAE;CAC7B,MAAM,MAAM,OAAO,MAAM,EAAE;CAE3B,IAAI,QAAQ,KAAK,QAAQ,MAAM,MAAM,G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O,QAAQ;CACjB;CAEA,MAAM,MAAM,YACV,aAAa,MAAM,QAAQ,CAAC;CAE9B,MAAM,QAAQ,gBAAgB,YAAY;EACxC,SAAS,CAAC;EACV,eAAe,QAAQ,iBAAiB;CAC1C,CAAC;CAED,OAAO;EACL;EACA,SAAS,MAAM;EACf,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,SAAS,MAAM;EACf,YAAY,MAAM;EAClB,YAAY,MAAM;EAClB,UAAU,MAAM;EAChB,QAAQ,MAAM;EACd,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,cAAc,MAAM;EACpB,eAAe,MAAM;EACrB,gBAAgB,MAAM;EACtB,iBAAiB,MAAM;EACvB,QAAQ,MAAM;EACd,OAAO,MAAM;EACb,OAAO,MAAM;EACb,UAAU,MAAM;EAChB,UAAU,MAAM;CAClB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/date.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n const copy: TodoRecord = {\n completed: todo.completed,\n priority: todo.priority,\n completedAt: todo.completedAt,\n createdAt: todo.createdAt,\n description: todo.description,\n projects: [...todo.projects],\n contexts: [...todo.contexts],\n data: { ...todo.data },\n };\n\n if (todo.line !== undefined) {\n copy.line = todo.line;\n }\n\n if (todo.raw !== undefined) {\n copy.raw = todo.raw;\n }\n\n return copy;\n}\n\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\n}\n","const DATE_SHAPE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYear(year: number): boolean {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\n/**\n * True when `value` is a real calendar date in `YYYY-MM-DD` form.\n *\n * The check is purely arithmetic so it does not depend on the host timezone and\n * does not let JavaScript's `Date` roll invalid values over (for example,\n * `2011-02-30` must not become March 2).\n */\nexport function isValidDate(value: string): boolean {\n const match = DATE_SHAPE_PATTERN.exec(value);\n if (!match) {\n return false;\n }\n\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n\n if (month < 1 || month > 12 || day < 1) {\n return false;\n }\n\n const maxDay =\n month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);\n\n return day <= maxDay;\n}\n","import type { ParseWarningHandler } from \"./types.ts\";\n\nconst EXTENSION_PATTERN = /^([^:\\s]+):([^:\\s]+)$/;\n\n/** Metadata collected from a task's text. */\nexport interface TodoMetadata {\n projects: string[];\n contexts: string[];\n data: Record<string, string>;\n}\n\n/** Everything derived from a task's text in one token pass. */\nexport interface TodoText extends TodoMetadata {\n description: string;\n}\n\nfunction tokenize(text: string): string[] {\n const trimmed = text.trim();\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(/\\s+/);\n}\n\n/**\n * True when a whitespace-delimited token is inline metadata.\n *\n * Inline metadata is a project (`+name`), a context (`@name`), or a\n * `key:value` extension. Bare `+`/`@` tokens and values containing another\n * colon are not metadata.\n */\nexport function isMetadataToken(token: string): boolean {\n if (token.startsWith(\"+\") && token.length > 1) {\n return true;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n return true;\n }\n\n return EXTENSION_PATTERN.test(token);\n}\n\n/**\n * Collect a task's description, projects, contexts, and extensions in one pass.\n *\n * Previous versions tokenized the text once for metadata and again to strip it;\n * doing both here keeps parsing to a single split per line.\n *\n * When a `key:value` key is repeated, `onWarning` receives a\n * `duplicate-metadata-key` warning and the last value wins.\n */\nexport function parseText(\n text: string,\n onWarning?: ParseWarningHandler,\n): TodoText {\n const projects: string[] = [];\n const contexts: string[] = [];\n const data: Record<string, string> = {};\n const descriptionTokens: string[] = [];\n\n for (const token of tokenize(text)) {\n if (token.startsWith(\"+\") && token.length > 1) {\n projects.push(token.slice(1));\n continue;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n contexts.push(token.slice(1));\n continue;\n }\n\n const extension = EXTENSION_PATTERN.exec(token);\n const key = extension?.[1];\n const value = extension?.[2];\n if (key !== undefined && value !== undefined) {\n if (Object.hasOwn(data, key)) {\n onWarning?.({\n code: \"duplicate-metadata-key\",\n message: `Duplicate metadata key \"${key}\"; the last value wins.`,\n meta: { key, previousValue: data[key], value },\n });\n }\n\n data[key] = value;\n continue;\n }\n\n descriptionTokens.push(token);\n }\n\n return {\n description: descriptionTokens.join(\" \"),\n projects,\n contexts,\n data,\n };\n}\n\n/** Collect projects, contexts, and extensions from task text. */\nexport function parseMetadata(text: string): TodoMetadata {\n const { projects, contexts, data } = parseText(text);\n return { projects, contexts, data };\n}\n\n/**\n * Remove inline metadata from task text.\n *\n * Remaining tokens are rejoined with single spaces, so repeated whitespace can\n * be normalized.\n */\nexport function stripMetadata(text: string): string {\n return parseText(text).description;\n}\n","import { isValidDate } from \"./date.ts\";\nimport { parseText } from \"./metadata.ts\";\nimport type {\n ParseOptions,\n ParseWarningHandler,\n TodoRecord,\n} from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\ntype LeadingDate =\n | { kind: \"absent\"; rest: string }\n | { kind: \"valid\"; date: string; rest: string }\n | { kind: \"invalid\"; value: string; rest: string };\n\n/**\n * Inspect a `YYYY-MM-DD` token at the start of `input`.\n *\n * A value with the right shape that does not exist on the calendar is reported\n * as `invalid`. In that case `rest` is the original input, so callers leave the\n * token in the description instead of consuming it.\n */\nfunction takeLeadingDate(input: string): LeadingDate {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return { kind: \"absent\", rest: input };\n }\n\n const date = match[1];\n if (date === undefined) {\n return { kind: \"absent\", rest: input };\n }\n\n if (!isValidDate(date)) {\n return { kind: \"invalid\", value: date, rest: input };\n }\n\n return { kind: \"valid\", date, rest: input.slice(match[0]!.length) };\n}\n\nfunction warnInvalidDate(\n value: string,\n field: \"completedAt\" | \"createdAt\",\n onWarning?: ParseWarningHandler,\n): void {\n const label = field === \"completedAt\" ? \"completion\" : \"creation\";\n\n onWarning?.({\n code: \"invalid-date\",\n message: `Invalid ${label} date \"${value}\"; treating it as text.`,\n meta: { value, field },\n });\n}\n\n/**\n * Accept either a {@link ParseWarningHandler} (deprecated) or\n * {@link ParseOptions} as the second argument.\n */\nfunction normalizeParseOptions(\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): ParseOptions {\n if (typeof onWarningOrOptions === \"function\") {\n return { onWarning: onWarningOrOptions };\n }\n\n return onWarningOrOptions ?? {};\n}\n\n/** Remove one trailing `\\r`, so `raw` has no carriage return for CRLF input. */\nfunction stripTrailingCarriageReturn(line: string): string {\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.\n *\n * The parser follows the todo.txt format rules:\n *\n * - Completed tasks start with `x `, optionally followed by a completion date\n * and then a creation date.\n * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional\n * creation date.\n * - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but\n * nonexistent date is treated as text.\n * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `options.onWarning` when supplied;\n * parsing still produces a record.\n *\n * With `options.includeSource`, the record carries `raw` (the exact input\n * line, minus a trailing `\\r`) and `line` (the number supplied via\n * `options.line`, when given).\n */\nexport function parseLine(\n line: string,\n options?: ParseOptions,\n): TodoRecord;\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseLine(\n line: string,\n onWarning: ParseWarningHandler,\n): TodoRecord;\nexport function parseLine(\n line: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord {\n const options = normalizeParseOptions(onWarningOrOptions);\n let rest = line;\n let completed = false;\n let priority: string | null = null;\n let completedAt: string | null = null;\n let createdAt: string | null = null;\n\n if (rest.startsWith(\"x \")) {\n completed = true;\n rest = rest.slice(2);\n\n const completedDate = takeLeadingDate(rest);\n if (completedDate.kind === \"valid\") {\n completedAt = completedDate.date;\n rest = completedDate.rest;\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n } else if (completedDate.kind === \"invalid\") {\n // The same token cannot also be a creation date, so only warn once.\n warnInvalidDate(completedDate.value, \"completedAt\", options.onWarning);\n }\n } else {\n const priorityMatch = PRIORITY_PATTERN.exec(rest);\n if (priorityMatch) {\n priority = priorityMatch[1]!;\n rest = rest.slice(priorityMatch[0]!.length);\n }\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(\n text,\n options.onWarning,\n );\n\n const record: TodoRecord = {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\n\n if (options.includeSource) {\n if (options.line !== undefined) {\n record.line = options.line;\n }\n\n record.raw = stripTrailingCarriageReturn(line);\n }\n\n return record;\n}\n\n/**\n * Parse the contents of a todo.txt file.\n *\n * Lines are split on `\\n` or `\\r\\n`; blank and whitespace-only lines are\n * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are\n * annotated with the 1-based physical line number.\n *\n * With `options.includeSource`, every record carries `raw` (the exact line,\n * minus a trailing `\\r`) and `line` (the 1-based physical line number,\n * counting blank lines).\n */\nexport function parseDocument(\n contents: string,\n options?: ParseOptions,\n): TodoRecord[];\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseDocument(\n contents: string,\n onWarning: ParseWarningHandler,\n): TodoRecord[];\nexport function parseDocument(\n contents: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord[] {\n const { includeSource, onWarning } = normalizeParseOptions(onWarningOrOptions);\n const records: TodoRecord[] = [];\n let lineNumber = 0;\n\n for (const line of contents.split(/\\r?\\n/)) {\n lineNumber += 1;\n\n if (line.trim() !== \"\") {\n records.push(\n parseLine(line, {\n includeSource,\n line: lineNumber,\n onWarning: onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n }),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecord, cloneRecords } from \"./clone.ts\";\nimport { isValidDate } from \"./date.ts\";\nimport type { TodoRecord } from \"./types.ts\";\n\n/** A predicate applied to every record in a query. */\nexport type TodoFilter = (todo: TodoRecord) => boolean;\n\n/** Loads and parses every todo.txt record. */\nexport type LoadRecords = () => Promise<TodoRecord[]>;\n\n/** Fields that {@link TodoQuery.sortBy} can order results by. */\nexport type TodoSortField =\n | \"priority\"\n | \"createdAt\"\n | \"completedAt\"\n | \"description\"\n | \"due\";\n\n/** Sort direction for {@link TodoQuery.sortBy}. Default: `\"asc\"`. */\nexport type TodoSortDirection = \"asc\" | \"desc\";\n\n/**\n * Per-call matching options.\n *\n * `caseSensitive` overrides the client-level default for one call. The default\n * differs per method: project and context matching is exact and case-sensitive\n * unless the option says otherwise, while search is case-insensitive unless the\n * option says otherwise.\n */\nexport interface TodoMatchOptions {\n /** Compare case-sensitively (or, for search, insensitively) for this call. */\n caseSensitive?: boolean;\n}\n\n/** One ordering step appended by {@link TodoQuery.sortBy}. */\nexport interface TodoSortSpec {\n field: TodoSortField;\n direction: TodoSortDirection;\n}\n\n/**\n * Pending/completed/total counts for one bucket of records.\n *\n * `total` is always `pending + completed`.\n */\nexport interface TodoCount {\n /** Records that are not completed. */\n pending: number;\n /** Records marked completed. */\n completed: number;\n /** Every record in the bucket. */\n total: number;\n}\n\n/**\n * One named bucket with its counts, from the aggregate query methods.\n *\n * The name is the project or context exactly as parsed, without the `+` or\n * `@` prefix and with its original casing.\n */\nexport interface TodoNameCount {\n /** Project or context name from the matching records. */\n name: string;\n /** Counts over the matching records that carry the name. */\n counts: TodoCount;\n}\n\n/**\n * Result of {@link TodoQuery.summary}: totals for the matching records plus\n * per-name counts.\n *\n * Per-name totals count multi-tag records once per name, so they do not sum\n * to the top-level `total` when multi-tag records or untagged records\n * exist.\n */\nexport interface TodoSummary {\n /** Every record matching the query. */\n total: number;\n /** Matching records that are not completed. */\n pending: number;\n /** Matching records that are completed. */\n completed: number;\n /** Per-project counts over the matching records. */\n projects: TodoNameCount[];\n /** Per-context counts over the matching records. */\n contexts: TodoNameCount[];\n}\n\n/** Internal query state: AND-composed filters plus one optional sort step. */\nexport interface TodoQueryState {\n filters: TodoFilter[];\n sort?: TodoSortSpec;\n /**\n * Client-level default for name matching. Search is unaffected: it stays\n * case-insensitive by default no matter what this says.\n */\n caseSensitive: boolean;\n}\n\n/**\n * A lazy query over parsed todo records.\n *\n * Filters return a new query and perform no IO. Awaiting a query resolves\n * through the supplied loader; the client caches parsed records, so only the\n * first query reads the file. Filters compose with AND: every predicate added\n * to the chain must match. Array arguments are OR within a single call, so\n * `project([\"A\", \"B\"])` matches either name while `project(\"A\").project(\"B\")`\n * requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}\n * are terminal plucks that resolve to unique, alphabetically sorted names;\n * {@link TodoQuery.summary}, {@link TodoQuery.countsByProject}, and\n * {@link TodoQuery.countsByContext} are terminal aggregates; and\n * {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.\n */\nexport interface TodoQuery extends PromiseLike<TodoRecord[]> {\n /** Only records that are not completed. */\n pending: () => TodoQuery;\n /** Only records that are completed. */\n completed: () => TodoQuery;\n /**\n * Only records tagged with the project `name`.\n *\n * An array matches any listed name (OR); repeated calls require every name\n * (AND). An empty array matches nothing. Matching is exact and\n * case-sensitive unless the client-level `caseSensitive` option or the\n * per-call override says otherwise; case-insensitive comparison uses\n * `toLowerCase()`, which is not full Unicode case folding.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records not tagged with the project `name`.\n *\n * An array excludes every listed name; an empty array excludes nothing.\n * This is not a replacement for `pending()`/`completed()`.\n */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with priority `letter`.\n *\n * Matching is exact against the uppercase letter the parser stores, so\n * `priority(\"a\")` matches nothing. An array matches any listed letter.\n */\n priority: (letter: string | string[]) => TodoQuery;\n /**\n * Only records whose description contains `text` as a substring.\n *\n * Case-insensitive by default, independently of the client-level matching\n * option. Only `description` is searched; projects, contexts, and metadata\n * have their own filters.\n */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with the metadata `key`.\n *\n * With a `value`, the record's value must match it exactly.\n */\n meta: (key: string, value?: string) => TodoQuery;\n /** Only records that have the metadata `key`, whatever its value. */\n hasMeta: (key: string) => TodoQuery;\n /**\n * Only records created strictly after `date`.\n *\n * The argument must be a real calendar date in `YYYY-MM-DD` form; anything\n * else throws a `TypeError` when the query is built, before any IO.\n * Records without a creation date never match.\n */\n createdAfter: (date: string) => TodoQuery;\n /** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /**\n * Sort the filtered records by `field`; default direction is `\"asc\"`.\n *\n * The sort is stable: records with equal keys keep file order. Missing\n * values (`null` priorities or dates, and missing or invalid `due` values)\n * sort last in both directions; `\"desc\"` reverses only the value\n * comparison, never the missing-value placement. Calling `sortBy` twice\n * keeps only the last call. Description ordering uses `localeCompare`, so\n * it follows the host locale for equal-ignoring-case ties.\n */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Unique project names in the current result, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** Unique context names in the current result, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /**\n * Aggregate counts for the records matching this query.\n *\n * `total`, `pending`, and `completed` count matching records, while\n * `projects` and `contexts` count each matching record once per distinct\n * name it carries, so a record tagged `+A +B` adds one to each name.\n * Per-name totals therefore do not sum to the top-level `total` when\n * multi-tag records or untagged records exist. Names are unique, keep\n * their original casing, and sort alphabetically like\n * {@link TodoQuery.projects}; completed-only records still contribute\n * their names. A `sortBy` step is ignored, and the summary loads through\n * the cache like every other query.\n */\n summary: () => Promise<TodoSummary>;\n /**\n * Unique project names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByProject: () => Promise<TodoNameCount[]>;\n /**\n * Unique context names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByContext: () => Promise<TodoNameCount[]>;\n /** Number of records in the current result; equal to `(await query).length`. */\n count: () => Promise<number>;\n /**\n * The first record of the filtered (and sorted) result, or `undefined`\n * when nothing matches. The record is a copy, so mutating it cannot affect\n * the client's cache.\n */\n first: () => Promise<TodoRecord | undefined>;\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Build a name-matching predicate for projects or contexts.\n *\n * Case-insensitive comparison normalizes both sides with `toLowerCase()`,\n * which is deterministic across machines and locales but not full Unicode\n * case folding. `invert` turns the predicate into a negation filter.\n */\nfunction nameFilter(\n pick: (todo: TodoRecord) => string[],\n names: string[],\n caseSensitive: boolean,\n invert: boolean,\n): TodoFilter {\n const wanted = caseSensitive\n ? names\n : names.map((name) => name.toLowerCase());\n\n const matches = (todo: TodoRecord): boolean =>\n pick(todo).some((value) =>\n wanted.includes(caseSensitive ? value : value.toLowerCase()),\n );\n\n return invert ? (todo) => !matches(todo) : matches;\n}\n\n/**\n * Validate a date-filter argument at query-build time.\n *\n * Invalid arguments throw instead of silently matching nothing, so a typo in\n * a bound cannot hide behind an empty result.\n */\nfunction requireValidDate(date: string, method: string): string {\n if (!isValidDate(date)) {\n throw new TypeError(\n `${method}() expected a real calendar date in YYYY-MM-DD form, got \"${date}\".`,\n );\n }\n\n return date;\n}\n\n/**\n * Build a date-comparison predicate on a record date field.\n *\n * Records with `null` dates never match; validated `YYYY-MM-DD` values\n * compare correctly as plain strings.\n */\nfunction dateFilter(\n field: \"createdAt\" | \"completedAt\",\n date: string,\n method: string,\n keep: (recordDate: string, bound: string) => boolean,\n): TodoFilter {\n const bound = requireValidDate(date, method);\n\n return (todo) => {\n const recordDate = todo[field];\n return recordDate !== null && keep(recordDate, bound);\n };\n}\n\n/** Read `data.due` when it is a real calendar date; otherwise `null`. */\nfunction dueDateOf(todo: TodoRecord): string | null {\n const due = todo.data[\"due\"];\n return due !== undefined && isValidDate(due) ? due : null;\n}\n\ntype NullableSortField = Exclude<TodoSortField, \"description\">;\n\n/** Extract the nullable sort key for every field except `description`. */\nfunction sortKey(todo: TodoRecord, field: NullableSortField): string | null {\n switch (field) {\n case \"priority\":\n return todo.priority;\n case \"createdAt\":\n return todo.createdAt;\n case \"completedAt\":\n return todo.completedAt;\n case \"due\":\n return dueDateOf(todo);\n }\n}\n\n/**\n * Compare nullable keys with missing values last in both directions.\n *\n * `desc` negates only the value comparison, never the missing-value\n * placement; equal keys compare as `0` so the stable sort keeps file order.\n */\nfunction compareNullableKeys(\n a: string | null,\n b: string | null,\n direction: TodoSortDirection,\n): number {\n if (a === null) {\n return b === null ? 0 : 1;\n }\n\n if (b === null) {\n return -1;\n }\n\n const result = a < b ? -1 : a > b ? 1 : 0;\n return direction === \"asc\" ? result : -result;\n}\n\n/** Build the sort comparator for one ordering step. */\nfunction makeComparator(\n spec: TodoSortSpec,\n): (a: TodoRecord, b: TodoRecord) => number {\n if (spec.field === \"description\") {\n return (a, b) => {\n const result = a.description.localeCompare(b.description);\n return spec.direction === \"asc\" ? result : -result;\n };\n }\n\n const field: NullableSortField = spec.field;\n\n return (a, b) =>\n compareNullableKeys(\n sortKey(a, field),\n sortKey(b, field),\n spec.direction,\n );\n}\n\n/**\n * Sort in place and return the same array.\n *\n * `Array#sort` is stable, so records with equal keys keep file order.\n */\nfunction applySort(records: TodoRecord[], sort: TodoSortSpec): TodoRecord[] {\n return records.sort(makeComparator(sort));\n}\n\n/**\n * Load, filter, and sort records without cloning them.\n *\n * The returned array is safe to sort because it is always a fresh copy when\n * a sort step exists; without one the loader's own array is returned as-is.\n */\nasync function resolveRaw(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (state.sort === undefined) {\n if (state.filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n }\n\n // Never sort the loader's array in place: the client's cache must keep\n // file order for later queries.\n const matches =\n state.filters.length === 0\n ? records.slice()\n : records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n\n return applySort(matches, state.sort);\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, state));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n // Sorting never applies to name plucks; they alphabetize themselves.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\n}\n\n/**\n * Count pending/completed/total per unique name over `records`.\n *\n * Each record contributes at most once per name, so a record tagged\n * `+A +A` counts `A` once. Names keep their original casing and sort\n * like the name plucks, so buckets line up with `projects()`/`contexts()`.\n */\nfunction countNames(\n records: TodoRecord[],\n pick: (todo: TodoRecord) => string[],\n): TodoNameCount[] {\n const buckets = new Map<string, TodoCount>();\n\n for (const record of records) {\n for (const name of new Set(pick(record))) {\n const bucket = buckets.get(name);\n\n if (bucket === undefined) {\n buckets.set(name, {\n pending: record.completed ? 0 : 1,\n completed: record.completed ? 1 : 0,\n total: 1,\n });\n } else if (record.completed) {\n bucket.completed += 1;\n bucket.total += 1;\n } else {\n bucket.pending += 1;\n bucket.total += 1;\n }\n }\n }\n\n return [...buckets]\n .map(([name, counts]) => ({ name, counts }))\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nfunction resolveCount(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<number> {\n return resolveRaw(load, { ...state, sort: undefined }).then(\n (records) => records.length,\n );\n}\n\n/**\n * Aggregate the current result into a summary.\n *\n * Sorting never applies to aggregates; they count records, not order them.\n */\nasync function resolveSummary(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoSummary> {\n const records = await resolveRaw(load, { ...state, sort: undefined });\n let pending = 0;\n let completed = 0;\n\n for (const record of records) {\n if (record.completed) {\n completed += 1;\n } else {\n pending += 1;\n }\n }\n\n return {\n total: records.length,\n pending,\n completed,\n projects: countNames(records, (todo) => todo.projects),\n contexts: countNames(records, (todo) => todo.contexts),\n };\n}\n\nfunction resolveCountsBy(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<TodoNameCount[]> {\n // Sorting never applies to aggregates; they count records, not order them.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n countNames(records, pick),\n );\n}\n\nasync function resolveFirst(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord | undefined> {\n const first = (await resolveRaw(load, state))[0];\n return first === undefined ? undefined : cloneRecord(first);\n}\n\n/**\n * Create a lazy query over the records loaded by `load`.\n *\n * Each filter method appends a predicate, so chained calls compose with AND,\n * while array arguments match any listed value. `sortBy` appends an ordering\n * step instead of a predicate; the last `sortBy` call wins. For example,\n * `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`, and\n * `pending().sortBy(\"priority\")` lists them A first.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n state: TodoQueryState = { filters: [], caseSensitive: true },\n): TodoQuery {\n const nameOptions = (options?: TodoMatchOptions): boolean =>\n options?.caseSensitive ?? state.caseSensitive;\n\n return {\n pending: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => !todo.completed],\n }),\n completed: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => todo.completed],\n }),\n project: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n context: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n notProject: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n notContext: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n priority: (letter) => {\n const letters = toArray(letter);\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => todo.priority !== null && letters.includes(todo.priority),\n ],\n });\n },\n search: (text, options) => {\n const caseSensitive = options?.caseSensitive ?? false;\n const needle = caseSensitive ? text : text.toLowerCase();\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => {\n const haystack = caseSensitive\n ? todo.description\n : todo.description.toLowerCase();\n return haystack.includes(needle);\n },\n ],\n });\n },\n meta: (key, value) => {\n const filter: TodoFilter =\n value === undefined\n ? (todo) => Object.hasOwn(todo.data, key)\n : (todo) => todo.data[key] === value;\n\n return createTodoQuery(load, { ...state, filters: [...state.filters, filter] });\n },\n hasMeta: (key) =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)],\n }),\n createdAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdAfter\", (a, b) => a > b),\n ],\n }),\n createdBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdBefore\", (a, b) => a < b),\n ],\n }),\n completedAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedAfter\", (a, b) => a > b),\n ],\n }),\n completedBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedBefore\", (a, b) => a < b),\n ],\n }),\n sortBy: (field, direction = \"asc\") =>\n createTodoQuery(load, { ...state, sort: { field, direction } }),\n projects: () => pluckNames(load, state, (todo) => todo.projects),\n contexts: () => pluckNames(load, state, (todo) => todo.contexts),\n summary: () => resolveSummary(load, state),\n countsByProject: () => resolveCountsBy(load, state, (todo) => todo.projects),\n countsByContext: () => resolveCountsBy(load, state, (todo) => todo.contexts),\n count: () => resolveCount(load, state),\n first: () => resolveFirst(load, state),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, state).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type {\n TodoMatchOptions,\n TodoNameCount,\n TodoQuery,\n TodoSortDirection,\n TodoSortField,\n TodoSummary,\n} from \"./query.ts\";\nimport type {\n TodoClientOptions,\n TodoLogger,\n TodoRecord,\n} from \"./types.ts\";\n\n/** The read interface returned by {@link createTodoTxt}. */\nexport interface TodoTxtClient {\n /** Read fresh todo.txt contents, replace the cache, and return every record. */\n all: () => Promise<TodoRecord[]>;\n /** Query only records that are not completed, using the cached snapshot. */\n pending: () => TodoQuery;\n /** Query only records that are completed, using the cached snapshot. */\n completed: () => TodoQuery;\n /**\n * Query records tagged with the project `name`, using the cache.\n *\n * An array matches any listed name; see {@link TodoQuery.project}.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the priority `letter`; see {@link TodoQuery.priority}. */\n priority: (letter: string | string[]) => TodoQuery;\n /** Query records whose description contains `text`; see {@link TodoQuery.search}. */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the metadata `key`; see {@link TodoQuery.meta}. */\n meta: (key: string, value?: string) => TodoQuery;\n /** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */\n hasMeta: (key: string) => TodoQuery;\n /** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */\n createdAfter: (date: string) => TodoQuery;\n /** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Count records in the cached snapshot; see {@link TodoQuery.count}. */\n count: () => Promise<number>;\n /** First record of the cached snapshot; see {@link TodoQuery.first}. */\n first: () => Promise<TodoRecord | undefined>;\n /** List unique project names from the cached snapshot, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** List unique context names from the cached snapshot, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /** Aggregate counts for the cached snapshot; see {@link TodoQuery.summary}. */\n summary: () => Promise<TodoSummary>;\n /** Per-project counts for the cached snapshot; see {@link TodoQuery.countsByProject}. */\n countsByProject: () => Promise<TodoNameCount[]>;\n /** Per-context counts for the cached snapshot; see {@link TodoQuery.countsByContext}. */\n countsByContext: () => Promise<TodoNameCount[]>;\n}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `options.read` is responsible for\n * producing the file contents and `options.write` will be used by the write\n * APIs once they are implemented. `options.logger` is optional and silent by\n * default; when supplied, it receives read lifecycle and parse warning\n * diagnostics. With `options.includeSource`, every record also carries the\n * 1-based `line` number and the exact `raw` line it was parsed from. With\n * `options.caseSensitive: false`, project and context matching compares\n * names through `toLowerCase()`; the default is exact matching.\n *\n * Parsed records are cached in memory per client. The first query loads and\n * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}\n * always reads fresh contents and replaces the cache, so it can be used to\n * refresh after the underlying file changes.\n *\n * Every line is parsed into a {@link TodoRecord} when the cache is populated.\n * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}\n * operate on that array of JSON records, plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names, and\n * aggregates such as {@link TodoQuery.summary} count pending and completed\n * records per name. Returned records are copies, so callers may mutate them\n * without affecting the cache.\n */\nexport function createTodoTxt(options: TodoClientOptions): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = options.logger;\n\n const log: TodoLogger = (level, message, meta) => {\n if (!logger) {\n return;\n }\n\n try {\n const result = logger(level, message, meta);\n\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n void Promise.resolve(result).catch(() => {});\n }\n } catch {\n // Logging is best-effort and must never break reads or queries.\n }\n };\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n\n log(\"debug\", \"Reading todo file\");\n const contents = await options.read();\n const records = parseDocument(contents, {\n includeSource: options.includeSource,\n onWarning: (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\n });\n },\n });\n log(\"debug\", \"Parsed todo file\", { records: records.length });\n\n if (currentGeneration === generation) {\n cache = records;\n }\n\n return records;\n };\n\n const refresh = (): Promise<TodoRecord[]> => {\n const promise = readFresh();\n inFlight = promise;\n\n void promise\n .finally(() => {\n if (inFlight === promise) {\n inFlight = undefined;\n }\n })\n .catch(() => {});\n\n return promise;\n };\n\n const loadCached = (): Promise<TodoRecord[]> => {\n if (inFlight) {\n return inFlight;\n }\n\n if (cache) {\n return Promise.resolve(cache);\n }\n\n return refresh();\n };\n\n const all = async (): Promise<TodoRecord[]> =>\n cloneRecords(await refresh());\n\n const query = createTodoQuery(loadCached, {\n filters: [],\n caseSensitive: options.caseSensitive ?? true,\n });\n\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n notProject: query.notProject,\n notContext: query.notContext,\n priority: query.priority,\n search: query.search,\n meta: query.meta,\n hasMeta: query.hasMeta,\n createdAfter: query.createdAfter,\n createdBefore: query.createdBefore,\n completedAfter: query.completedAfter,\n completedBefore: query.completedBefore,\n sortBy: query.sortBy,\n count: query.count,\n first: query.first,\n projects: query.projects,\n contexts: query.contexts,\n summary: query.summary,\n countsByProject: query.countsByProject,\n countsByContext: query.countsByContext,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,MAAM,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