@jibone/todotxt-core 0.1.1 → 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 CHANGED
@@ -54,20 +54,30 @@ const todos = createTodoTxt({
54
54
  ```
55
55
 
56
56
  `write` is optional until the write APIs are implemented, so read-only clients
57
- can omit it.
57
+ can omit it. `logger` is optional too and silent when omitted; see
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).
58
60
 
59
61
  `all()` returns a `TodoRecord` for each non-empty line:
60
62
 
61
- | Field | Description |
62
- | ------------- | --------------------------------------------------------------- |
63
- | `completed` | `true` when the line starts with `x ` |
64
- | `priority` | Uppercase letter from `(A)`–`(Z)`, or `null` |
65
- | `completedAt` | `YYYY-MM-DD` completion date, or `null` |
66
- | `createdAt` | `YYYY-MM-DD` creation date, or `null` |
67
- | `description` | Task text with projects, contexts, and `key:value` tags removed |
68
- | `projects` | Projects without the `+` prefix |
69
- | `contexts` | Contexts without the `@` prefix |
70
- | `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" }`) |
73
+
74
+ If a `key:value` key appears more than once, the last value wins. With a
75
+ [logger](#logging) configured, the parser also emits a `warn` for each duplicate
76
+ key.
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.
71
81
 
72
82
  ## Querying
73
83
 
@@ -165,6 +175,44 @@ Filters are applied in sequence:
165
175
  completed record. A project with both pending and completed items appears in
166
176
  both `pending().projects()` and `completed().projects()`.
167
177
 
178
+ ## Logging
179
+
180
+ `createTodoTxt` is silent by default. Pass a `logger` to receive diagnostics.
181
+ It is called as `logger(level, message, meta?)`, where `level` is `"debug"`,
182
+ `"info"`, `"warn"`, or `"error"`. Bring your own implementation:
183
+
184
+ ```ts
185
+ import { createTodoTxt } from "@jibone/todotxt-core";
186
+ import type { TodoLogger } from "@jibone/todotxt-core";
187
+
188
+ const logger: TodoLogger = (level, message, meta) => {
189
+ const line = `[todotxt:${level}] ${message}`;
190
+
191
+ if (meta) {
192
+ console.log(line, meta);
193
+ } else {
194
+ console.log(line);
195
+ }
196
+ };
197
+
198
+ const todos = createTodoTxt({
199
+ read: () => Bun.file("todo.txt").text(),
200
+ logger,
201
+ });
202
+ ```
203
+
204
+ Currently the client emits:
205
+
206
+ - `debug` when a read starts and when it finishes, with `{ records }`.
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.
210
+
211
+ Cached queries do not log. Read failures stay promise rejections and are not
212
+ logged as `error`; the other levels are reserved for the write APIs. Logging is
213
+ best-effort: a logger that throws or rejects never breaks a read or query. See
214
+ `examples/todo-logger.ts`.
215
+
168
216
  ## Parser
169
217
 
170
218
  The parser also works without the client wrapper:
@@ -177,20 +225,45 @@ const records = parseDocument(contents);
177
225
  ```
178
226
 
179
227
  `parseLine` returns a `TodoRecord` directly. The original raw line is not
180
- 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).
181
232
 
182
233
  Writing is not implemented yet. The `write` hook is optional for now and will
183
234
  become required for the write APIs when they land.
184
235
 
185
- ## Example
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:
248
+
249
+ ```sh
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
255
+ ```
256
+
257
+ Node.js examples show the same API with `node:fs/promises` hooks:
186
258
 
187
259
  ```sh
188
- bun example/todo-all.ts
189
- bun example/todo-project.ts
190
- bun example/todo-context.ts
191
- bun example/todo-cross.ts
260
+ node examples/node/todo-all.ts
261
+ node examples/node/todo-logger.ts
192
262
  ```
193
263
 
264
+ These require Node 22.18+ for native TypeScript type stripping; the library
265
+ itself still runs on Node 20+.
266
+
194
267
  ## Development
195
268
 
196
269
  ```sh
package/dist/index.d.ts CHANGED
@@ -5,19 +5,57 @@
5
5
  * implementations.
6
6
  */
7
7
  type MaybePromise<T> = T | Promise<T>;
8
+ /** Severity passed to a consumer-supplied logger. */
9
+ type LogLevel = "debug" | "info" | "warn" | "error";
8
10
  /**
9
- * File access callbacks supplied by the consumer.
11
+ * Consumer-supplied logger.
12
+ *
13
+ * The library is silent by default. When a logger is provided, it receives a
14
+ * level, a human-readable message, and optional structured context. Logging is
15
+ * best-effort: implementations may throw or return a promise, and neither will
16
+ * affect reads or queries.
17
+ */
18
+ type TodoLogger = (level: LogLevel, message: string, meta?: Record<string, unknown>) => MaybePromise<unknown>;
19
+ /**
20
+ * A non-fatal issue found while parsing.
21
+ *
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.
28
+ */
29
+ interface ParseWarning {
30
+ /** Stable identifier for programmatic handling. */
31
+ code: "duplicate-metadata-key" | "invalid-date";
32
+ /** Human-readable description of the issue. */
33
+ message: string;
34
+ /** 1-based physical line number, when called through {@link parseDocument}. */
35
+ line?: number;
36
+ /** Structured details such as the offending key and values. */
37
+ meta: Record<string, unknown>;
38
+ }
39
+ /** Receives parse warnings. */
40
+ type ParseWarningHandler = (warning: ParseWarning) => void;
41
+ /**
42
+ * Callbacks supplied by the consumer.
10
43
  *
11
44
  * The library itself never touches the filesystem. `read` is used by
12
45
  * {@link createTodoTxt}. `write` is optional until the write APIs land; when
13
46
  * they do, callers that mutate todos will need to provide it. The write hook's
14
47
  * return value is ignored, so it may return anything (for example
15
48
  * `Bun.write`'s `Promise<number>`).
49
+ *
50
+ * `logger` is an optional bring-your-own logger. It is silent when omitted.
16
51
  */
17
- interface TodoFileHooks {
52
+ interface TodoHooks {
18
53
  read: () => MaybePromise<string>;
19
54
  write?: (contents: string) => MaybePromise<unknown>;
55
+ logger?: TodoLogger;
20
56
  }
57
+ /** @deprecated Use {@link TodoHooks}. */
58
+ type TodoFileHooks = TodoHooks;
21
59
  /**
22
60
  * A single todo.txt line parsed into a JSON-friendly record.
23
61
  *
@@ -30,9 +68,19 @@ interface TodoRecord {
30
68
  completed: boolean;
31
69
  /** Uppercase priority letter, e.g. `"A"` for `(A)`, or `null`. */
32
70
  priority: string | null;
33
- /** Completion date in `YYYY-MM-DD` form, or `null`. */
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
+ */
34
77
  completedAt: string | null;
35
- /** Creation date in `YYYY-MM-DD` form, or `null`. */
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
+ */
36
84
  createdAt: string | null;
37
85
  /** Task text with projects, contexts, and `key:value` metadata removed. */
38
86
  description: string;
@@ -92,7 +140,8 @@ interface TodoTxtClient {
92
140
  *
93
141
  * The library performs no IO of its own: `hooks.read` is responsible for
94
142
  * producing the file contents and `hooks.write` will be used by the write APIs
95
- * once they are implemented.
143
+ * once they are implemented. `hooks.logger` is optional and silent by default;
144
+ * when supplied, it receives read lifecycle and parse warning diagnostics.
96
145
  *
97
146
  * Parsed records are cached in memory per client. The first query loads and
98
147
  * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
@@ -106,7 +155,7 @@ interface TodoTxtClient {
106
155
  * Returned records are copies, so callers may mutate them without affecting the
107
156
  * cache.
108
157
  */
109
- export declare function createTodoTxt(hooks: TodoFileHooks): TodoTxtClient;
158
+ export declare function createTodoTxt(hooks: TodoHooks): TodoTxtClient;
110
159
  /**
111
160
  * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
112
161
  *
@@ -116,15 +165,21 @@ export declare function createTodoTxt(hooks: TodoFileHooks): TodoTxtClient;
116
165
  * and then a creation date.
117
166
  * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
118
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.
119
170
  * - Projects, contexts, and `key:value` metadata may appear anywhere in the
120
171
  * remaining text.
172
+ *
173
+ * Recoverable issues are reported to `onWarning` when supplied; parsing still
174
+ * produces a record.
121
175
  */
122
- export declare function parseLine(line: string): TodoRecord;
176
+ export declare function parseLine(line: string, onWarning?: ParseWarningHandler): TodoRecord;
123
177
  /**
124
178
  * Parse the contents of a todo.txt file.
125
179
  *
126
180
  * Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
127
- * skipped. Every remaining line becomes a {@link TodoRecord}.
181
+ * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are
182
+ * annotated with the 1-based physical line number.
128
183
  */
129
- export declare function parseDocument(contents: string): TodoRecord[];
130
- export type { MaybePromise, TodoFileHooks, TodoQuery, TodoRecord, TodoTxtClient };
184
+ export declare function parseDocument(contents: string, onWarning?: ParseWarningHandler): TodoRecord[];
185
+ export type { LogLevel, MaybePromise, ParseWarning, ParseWarningHandler, TodoFileHooks, TodoHooks, TodoLogger, TodoQuery, TodoRecord, TodoTxtClient };
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) {
@@ -28,8 +63,11 @@ function tokenize(text) {
28
63
  *
29
64
  * Previous versions tokenized the text once for metadata and again to strip it;
30
65
  * doing both here keeps parsing to a single split per line.
66
+ *
67
+ * When a `key:value` key is repeated, `onWarning` receives a
68
+ * `duplicate-metadata-key` warning and the last value wins.
31
69
  */
32
- function parseText(text) {
70
+ function parseText(text, onWarning) {
33
71
  const projects = [];
34
72
  const contexts = [];
35
73
  const data = {};
@@ -47,6 +85,15 @@ function parseText(text) {
47
85
  const key = extension?.[1];
48
86
  const value = extension?.[2];
49
87
  if (key !== void 0 && value !== void 0) {
88
+ if (Object.hasOwn(data, key)) onWarning?.({
89
+ code: "duplicate-metadata-key",
90
+ message: `Duplicate metadata key "${key}"; the last value wins.`,
91
+ meta: {
92
+ key,
93
+ previousValue: data[key],
94
+ value
95
+ }
96
+ });
50
97
  data[key] = value;
51
98
  continue;
52
99
  }
@@ -63,17 +110,43 @@ function parseText(text) {
63
110
  const PRIORITY_PATTERN = /^\(([A-Z])\) /;
64
111
  const LEADING_DATE_PATTERN = /^(\d{4}-\d{2}-\d{2})(?: |$)/;
65
112
  /**
66
- * Consume a `YYYY-MM-DD` date from the start of `input`.
113
+ * Inspect a `YYYY-MM-DD` token at the start of `input`.
67
114
  *
68
- * Only the shape is validated; the date does not have to exist on a calendar
69
- * (matching the literal format rules).
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.
70
118
  */
71
119
  function takeLeadingDate(input) {
72
120
  const match = LEADING_DATE_PATTERN.exec(input);
73
- if (!match) return [null, input];
121
+ if (!match) return {
122
+ kind: "absent",
123
+ rest: input
124
+ };
74
125
  const date = match[1];
75
- if (date === void 0) return [null, input];
76
- return [date, input.slice(match[0].length)];
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
+ });
77
150
  }
78
151
  /**
79
152
  * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
@@ -84,10 +157,15 @@ function takeLeadingDate(input) {
84
157
  * and then a creation date.
85
158
  * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
86
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.
87
162
  * - Projects, contexts, and `key:value` metadata may appear anywhere in the
88
163
  * remaining text.
164
+ *
165
+ * Recoverable issues are reported to `onWarning` when supplied; parsing still
166
+ * produces a record.
89
167
  */
90
- function parseLine(line) {
168
+ function parseLine(line, onWarning) {
91
169
  let rest = line;
92
170
  let completed = false;
93
171
  let priority = null;
@@ -96,17 +174,29 @@ function parseLine(line) {
96
174
  if (rest.startsWith("x ")) {
97
175
  completed = true;
98
176
  rest = rest.slice(2);
99
- [completedAt, rest] = takeLeadingDate(rest);
100
- [createdAt, rest] = takeLeadingDate(rest);
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);
101
187
  } else {
102
188
  const priorityMatch = PRIORITY_PATTERN.exec(rest);
103
189
  if (priorityMatch) {
104
190
  priority = priorityMatch[1];
105
191
  rest = rest.slice(priorityMatch[0].length);
106
192
  }
107
- [createdAt, rest] = takeLeadingDate(rest);
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);
108
198
  }
109
- const { description, projects, contexts, data } = parseText(rest.trim());
199
+ const { description, projects, contexts, data } = parseText(rest.trim(), onWarning);
110
200
  return {
111
201
  completed,
112
202
  priority,
@@ -122,11 +212,19 @@ function parseLine(line) {
122
212
  * Parse the contents of a todo.txt file.
123
213
  *
124
214
  * Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
125
- * skipped. Every remaining line becomes a {@link TodoRecord}.
215
+ * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are
216
+ * annotated with the 1-based physical line number.
126
217
  */
127
- function parseDocument(contents) {
218
+ function parseDocument(contents, onWarning) {
128
219
  const records = [];
129
- for (const line of contents.split(/\r?\n/)) if (line.trim() !== "") records.push(parseLine(line));
220
+ let lineNumber = 0;
221
+ for (const line of contents.split(/\r?\n/)) {
222
+ lineNumber += 1;
223
+ if (line.trim() !== "") records.push(parseLine(line, onWarning ? (warning) => onWarning({
224
+ ...warning,
225
+ line: lineNumber
226
+ }) : void 0));
227
+ }
130
228
  return records;
131
229
  }
132
230
  // src/query.ts
@@ -168,7 +266,8 @@ function createTodoQuery(load, filters = []) {
168
266
  *
169
267
  * The library performs no IO of its own: `hooks.read` is responsible for
170
268
  * producing the file contents and `hooks.write` will be used by the write APIs
171
- * once they are implemented.
269
+ * once they are implemented. `hooks.logger` is optional and silent by default;
270
+ * when supplied, it receives read lifecycle and parse warning diagnostics.
172
271
  *
173
272
  * Parsed records are cached in memory per client. The first query loads and
174
273
  * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
@@ -186,9 +285,25 @@ function createTodoTxt(hooks) {
186
285
  let cache;
187
286
  let inFlight;
188
287
  let generation = 0;
288
+ const logger = hooks.logger;
289
+ const log = (level, message, meta) => {
290
+ if (!logger) return;
291
+ try {
292
+ const result = logger(level, message, meta);
293
+ if (result && typeof result.then === "function") Promise.resolve(result).catch(() => {});
294
+ } catch {}
295
+ };
189
296
  const readFresh = async () => {
190
297
  const currentGeneration = ++generation;
191
- const records = parseDocument(await hooks.read());
298
+ log("debug", "Reading todo file");
299
+ const records = parseDocument(await hooks.read(), (warning) => {
300
+ log("warn", warning.message, {
301
+ ...warning.meta,
302
+ code: warning.code,
303
+ line: warning.line
304
+ });
305
+ });
306
+ log("debug", "Parsed todo file", { records: records.length });
192
307
  if (currentGeneration === generation) cache = records;
193
308
  return records;
194
309
  };
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","const 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 */\nexport function parseText(text: string): 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 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 { 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 */\nexport function parseLine(line: string): 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);\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}.\n */\nexport function parseDocument(contents: string): TodoRecord[] {\n const records: TodoRecord[] = [];\n\n for (const line of contents.split(/\\r?\\n/)) {\n if (line.trim() !== \"\") {\n records.push(parseLine(line));\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 { TodoFileHooks, 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.\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: TodoFileHooks): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n const records = parseDocument(await hooks.read());\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;;ACnBA,MAAM,oBAAoB;AAc1B,SAAS,SAAS,MAAwB;CACxC,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,YAAY,IACd,OAAO,CAAC;CAGV,OAAO,QAAQ,MAAM,KAAK;AAC5B;;;;;;;AA2BA,SAAgB,UAAU,MAAwB;CAChD,MAAM,WAAqB,CAAC;CAC5B,MAAM,WAAqB,CAAC;CAC5B,MAAM,OAA+B,CAAC;CACtC,MAAM,oBAA8B,CAAC;CAErC,KAAK,MAAM,SAAS,SAAS,IAAI,GAAG;EAClC,IAAI,MAAM,WAAW,GAAG,KAAK,MAAM,SAAS,GAAG;GAC7C,SAA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AAK,QAAQ;EACjE,gBAAgB,WAAW,MAAM,UAAU,SAAS,KAAK,QAAQ;EACjE,OAAO,aAAa,eAClB,eAAe,MAAM,OAAO,CAAC,CAAC,KAAK,aAAa,UAAU;CAC9D;AACF;;;;;;;;;;;;;;;;;;;;;ACzDA,SAAgB,cAAc,OAAqC;CACjE,IAAI;CACJ,IAAI;CACJ,IAAI,aAAa;CAEjB,MAAM,YAAY,YAAmC;EACnD,MAAM,oBAAoB,EAAE;EAC5B,MAAM,UAAU,cAAc,MAAM,MAAM,KAAK,CAAC;EAEhD,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;;ACnBA,MAAM,qBAAqB;AAC3B,MAAM,g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AEhC,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jibone/todotxt-core",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Parse and query todo.txt files with runtime-agnostic file hooks.",
5
5
  "license": "MIT",
6
6
  "author": "J Shamsul Bahri",