@jibone/todotxt-core 0.2.0 → 0.3.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 +50 -19
- package/dist/index.d.ts +20 -3
- package/dist/index.js +84 -9
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -55,25 +55,30 @@ const todos = createTodoTxt({
|
|
|
55
55
|
|
|
56
56
|
`write` is optional until the write APIs are implemented, so read-only clients
|
|
57
57
|
can omit it. `logger` is optional too and silent when omitted; see
|
|
58
|
-
[Logging](#logging).
|
|
58
|
+
[Logging](#logging). The runnable Node version is
|
|
59
|
+
[`examples/node/todo-all.ts`](https://github.com/jibone/todotxt-core/blob/master/examples/node/todo-all.ts).
|
|
59
60
|
|
|
60
61
|
`all()` returns a `TodoRecord` for each non-empty line:
|
|
61
62
|
|
|
62
|
-
| Field | Description
|
|
63
|
-
| ------------- |
|
|
64
|
-
| `completed` | `true` when the line starts with `x `
|
|
65
|
-
| `priority` | Uppercase letter from `(A)`–`(Z)`, or `null`
|
|
66
|
-
| `completedAt` | `YYYY-MM-DD` completion date, or `null`
|
|
67
|
-
| `createdAt` | `YYYY-MM-DD` creation date, or `null`
|
|
68
|
-
| `description` | Task text with projects, contexts, and `key:value` tags removed
|
|
69
|
-
| `projects` | Projects without the `+` prefix
|
|
70
|
-
| `contexts` | Contexts without the `@` prefix
|
|
71
|
-
| `data` | `key:value` metadata (`{ due: "2011-03-05" }`)
|
|
63
|
+
| Field | Description |
|
|
64
|
+
| ------------- | ------------------------------------------------------------------- |
|
|
65
|
+
| `completed` | `true` when the line starts with `x ` |
|
|
66
|
+
| `priority` | Uppercase letter from `(A)`–`(Z)`, or `null` |
|
|
67
|
+
| `completedAt` | `YYYY-MM-DD` completion date that exists on the calendar, or `null` |
|
|
68
|
+
| `createdAt` | `YYYY-MM-DD` creation date that exists on the calendar, or `null` |
|
|
69
|
+
| `description` | Task text with projects, contexts, and `key:value` tags removed |
|
|
70
|
+
| `projects` | Projects without the `+` prefix |
|
|
71
|
+
| `contexts` | Contexts without the `@` prefix |
|
|
72
|
+
| `data` | `key:value` metadata (`{ due: "2011-03-05" }`) |
|
|
72
73
|
|
|
73
74
|
If a `key:value` key appears more than once, the last value wins. With a
|
|
74
75
|
[logger](#logging) configured, the parser also emits a `warn` for each duplicate
|
|
75
76
|
key.
|
|
76
77
|
|
|
78
|
+
See [How todotxt-core parses todo.txt](https://github.com/jibone/todotxt-core/blob/master/docs/todo-txt-rules.md)
|
|
79
|
+
for the complete rule-by-rule interpretation, including date validation and
|
|
80
|
+
deliberate leniencies.
|
|
81
|
+
|
|
77
82
|
## Querying
|
|
78
83
|
|
|
79
84
|
Queries are lazy: chaining filters does no IO. The first query on a client reads
|
|
@@ -200,11 +205,13 @@ Currently the client emits:
|
|
|
200
205
|
|
|
201
206
|
- `debug` when a read starts and when it finishes, with `{ records }`.
|
|
202
207
|
- `warn` for each duplicate `key:value` key; the last value still wins.
|
|
208
|
+
- `warn` for each leading date that is not a real calendar date; the value stays
|
|
209
|
+
in the description.
|
|
203
210
|
|
|
204
211
|
Cached queries do not log. Read failures stay promise rejections and are not
|
|
205
212
|
logged as `error`; the other levels are reserved for the write APIs. Logging is
|
|
206
213
|
best-effort: a logger that throws or rejects never breaks a read or query. See
|
|
207
|
-
`
|
|
214
|
+
`examples/todo-logger.ts`.
|
|
208
215
|
|
|
209
216
|
## Parser
|
|
210
217
|
|
|
@@ -218,21 +225,45 @@ const records = parseDocument(contents);
|
|
|
218
225
|
```
|
|
219
226
|
|
|
220
227
|
`parseLine` returns a `TodoRecord` directly. The original raw line is not
|
|
221
|
-
retained.
|
|
228
|
+
retained. Dates must be real calendar dates in `YYYY-MM-DD` form; a shape-valid
|
|
229
|
+
but nonexistent date such as `2011-99-99` is treated as text and reported as an
|
|
230
|
+
`invalid-date` warning. The full rule-by-rule interpretation is documented in
|
|
231
|
+
[How todotxt-core parses todo.txt](https://github.com/jibone/todotxt-core/blob/master/docs/todo-txt-rules.md).
|
|
222
232
|
|
|
223
233
|
Writing is not implemented yet. The `write` hook is optional for now and will
|
|
224
234
|
become required for the write APIs when they land.
|
|
225
235
|
|
|
226
|
-
##
|
|
236
|
+
## Examples
|
|
237
|
+
|
|
238
|
+
```sh
|
|
239
|
+
bun examples/todo-all.ts
|
|
240
|
+
bun examples/todo-project.ts
|
|
241
|
+
bun examples/todo-context.ts
|
|
242
|
+
bun examples/todo-cross.ts
|
|
243
|
+
bun examples/todo-logger.ts
|
|
244
|
+
bun examples/todo-try.ts
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Each format rule also has a runnable example:
|
|
227
248
|
|
|
228
249
|
```sh
|
|
229
|
-
bun
|
|
230
|
-
bun
|
|
231
|
-
bun
|
|
232
|
-
bun
|
|
233
|
-
bun
|
|
250
|
+
bun examples/rules/rule-1-priority.ts
|
|
251
|
+
bun examples/rules/rule-2-creation-date.ts
|
|
252
|
+
bun examples/rules/rule-3-projects-contexts.ts
|
|
253
|
+
bun examples/rules/rule-4-completed.ts
|
|
254
|
+
bun examples/rules/rule-5-metadata.ts
|
|
234
255
|
```
|
|
235
256
|
|
|
257
|
+
Node.js examples show the same API with `node:fs/promises` hooks:
|
|
258
|
+
|
|
259
|
+
```sh
|
|
260
|
+
node examples/node/todo-all.ts
|
|
261
|
+
node examples/node/todo-logger.ts
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
These require Node 22.18+ for native TypeScript type stripping; the library
|
|
265
|
+
itself still runs on Node 20+.
|
|
266
|
+
|
|
236
267
|
## Development
|
|
237
268
|
|
|
238
269
|
```sh
|
package/dist/index.d.ts
CHANGED
|
@@ -20,10 +20,15 @@ type TodoLogger = (level: LogLevel, message: string, meta?: Record<string, unkno
|
|
|
20
20
|
* A non-fatal issue found while parsing.
|
|
21
21
|
*
|
|
22
22
|
* Warnings describe recoverable conditions; the parser still returns a record.
|
|
23
|
+
*
|
|
24
|
+
* - `duplicate-metadata-key`: a `key:value` key appears more than once; the
|
|
25
|
+
* last value wins.
|
|
26
|
+
* - `invalid-date`: a leading `YYYY-MM-DD` value is not a real calendar date.
|
|
27
|
+
* The value is not used as a date and remains part of the description.
|
|
23
28
|
*/
|
|
24
29
|
interface ParseWarning {
|
|
25
30
|
/** Stable identifier for programmatic handling. */
|
|
26
|
-
code: "duplicate-metadata-key";
|
|
31
|
+
code: "duplicate-metadata-key" | "invalid-date";
|
|
27
32
|
/** Human-readable description of the issue. */
|
|
28
33
|
message: string;
|
|
29
34
|
/** 1-based physical line number, when called through {@link parseDocument}. */
|
|
@@ -63,9 +68,19 @@ interface TodoRecord {
|
|
|
63
68
|
completed: boolean;
|
|
64
69
|
/** Uppercase priority letter, e.g. `"A"` for `(A)`, or `null`. */
|
|
65
70
|
priority: string | null;
|
|
66
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* Completion date in `YYYY-MM-DD` form, or `null`.
|
|
73
|
+
*
|
|
74
|
+
* The value is always a real calendar date. A shape-valid but nonexistent
|
|
75
|
+
* date (such as `2011-99-99`) is left in the description instead.
|
|
76
|
+
*/
|
|
67
77
|
completedAt: string | null;
|
|
68
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* Creation date in `YYYY-MM-DD` form, or `null`.
|
|
80
|
+
*
|
|
81
|
+
* The value is always a real calendar date. A shape-valid but nonexistent
|
|
82
|
+
* date (such as `2011-99-99`) is left in the description instead.
|
|
83
|
+
*/
|
|
69
84
|
createdAt: string | null;
|
|
70
85
|
/** Task text with projects, contexts, and `key:value` metadata removed. */
|
|
71
86
|
description: string;
|
|
@@ -150,6 +165,8 @@ export declare function createTodoTxt(hooks: TodoHooks): TodoTxtClient;
|
|
|
150
165
|
* and then a creation date.
|
|
151
166
|
* - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
|
|
152
167
|
* creation date.
|
|
168
|
+
* - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but
|
|
169
|
+
* nonexistent date is treated as text.
|
|
153
170
|
* - Projects, contexts, and `key:value` metadata may appear anywhere in the
|
|
154
171
|
* remaining text.
|
|
155
172
|
*
|
package/dist/index.js
CHANGED
|
@@ -16,6 +16,41 @@ function cloneRecord(todo) {
|
|
|
16
16
|
function cloneRecords(records) {
|
|
17
17
|
return records.map(cloneRecord);
|
|
18
18
|
}
|
|
19
|
+
// src/date.ts
|
|
20
|
+
const DATE_SHAPE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
21
|
+
const DAYS_IN_MONTH = [
|
|
22
|
+
31,
|
|
23
|
+
28,
|
|
24
|
+
31,
|
|
25
|
+
30,
|
|
26
|
+
31,
|
|
27
|
+
30,
|
|
28
|
+
31,
|
|
29
|
+
31,
|
|
30
|
+
30,
|
|
31
|
+
31,
|
|
32
|
+
30,
|
|
33
|
+
31
|
|
34
|
+
];
|
|
35
|
+
function isLeapYear(year) {
|
|
36
|
+
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* True when `value` is a real calendar date in `YYYY-MM-DD` form.
|
|
40
|
+
*
|
|
41
|
+
* The check is purely arithmetic so it does not depend on the host timezone and
|
|
42
|
+
* does not let JavaScript's `Date` roll invalid values over (for example,
|
|
43
|
+
* `2011-02-30` must not become March 2).
|
|
44
|
+
*/
|
|
45
|
+
function isValidDate(value) {
|
|
46
|
+
const match = DATE_SHAPE_PATTERN.exec(value);
|
|
47
|
+
if (!match) return false;
|
|
48
|
+
const year = Number(match[1]);
|
|
49
|
+
const month = Number(match[2]);
|
|
50
|
+
const day = Number(match[3]);
|
|
51
|
+
if (month < 1 || month > 12 || day < 1) return false;
|
|
52
|
+
return day <= (month === 2 && isLeapYear(year) ? 29 : DAYS_IN_MONTH[month - 1] ?? 0);
|
|
53
|
+
}
|
|
19
54
|
// src/metadata.ts
|
|
20
55
|
const EXTENSION_PATTERN = /^([^:\s]+):([^:\s]+)$/;
|
|
21
56
|
function tokenize(text) {
|
|
@@ -75,17 +110,43 @@ function parseText(text, onWarning) {
|
|
|
75
110
|
const PRIORITY_PATTERN = /^\(([A-Z])\) /;
|
|
76
111
|
const LEADING_DATE_PATTERN = /^(\d{4}-\d{2}-\d{2})(?: |$)/;
|
|
77
112
|
/**
|
|
78
|
-
*
|
|
113
|
+
* Inspect a `YYYY-MM-DD` token at the start of `input`.
|
|
79
114
|
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
115
|
+
* A value with the right shape that does not exist on the calendar is reported
|
|
116
|
+
* as `invalid`. In that case `rest` is the original input, so callers leave the
|
|
117
|
+
* token in the description instead of consuming it.
|
|
82
118
|
*/
|
|
83
119
|
function takeLeadingDate(input) {
|
|
84
120
|
const match = LEADING_DATE_PATTERN.exec(input);
|
|
85
|
-
if (!match) return
|
|
121
|
+
if (!match) return {
|
|
122
|
+
kind: "absent",
|
|
123
|
+
rest: input
|
|
124
|
+
};
|
|
86
125
|
const date = match[1];
|
|
87
|
-
if (date === void 0) return
|
|
88
|
-
|
|
126
|
+
if (date === void 0) return {
|
|
127
|
+
kind: "absent",
|
|
128
|
+
rest: input
|
|
129
|
+
};
|
|
130
|
+
if (!isValidDate(date)) return {
|
|
131
|
+
kind: "invalid",
|
|
132
|
+
value: date,
|
|
133
|
+
rest: input
|
|
134
|
+
};
|
|
135
|
+
return {
|
|
136
|
+
kind: "valid",
|
|
137
|
+
date,
|
|
138
|
+
rest: input.slice(match[0].length)
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function warnInvalidDate(value, field, onWarning) {
|
|
142
|
+
onWarning?.({
|
|
143
|
+
code: "invalid-date",
|
|
144
|
+
message: `Invalid ${field === "completedAt" ? "completion" : "creation"} date "${value}"; treating it as text.`,
|
|
145
|
+
meta: {
|
|
146
|
+
value,
|
|
147
|
+
field
|
|
148
|
+
}
|
|
149
|
+
});
|
|
89
150
|
}
|
|
90
151
|
/**
|
|
91
152
|
* Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
|
|
@@ -96,6 +157,8 @@ function takeLeadingDate(input) {
|
|
|
96
157
|
* and then a creation date.
|
|
97
158
|
* - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
|
|
98
159
|
* creation date.
|
|
160
|
+
* - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but
|
|
161
|
+
* nonexistent date is treated as text.
|
|
99
162
|
* - Projects, contexts, and `key:value` metadata may appear anywhere in the
|
|
100
163
|
* remaining text.
|
|
101
164
|
*
|
|
@@ -111,15 +174,27 @@ function parseLine(line, onWarning) {
|
|
|
111
174
|
if (rest.startsWith("x ")) {
|
|
112
175
|
completed = true;
|
|
113
176
|
rest = rest.slice(2);
|
|
114
|
-
|
|
115
|
-
|
|
177
|
+
const completedDate = takeLeadingDate(rest);
|
|
178
|
+
if (completedDate.kind === "valid") {
|
|
179
|
+
completedAt = completedDate.date;
|
|
180
|
+
rest = completedDate.rest;
|
|
181
|
+
const createdDate = takeLeadingDate(rest);
|
|
182
|
+
if (createdDate.kind === "valid") {
|
|
183
|
+
createdAt = createdDate.date;
|
|
184
|
+
rest = createdDate.rest;
|
|
185
|
+
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", onWarning);
|
|
186
|
+
} else if (completedDate.kind === "invalid") warnInvalidDate(completedDate.value, "completedAt", onWarning);
|
|
116
187
|
} else {
|
|
117
188
|
const priorityMatch = PRIORITY_PATTERN.exec(rest);
|
|
118
189
|
if (priorityMatch) {
|
|
119
190
|
priority = priorityMatch[1];
|
|
120
191
|
rest = rest.slice(priorityMatch[0].length);
|
|
121
192
|
}
|
|
122
|
-
|
|
193
|
+
const createdDate = takeLeadingDate(rest);
|
|
194
|
+
if (createdDate.kind === "valid") {
|
|
195
|
+
createdAt = createdDate.date;
|
|
196
|
+
rest = createdDate.rest;
|
|
197
|
+
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", onWarning);
|
|
123
198
|
}
|
|
124
199
|
const { description, projects, contexts, data } = parseText(rest.trim(), onWarning);
|
|
125
200
|
return {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.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 return {\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\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\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 { parseText } from \"./metadata.ts\";\nimport type { ParseWarningHandler, TodoRecord } from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\n/**\n * Consume a `YYYY-MM-DD` date from the start of `input`.\n *\n * Only the shape is validated; the date does not have to exist on a calendar\n * (matching the literal format rules).\n */\nfunction takeLeadingDate(input: string): [date: string | null, rest: string] {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return [null, input];\n }\n\n const date = match[1];\n if (date === undefined) {\n return [null, input];\n }\n\n return [date, input.slice(match[0]!.length)];\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 * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `onWarning` when supplied; parsing still\n * produces a record.\n */\nexport function parseLine(\n line: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord {\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 [completedAt, rest] = takeLeadingDate(rest);\n [createdAt, rest] = takeLeadingDate(rest);\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 [createdAt, rest] = takeLeadingDate(rest);\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(text, onWarning);\n\n return {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\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 */\nexport function parseDocument(\n contents: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord[] {\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(\n line,\n onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n ),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecords } from \"./clone.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/**\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. {@link TodoQuery.projects} and\n * {@link TodoQuery.contexts} are terminal plucks that resolve to unique,\n * alphabetically sorted names.\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 /** Only records tagged with the project `name`. */\n project: (name: string) => TodoQuery;\n /** Only records tagged with the context `name`. */\n context: (name: string) => 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\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nasync function resolveRaw(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n filters.every((filter) => filter(record)),\n );\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, filters));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n filters: TodoFilter[],\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n return resolveRaw(load, filters).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\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. For\n * example, `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n filters: TodoFilter[] = [],\n): TodoQuery {\n return {\n pending: () =>\n createTodoQuery(load, [...filters, (todo) => !todo.completed]),\n completed: () =>\n createTodoQuery(load, [...filters, (todo) => todo.completed]),\n project: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.projects.includes(name),\n ]),\n context: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.contexts.includes(name),\n ]),\n projects: () => pluckNames(load, filters, (todo) => todo.projects),\n contexts: () => pluckNames(load, filters, (todo) => todo.contexts),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, filters).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type { TodoQuery } from \"./query.ts\";\nimport type { TodoHooks, TodoLogger, TodoRecord } 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 /** Query records tagged with a single project name, using the cache. */\n project: (name: string) => TodoQuery;\n /** Query records tagged with a single context name, using the cache. */\n context: (name: string) => TodoQuery;\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: `hooks.read` is responsible for\n * producing the file contents and `hooks.write` will be used by the write APIs\n * once they are implemented. `hooks.logger` is optional and silent by default;\n * when supplied, it receives read lifecycle and parse warning diagnostics.\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(hooks: TodoHooks): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = hooks.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 hooks.read();\n const records = parseDocument(contents, (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\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\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n projects: query.projects,\n contexts: query.contexts,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,OAAO;EACL,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,UAAU,CAAC,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Aa,QAAQ,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC;EAE/C,QAAQ,CAER;CACF;CAEA,MAAM,YAAY,YAAmC;EACnD,MAAM,oBAAoB,EAAE;EAE5B,IAAI,SAAS,mBAAmB;EAEhC,MAAM,UAAU,cAAc,MADP,MAAM,KAAK,IACO,YAAY;GACnD,IAAI,QAAQ,QAAQ,SAAS;IAC3B,GAAG,QAAQ;IACX,MAAM,QAAQ;IACd,MAAM,QAAQ;GAChB,CAAC;EACH,CAAC;EACD,IAAI,SAAS,oBAAoB,EAAE,SAAS,QAAQ,OAAO,CAAC;EAE5D,IAAI,sBAAsB,YACxB,QAAQ;EAGV,OAAO;CACT;CAEA,MAAM,gBAAuC;EAC3C,MAAM,UAAU,UAAU;EAC1B,WAAW;EAEX,QACG,cAAc;GACb,IAAI,aAAa,SACf,WAAW,KAAA;EAEf,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EAEjB,OAAO;CACT;CAEA,MAAM,mBAA0C;EAC9C,IAAI,UACF,OAAO;EAGT,IAAI,OACF,OAAO,QAAQ,QAAQ,KAAK;EAG9B,OAAO,QAAQ;CACjB;CAEA,MAAM,MAAM,YACV,aAAa,MAAM,QAAQ,CAAC;CAE9B,MAAM,QAAQ,gBAAgB,UAAU;CAExC,OAAO;EACL;EACA,SAAS,MAAM;EACf,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,SAAS,MAAM;EACf,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 return {\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\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 { ParseWarningHandler, TodoRecord } 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 * 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 `onWarning` when supplied; parsing still\n * produces a record.\n */\nexport function parseLine(\n line: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord {\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\", 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\", 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\", onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(text, onWarning);\n\n return {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\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 */\nexport function parseDocument(\n contents: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord[] {\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(\n line,\n onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n ),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecords } from \"./clone.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/**\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. {@link TodoQuery.projects} and\n * {@link TodoQuery.contexts} are terminal plucks that resolve to unique,\n * alphabetically sorted names.\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 /** Only records tagged with the project `name`. */\n project: (name: string) => TodoQuery;\n /** Only records tagged with the context `name`. */\n context: (name: string) => 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\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nasync function resolveRaw(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n filters.every((filter) => filter(record)),\n );\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, filters));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n filters: TodoFilter[],\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n return resolveRaw(load, filters).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\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. For\n * example, `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n filters: TodoFilter[] = [],\n): TodoQuery {\n return {\n pending: () =>\n createTodoQuery(load, [...filters, (todo) => !todo.completed]),\n completed: () =>\n createTodoQuery(load, [...filters, (todo) => todo.completed]),\n project: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.projects.includes(name),\n ]),\n context: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.contexts.includes(name),\n ]),\n projects: () => pluckNames(load, filters, (todo) => todo.projects),\n contexts: () => pluckNames(load, filters, (todo) => todo.contexts),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, filters).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type { TodoQuery } from \"./query.ts\";\nimport type { TodoHooks, TodoLogger, TodoRecord } 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 /** Query records tagged with a single project name, using the cache. */\n project: (name: string) => TodoQuery;\n /** Query records tagged with a single context name, using the cache. */\n context: (name: string) => TodoQuery;\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: `hooks.read` is responsible for\n * producing the file contents and `hooks.write` will be used by the write APIs\n * once they are implemented. `hooks.logger` is optional and silent by default;\n * when supplied, it receives read lifecycle and parse warning diagnostics.\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(hooks: TodoHooks): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = hooks.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 hooks.read();\n const records = parseDocument(contents, (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\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\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n projects: query.projects,\n contexts: query.contexts,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,OAAO;EACL,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;AACF;;AAGA,SAAgB,aAAa,SAA8C;CACzE,OAAO,QAAQ,IAAI,WAAW;AAChC;;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