@type32/tasks 0.0.0 → 0.1.1
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 +262 -27
- package/SPEC.md +269 -0
- package/conformance/errors.yaml +610 -0
- package/conformance/valid.yaml +194 -0
- package/dist/index.d.mts +114 -4
- package/dist/index.mjs +301 -55
- package/llms.txt +43 -0
- package/package.json +8 -2
package/dist/index.mjs
CHANGED
|
@@ -1,32 +1,43 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
2
|
import { TomlDate, parse as parse$1, stringify as stringify$1 } from "smol-toml";
|
|
3
|
-
import {
|
|
3
|
+
import { load } from "js-yaml";
|
|
4
|
+
import { stringify as stringify$2 } from "yaml";
|
|
4
5
|
import { Temporal } from "temporal-polyfill";
|
|
5
6
|
// src/cycle.ts
|
|
6
7
|
/**
|
|
7
8
|
* Indices of the first cycle along `edges`, in link order (each member links to the next, the last to the first).
|
|
8
|
-
* Edges to unknown ids are ignored.
|
|
9
|
+
* Edges to unknown ids are ignored. Iterative, so chains of any length don't overflow the call stack.
|
|
9
10
|
*/
|
|
10
11
|
function findCycle(items, edges) {
|
|
11
12
|
const index = new Map(items.map((item, i) => [item.id, i]));
|
|
12
13
|
const state = new Uint8Array(items.length);
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
const path = [];
|
|
15
|
+
const targets = [];
|
|
16
|
+
const next = [];
|
|
17
|
+
const enter = (i) => {
|
|
17
18
|
state[i] = 1;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const cycle = j === void 0 ? void 0 : visit(j);
|
|
22
|
-
if (cycle) return cycle;
|
|
23
|
-
}
|
|
24
|
-
stack.pop();
|
|
25
|
-
state[i] = 2;
|
|
19
|
+
path.push(i);
|
|
20
|
+
targets.push(edges(items[i]));
|
|
21
|
+
next.push(0);
|
|
26
22
|
};
|
|
27
|
-
for (let
|
|
28
|
-
|
|
29
|
-
|
|
23
|
+
for (let root = 0; root < items.length; root++) {
|
|
24
|
+
if (state[root] !== 0) continue;
|
|
25
|
+
enter(root);
|
|
26
|
+
while (path.length > 0) {
|
|
27
|
+
const top = path.length - 1;
|
|
28
|
+
const position = next[top];
|
|
29
|
+
if (position === targets[top].length) {
|
|
30
|
+
state[path.pop()] = 2;
|
|
31
|
+
targets.pop();
|
|
32
|
+
next.pop();
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
next[top] = position + 1;
|
|
36
|
+
const j = index.get(targets[top][position]);
|
|
37
|
+
if (j === void 0 || state[j] === 2) continue;
|
|
38
|
+
if (state[j] === 1) return path.slice(path.indexOf(j));
|
|
39
|
+
enter(j);
|
|
40
|
+
}
|
|
30
41
|
}
|
|
31
42
|
}
|
|
32
43
|
// src/schema.ts
|
|
@@ -106,6 +117,7 @@ function resolveFields(doc) {
|
|
|
106
117
|
}
|
|
107
118
|
return out;
|
|
108
119
|
}
|
|
120
|
+
/** `span`, `moment` or `todo`, from the task's time fields. Use it to pick how to draw a task. */
|
|
109
121
|
function kindOf(task) {
|
|
110
122
|
if (task.start === void 0) return "todo";
|
|
111
123
|
return task.end !== void 0 || task.duration !== void 0 ? "span" : "moment";
|
|
@@ -150,13 +162,17 @@ function sortKey(v) {
|
|
|
150
162
|
if (s.length === 19) s += ".";
|
|
151
163
|
return s.padEnd(29, "0");
|
|
152
164
|
}
|
|
165
|
+
const knownZones = /* @__PURE__ */ new Set();
|
|
153
166
|
function isTimeZone(v) {
|
|
167
|
+
if (knownZones.has(v)) return true;
|
|
154
168
|
if (/^[+-]/.test(v)) return false;
|
|
155
169
|
try {
|
|
156
|
-
|
|
170
|
+
new Intl.DateTimeFormat("en-US", { timeZone: v }).resolvedOptions();
|
|
157
171
|
} catch {
|
|
158
172
|
return false;
|
|
159
173
|
}
|
|
174
|
+
knownZones.add(v);
|
|
175
|
+
return true;
|
|
160
176
|
}
|
|
161
177
|
const id = z.string().min(1, "expected a non-empty id");
|
|
162
178
|
const utc$1 = z.iso.datetime("expected a UTC date-time like 2026-11-09T10:00:00Z");
|
|
@@ -245,7 +261,7 @@ const taskSchema = z.looseObject({
|
|
|
245
261
|
z.number(),
|
|
246
262
|
z.boolean(),
|
|
247
263
|
z.array(z.string())
|
|
248
|
-
])).exactOptional()
|
|
264
|
+
], { error: "expected text, a finite number, true/false, or a list of strings" })).exactOptional()
|
|
249
265
|
});
|
|
250
266
|
/** The whole format. Use `validate()`/`parse()` for errors as `TasksFormatError`. */
|
|
251
267
|
const documentSchema = z.looseObject({
|
|
@@ -258,6 +274,12 @@ const documentSchema = z.looseObject({
|
|
|
258
274
|
path,
|
|
259
275
|
message
|
|
260
276
|
})));
|
|
277
|
+
/** One task on its own: shape and time rules. References and `values` need the whole document. */
|
|
278
|
+
const standaloneTaskSchema = taskSchema.superRefine((t, ctx) => checkTime(t, [], (path, message) => ctx.addIssue({
|
|
279
|
+
code: "custom",
|
|
280
|
+
path,
|
|
281
|
+
message
|
|
282
|
+
})));
|
|
261
283
|
function checkDocument(doc, issue) {
|
|
262
284
|
const lists = doc.lists ?? [];
|
|
263
285
|
const defs = doc.fields ?? [];
|
|
@@ -350,7 +372,13 @@ function checkField(f, path, issue) {
|
|
|
350
372
|
for (const key of ["min", "max"]) if (f[key] !== void 0) issue([...path, key], `only number fields can have "${key}"`);
|
|
351
373
|
}
|
|
352
374
|
if (f.min !== void 0 && f.max !== void 0 && f.min > f.max) issue([...path, "max"], "max is below min");
|
|
353
|
-
|
|
375
|
+
f.categories?.forEach((c, i) => {
|
|
376
|
+
if (f.categories.indexOf(c) !== i) issue([
|
|
377
|
+
...path,
|
|
378
|
+
"categories",
|
|
379
|
+
i
|
|
380
|
+
], `duplicate category "${c}"`);
|
|
381
|
+
});
|
|
354
382
|
}
|
|
355
383
|
if (f.options === void 0) return;
|
|
356
384
|
if (!select) return issue([...path, "options"], `only select fields can have "options"`);
|
|
@@ -371,7 +399,7 @@ function checkField(f, path, issue) {
|
|
|
371
399
|
if (o.title === void 0) issue([...p, "title"], "options need a title");
|
|
372
400
|
if (!categories) {
|
|
373
401
|
if (o.category !== void 0) issue([...p, "category"], `field "${f.id}" has no categories`);
|
|
374
|
-
} else if (o.category === void 0 || !categories.includes(o.category)) issue([...p, "category"], `expected one of: ${categories.join(", ")}`);
|
|
402
|
+
} else if (o.deletedAt === void 0 && (o.category === void 0 || !categories.includes(o.category))) issue([...p, "category"], `expected one of: ${categories.join(", ")}`);
|
|
375
403
|
});
|
|
376
404
|
}
|
|
377
405
|
function checkTime(t, path, issue) {
|
|
@@ -435,6 +463,10 @@ function valueError(f, v) {
|
|
|
435
463
|
}
|
|
436
464
|
}
|
|
437
465
|
// src/parse.ts
|
|
466
|
+
/**
|
|
467
|
+
* Thrown for any input the format rejects: syntax errors, wrong shapes, broken rules. `message` lists every
|
|
468
|
+
* issue as `path: message` lines, ready to show to a user; `issues` has them structured.
|
|
469
|
+
*/
|
|
438
470
|
var TasksFormatError = class extends Error {
|
|
439
471
|
issues;
|
|
440
472
|
constructor(issues) {
|
|
@@ -448,31 +480,73 @@ var TasksFormatError = class extends Error {
|
|
|
448
480
|
* Cross-field rules (references, cycles, values) only run once the structure is valid.
|
|
449
481
|
*/
|
|
450
482
|
function validate(value) {
|
|
451
|
-
|
|
483
|
+
return check(documentSchema, value);
|
|
484
|
+
}
|
|
485
|
+
/** Runs `schema`, turning Zod issues into a `TasksFormatError` with paths under `prefix`. */
|
|
486
|
+
function check(schema, value, prefix = []) {
|
|
487
|
+
const result = schema.safeParse(value);
|
|
452
488
|
if (result.success) return result.data;
|
|
453
489
|
throw new TasksFormatError(result.error.issues.map((i) => ({
|
|
454
|
-
path: i.path.map((k) => typeof k === "symbol" ? String(k) : k),
|
|
490
|
+
path: [...prefix, ...i.path.map((k) => typeof k === "symbol" ? String(k) : k)],
|
|
455
491
|
message: i.message
|
|
456
492
|
})));
|
|
457
493
|
}
|
|
494
|
+
/** Reads and validates a whole document. Throws `TasksFormatError`. Dates and times come back as strings. */
|
|
458
495
|
function parse(text, format) {
|
|
459
|
-
|
|
496
|
+
return validate(decode(text, format));
|
|
497
|
+
}
|
|
498
|
+
/** Validates, then serializes. Unknown keys are written back unchanged. */
|
|
499
|
+
function stringify(doc, format) {
|
|
500
|
+
return encode(validate(doc), format);
|
|
501
|
+
}
|
|
502
|
+
/** Text → plain data. Syntax errors become `TasksFormatError`; a leading BOM is ignored. */
|
|
503
|
+
function decode(text, format) {
|
|
504
|
+
const source = text.replace(/^\uFEFF/, "");
|
|
460
505
|
try {
|
|
461
|
-
|
|
506
|
+
switch (format) {
|
|
507
|
+
case "json": return JSON.parse(source);
|
|
508
|
+
case "yaml": {
|
|
509
|
+
const value = load(source);
|
|
510
|
+
checkExpansion(value, source.length);
|
|
511
|
+
return value;
|
|
512
|
+
}
|
|
513
|
+
case "toml": return datesToStrings(parse$1(source));
|
|
514
|
+
}
|
|
462
515
|
} catch (error) {
|
|
463
516
|
throw new TasksFormatError([{
|
|
464
517
|
path: [],
|
|
465
518
|
message: `invalid ${format}: ${error.message}`
|
|
466
519
|
}]);
|
|
467
520
|
}
|
|
468
|
-
return validate(value);
|
|
469
521
|
}
|
|
470
|
-
/**
|
|
471
|
-
|
|
472
|
-
|
|
522
|
+
/**
|
|
523
|
+
* Aliases are kept as shared references, so a few dozen nested ones can stand for billions of values that
|
|
524
|
+
* validation would then walk. Reject data far larger than its text could hold without aliases.
|
|
525
|
+
*/
|
|
526
|
+
function checkExpansion(value, sourceLength) {
|
|
527
|
+
let budget = sourceLength * 10 + 1e4;
|
|
528
|
+
const stack = [value];
|
|
529
|
+
while (stack.length > 0) {
|
|
530
|
+
const v = stack.pop();
|
|
531
|
+
if (--budget < 0) throw new Error("aliases expand to far more data than the text holds");
|
|
532
|
+
if (v !== null && typeof v === "object") stack.push(...Object.values(v));
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
/** Plain data → text, no validation. */
|
|
536
|
+
function encode(data, format) {
|
|
473
537
|
switch (format) {
|
|
474
538
|
case "json": return `${JSON.stringify(data, null, 2)}\n`;
|
|
475
|
-
case "yaml": return stringify$2(data, {
|
|
539
|
+
case "yaml": return stringify$2(data, {
|
|
540
|
+
version: "1.1",
|
|
541
|
+
customTags: [
|
|
542
|
+
"intOct",
|
|
543
|
+
"intHex",
|
|
544
|
+
"int",
|
|
545
|
+
"floatExp",
|
|
546
|
+
"floatNaN",
|
|
547
|
+
"float"
|
|
548
|
+
]
|
|
549
|
+
});
|
|
476
550
|
case "toml": {
|
|
477
551
|
const path = findNull(data, []);
|
|
478
552
|
if (path) throw new TasksFormatError([{
|
|
@@ -483,13 +557,6 @@ function stringify(doc, format) {
|
|
|
483
557
|
}
|
|
484
558
|
}
|
|
485
559
|
}
|
|
486
|
-
function decode(text, format) {
|
|
487
|
-
switch (format) {
|
|
488
|
-
case "json": return JSON.parse(text);
|
|
489
|
-
case "yaml": return parse$2(text);
|
|
490
|
-
case "toml": return datesToStrings(parse$1(text));
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
560
|
/** Unquoted TOML dates parse to TomlDate; the format stores them as strings in the same form. */
|
|
494
561
|
function datesToStrings(value) {
|
|
495
562
|
if (value instanceof TomlDate) return value.toISOString();
|
|
@@ -590,6 +657,7 @@ function breakCycles(items, collection, key, repairs) {
|
|
|
590
657
|
item.dependsOn = item.dependsOn.filter((d) => d !== target);
|
|
591
658
|
if (item.dependsOn.length === 0) delete item.dependsOn;
|
|
592
659
|
}
|
|
660
|
+
bump(item);
|
|
593
661
|
repairs.push({
|
|
594
662
|
path: [
|
|
595
663
|
collection,
|
|
@@ -621,32 +689,39 @@ function repairOptions(doc, repairs) {
|
|
|
621
689
|
return;
|
|
622
690
|
}
|
|
623
691
|
const { categories } = f;
|
|
624
|
-
f.options
|
|
625
|
-
if (
|
|
626
|
-
if (o.category === void 0) return true;
|
|
627
|
-
repairs.push({
|
|
628
|
-
path,
|
|
629
|
-
message: `"${f.id}" has no categories anymore; option "${o.id}" lost its category`,
|
|
630
|
-
removed: o.category
|
|
631
|
-
});
|
|
632
|
-
delete o.category;
|
|
633
|
-
return true;
|
|
634
|
-
}
|
|
635
|
-
if (o.category !== void 0 && categories.includes(o.category)) return true;
|
|
692
|
+
for (const o of f.options) if (!categories) {
|
|
693
|
+
if (o.category === void 0) continue;
|
|
636
694
|
repairs.push({
|
|
637
695
|
path,
|
|
638
|
-
message: `
|
|
639
|
-
removed: o
|
|
696
|
+
message: `"${f.id}" has no categories anymore; option "${o.id}" lost its category`,
|
|
697
|
+
removed: o.category
|
|
640
698
|
});
|
|
641
|
-
|
|
642
|
-
|
|
699
|
+
delete o.category;
|
|
700
|
+
bump(o);
|
|
701
|
+
} else if (o.deletedAt === void 0 && (o.category === void 0 || !categories.includes(o.category))) {
|
|
702
|
+
repairs.push({
|
|
703
|
+
path,
|
|
704
|
+
message: `option "${o.id}" has category "${o.category}", which "${f.id}" no longer has; marked deleted`,
|
|
705
|
+
removed: o.category
|
|
706
|
+
});
|
|
707
|
+
bump(o);
|
|
708
|
+
o.deletedAt = o.updatedAt;
|
|
709
|
+
}
|
|
643
710
|
});
|
|
644
711
|
}
|
|
712
|
+
/**
|
|
713
|
+
* A repaired record must beat both copies it came from, or merging a stale copy again would undo the repair.
|
|
714
|
+
* One millisecond past its own stamp is deterministic, so every device produces the same repaired record.
|
|
715
|
+
*/
|
|
716
|
+
function bump(record) {
|
|
717
|
+
record.updatedAt = Temporal.Instant.from(record.updatedAt).add({ milliseconds: 1 }).toString();
|
|
718
|
+
}
|
|
645
719
|
/** Values set against an older version of their field definition. */
|
|
646
720
|
function repairValues(doc, repairs) {
|
|
647
721
|
const fields = resolveFields(doc);
|
|
648
722
|
doc.tasks.forEach((t, i) => {
|
|
649
723
|
if (!t.values) return;
|
|
724
|
+
let changed = false;
|
|
650
725
|
for (const [key, value] of Object.entries(t.values)) {
|
|
651
726
|
const field = fields[key];
|
|
652
727
|
const error = field ? valueError(field, value) : `unknown field "${key}"`;
|
|
@@ -662,7 +737,9 @@ function repairValues(doc, repairs) {
|
|
|
662
737
|
removed: value
|
|
663
738
|
});
|
|
664
739
|
delete t.values[key];
|
|
740
|
+
changed = true;
|
|
665
741
|
}
|
|
742
|
+
if (changed) bump(t);
|
|
666
743
|
if (Object.keys(t.values).length === 0) delete t.values;
|
|
667
744
|
});
|
|
668
745
|
}
|
|
@@ -734,10 +811,69 @@ function occurrences(task, range) {
|
|
|
734
811
|
if (rule?.count !== void 0 && count++ >= rule.count) break;
|
|
735
812
|
if (excluded.has(occurrence.toString())) continue;
|
|
736
813
|
const built = build(occurrence);
|
|
737
|
-
if (built)
|
|
814
|
+
if (!built) continue;
|
|
815
|
+
const last = result.at(-1);
|
|
816
|
+
if (last && (last.start ?? last.due) === (built.start ?? built.due)) continue;
|
|
817
|
+
result.push(built);
|
|
738
818
|
}
|
|
739
819
|
return result;
|
|
740
820
|
}
|
|
821
|
+
/**
|
|
822
|
+
* Completes a task, returning a new one (the input is unchanged); `updatedAt` becomes `completedAt`.
|
|
823
|
+
* - Recurring with occurrences left: `start`, `end` and `due` move to the next occurrence (by their offsets
|
|
824
|
+
* from the anchor), `count` drops by the occurrences used up, `status` and `progress` (if set) reset to
|
|
825
|
+
* `todo` and 0. `completedAt` is left alone: the series isn't done.
|
|
826
|
+
* - Otherwise, including the last occurrence: `status` becomes `done` and `completedAt` is set.
|
|
827
|
+
*/
|
|
828
|
+
function completeTask(task, completedAt) {
|
|
829
|
+
const anchorText = task.start ?? task.due;
|
|
830
|
+
const rule = task.recurrence;
|
|
831
|
+
const next = rule && anchorText !== void 0 ? nextAfterAnchor(task, PlainDateTime.from(anchorText), rule) : void 0;
|
|
832
|
+
if (!next) return {
|
|
833
|
+
...task,
|
|
834
|
+
completedAt,
|
|
835
|
+
updatedAt: completedAt,
|
|
836
|
+
values: {
|
|
837
|
+
...task.values,
|
|
838
|
+
status: "done"
|
|
839
|
+
}
|
|
840
|
+
};
|
|
841
|
+
const anchor = PlainDateTime.from(anchorText);
|
|
842
|
+
const moved = (value) => format(next.at.add(anchor.until(PlainDateTime.from(value), { largestUnit: "days" })), value);
|
|
843
|
+
const out = {
|
|
844
|
+
...task,
|
|
845
|
+
updatedAt: completedAt
|
|
846
|
+
};
|
|
847
|
+
if (task.start !== void 0) out.start = moved(task.start);
|
|
848
|
+
if (task.end !== void 0) out.end = moved(task.end);
|
|
849
|
+
if (task.due !== void 0) out.due = moved(task.due);
|
|
850
|
+
if (rule.count !== void 0) out.recurrence = {
|
|
851
|
+
...rule,
|
|
852
|
+
count: rule.count - next.used
|
|
853
|
+
};
|
|
854
|
+
if (task.values) {
|
|
855
|
+
out.values = { ...task.values };
|
|
856
|
+
if (out.values["status"] !== void 0) out.values["status"] = "todo";
|
|
857
|
+
if (out.values["progress"] !== void 0) out.values["progress"] = 0;
|
|
858
|
+
}
|
|
859
|
+
return out;
|
|
860
|
+
}
|
|
861
|
+
/** The first occurrence after the anchor, and how many occurrences (excluded ones included) precede it. */
|
|
862
|
+
function nextAfterAnchor(task, anchor, rule) {
|
|
863
|
+
const until = rule.until === void 0 ? void 0 : PlainDateTime.from(rule.until);
|
|
864
|
+
const limit = until ?? anchor.add({ years: 1e3 });
|
|
865
|
+
const excluded = new Set(task.excludedDates?.map((d) => PlainDateTime.from(d).toString()));
|
|
866
|
+
let index = -1;
|
|
867
|
+
for (const at of recur(anchor, rule, limit)) {
|
|
868
|
+
index++;
|
|
869
|
+
if (until && PlainDateTime.compare(at, until) > 0) return void 0;
|
|
870
|
+
if (rule.count !== void 0 && index >= rule.count) return void 0;
|
|
871
|
+
if (index > 0 && !excluded.has(at.toString())) return {
|
|
872
|
+
at,
|
|
873
|
+
used: index
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
}
|
|
741
877
|
/** Keeps the source's form: date-only stays a date, a time written without seconds stays without them. */
|
|
742
878
|
function format(value, like) {
|
|
743
879
|
if (!like.includes("T")) return value.toPlainDate().toString();
|
|
@@ -1220,4 +1356,114 @@ function unescape(value, split = false) {
|
|
|
1220
1356
|
}
|
|
1221
1357
|
return parts;
|
|
1222
1358
|
}
|
|
1223
|
-
|
|
1359
|
+
// src/markdown.ts
|
|
1360
|
+
const CLOSE = {
|
|
1361
|
+
"---": /^---[ \t]*(?:\r?\n|$)/m,
|
|
1362
|
+
"+++": /^\+\+\+[ \t]*(?:\r?\n|$)/m
|
|
1363
|
+
};
|
|
1364
|
+
/** Frontmatter must open on the first line and close on a line of its own. */
|
|
1365
|
+
function split(text) {
|
|
1366
|
+
const source = text.replace(/^\uFEFF/, "");
|
|
1367
|
+
const open = /^(---|\+\+\+)[ \t]*\r?\n/.exec(source);
|
|
1368
|
+
if (!open) return void 0;
|
|
1369
|
+
const fence = open[1];
|
|
1370
|
+
const rest = source.slice(open[0].length);
|
|
1371
|
+
const close = CLOSE[fence].exec(rest);
|
|
1372
|
+
if (!close) return void 0;
|
|
1373
|
+
return {
|
|
1374
|
+
syntax: fence === "---" ? "yaml" : "toml",
|
|
1375
|
+
data: rest.slice(0, close.index),
|
|
1376
|
+
body: rest.slice(close.index + close[0].length)
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
const NO_TASK = "frontmatter has no task object";
|
|
1380
|
+
const frontmatterSchema = z.looseObject({ task: z.record(z.string(), z.unknown(), { error: NO_TASK }) }, { error: NO_TASK });
|
|
1381
|
+
/**
|
|
1382
|
+
* True when `text` opens with YAML or TOML frontmatter holding a `task` object. Reads only the frontmatter
|
|
1383
|
+
* and never throws; it doesn't validate the task (use `parseMarkdown` for that). Meant for indexing.
|
|
1384
|
+
*/
|
|
1385
|
+
function isTaskFile(text) {
|
|
1386
|
+
const parts = split(text);
|
|
1387
|
+
if (!parts?.data.includes("task")) return false;
|
|
1388
|
+
try {
|
|
1389
|
+
return frontmatterSchema.safeParse(decode(parts.data, parts.syntax)).success;
|
|
1390
|
+
} catch {
|
|
1391
|
+
return false;
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Reads a task file. Checks the task's shape and time rules; references (`listId`, `parentId`, `dependsOn`)
|
|
1396
|
+
* and `values` are checked once tasks are combined into a document with `validate()`.
|
|
1397
|
+
*/
|
|
1398
|
+
function parseMarkdown(text) {
|
|
1399
|
+
const parts = split(text);
|
|
1400
|
+
if (!parts) throw new TasksFormatError([{
|
|
1401
|
+
path: [],
|
|
1402
|
+
message: "expected frontmatter between --- (YAML) or +++ (TOML) lines at the start of the file"
|
|
1403
|
+
}]);
|
|
1404
|
+
const data = parts.data.trim() === "" ? {} : decode(parts.data, parts.syntax);
|
|
1405
|
+
const { task, ...frontmatter } = check(frontmatterSchema, data);
|
|
1406
|
+
if (Object.hasOwn(task, "notes")) throw new TasksFormatError([{
|
|
1407
|
+
path: ["task", "notes"],
|
|
1408
|
+
message: "notes are the Markdown body, not a frontmatter key"
|
|
1409
|
+
}]);
|
|
1410
|
+
const withNotes = parts.body === "" ? task : {
|
|
1411
|
+
...task,
|
|
1412
|
+
notes: parts.body
|
|
1413
|
+
};
|
|
1414
|
+
return {
|
|
1415
|
+
task: check(standaloneTaskSchema, withNotes, ["task"]),
|
|
1416
|
+
frontmatter,
|
|
1417
|
+
syntax: parts.syntax
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
/** Writes frontmatter (other keys first, then `task`) and `task.notes` as the body. Fences use `\n`. */
|
|
1421
|
+
function stringifyMarkdown(file) {
|
|
1422
|
+
const { notes, ...task } = check(standaloneTaskSchema, file.task, ["task"]);
|
|
1423
|
+
const fence = file.syntax === "yaml" ? "---" : "+++";
|
|
1424
|
+
const data = encode({
|
|
1425
|
+
...file.frontmatter,
|
|
1426
|
+
task
|
|
1427
|
+
}, file.syntax);
|
|
1428
|
+
return `${fence}\n${data.endsWith("\n") ? data : `${data}\n`}${fence}\n${notes ?? ""}`;
|
|
1429
|
+
}
|
|
1430
|
+
// src/predicates.ts
|
|
1431
|
+
/** The status category: `shipped` → `done` if the document maps it so. No status means `todo`. */
|
|
1432
|
+
function statusOf(task, fields) {
|
|
1433
|
+
const id = task.values?.["status"];
|
|
1434
|
+
return fields["status"].options.find((o) => o.id === id)?.category ?? "todo";
|
|
1435
|
+
}
|
|
1436
|
+
/** The priority category, or undefined when the task has none. */
|
|
1437
|
+
function priorityOf(task, fields) {
|
|
1438
|
+
const id = task.values?.["priority"];
|
|
1439
|
+
return fields["priority"].options.find((o) => o.id === id)?.category;
|
|
1440
|
+
}
|
|
1441
|
+
/** Status means done. Cancelled tasks aren't complete. */
|
|
1442
|
+
function isComplete(task, fields) {
|
|
1443
|
+
return statusOf(task, fields) === "done";
|
|
1444
|
+
}
|
|
1445
|
+
/** Still to do: not deleted, and status `todo` or `doing`. */
|
|
1446
|
+
function isOpen(task, fields) {
|
|
1447
|
+
const status = statusOf(task, fields);
|
|
1448
|
+
return task.deletedAt === void 0 && (status === "todo" || status === "doing");
|
|
1449
|
+
}
|
|
1450
|
+
/**
|
|
1451
|
+
* The task is open and its `due` has passed. An all-day due date is overdue once its day is over in the
|
|
1452
|
+
* viewer's zone; a timed one once that moment passes, in the task's `timeZone` if it has one.
|
|
1453
|
+
*/
|
|
1454
|
+
function isOverdue(task, fields, options = {}) {
|
|
1455
|
+
const { due } = task;
|
|
1456
|
+
if (due === void 0 || !isOpen(task, fields)) return false;
|
|
1457
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
1458
|
+
const instant = Temporal.Instant.from(typeof now === "string" ? now : now.toISOString());
|
|
1459
|
+
const allDay = !due.includes("T");
|
|
1460
|
+
const zone = (allDay ? void 0 : task.timeZone) ?? options.timeZone ?? Temporal.Now.timeZoneId();
|
|
1461
|
+
const wall = instant.toZonedDateTimeISO(zone).toPlainDateTime();
|
|
1462
|
+
return allDay ? Temporal.PlainDate.compare(wall.toPlainDate(), Temporal.PlainDate.from(due)) > 0 : Temporal.PlainDateTime.compare(wall, Temporal.PlainDateTime.from(due)) > 0;
|
|
1463
|
+
}
|
|
1464
|
+
/** The tasks in `dependsOn` still in the way: not done, not cancelled, not deleted. Empty when unblocked. */
|
|
1465
|
+
function blockers(task, tasks, fields) {
|
|
1466
|
+
const ids = new Set(task.dependsOn);
|
|
1467
|
+
return ids.size === 0 ? [] : tasks.filter((t) => ids.has(t.id) && isOpen(t, fields));
|
|
1468
|
+
}
|
|
1469
|
+
export { TasksFormatError, blockers, completeTask, documentSchema, fromICS, isComplete, isOpen, isOverdue, isTaskFile, kindOf, merge, occurrences, parse, parseMarkdown, priorityOf, resolveFields, statusOf, stringify, stringifyMarkdown, toICS, validate };
|
package/llms.txt
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# @type32/tasks
|
|
2
|
+
|
|
3
|
+
> TypeScript library and file format that unifies todos, calendar events and timelines as one object, the task. It parses and validates JSON, YAML and TOML documents and Markdown task files, merges copies for sync, expands recurrence across time zones, and converts to and from iCalendar. ESM only; `import { … } from "@type32/tasks"`.
|
|
4
|
+
|
|
5
|
+
A task's kind comes from its time fields, never a type field: `start` plus `end` or `duration` is a span (event or timeline bar), `start` alone is a moment (milestone), and no `start` is a todo (optionally with `due`).
|
|
6
|
+
|
|
7
|
+
## Rules for writing documents
|
|
8
|
+
|
|
9
|
+
- Top level: `{ version: "1.0", lists?: List[], fields?: FieldDefinition[], tasks: Task[] }`.
|
|
10
|
+
- Every task, list, custom field and field option needs `id` (UUID recommended) and `updatedAt`. Set `updatedAt` to the current UTC time on every change.
|
|
11
|
+
- Delete by setting `deletedAt` (UTC); never remove a record that others may reference.
|
|
12
|
+
- Time formats:
|
|
13
|
+
- `start`, `end`, `due`, `until` and `excludedDates` are local: `2026-11-12` (all-day) or `2026-11-12T09:30` (wall clock in `timeZone`; floating without one). Never put an offset or `Z` on these.
|
|
14
|
+
- `updatedAt`, `completedAt` and `deletedAt` are UTC with `Z`.
|
|
15
|
+
- `end` needs `start`, must be the same form (both dates or both date-times), and can't come before it. A date `end` is inclusive. Use `end` or `duration` (ISO 8601 such as `PT1H30M`, `P1D`, `P2W`; never years or months), not both.
|
|
16
|
+
- `timeZone` is an IANA name (`Europe/Berlin`), never an offset.
|
|
17
|
+
- `recurrence`: `{ freq: daily|weekly|monthly|yearly, interval?, byDay?: [{ day: mo…su, nth? }], byMonthDay?, byMonth?, count? | until? }`.
|
|
18
|
+
- It needs `start` or `due`.
|
|
19
|
+
- `nth` only with monthly or yearly.
|
|
20
|
+
- Any other key is an error.
|
|
21
|
+
- Statuses, priorities, tags and custom fields all go in `task.values`:
|
|
22
|
+
- Built-ins: `status: todo|doing|done|cancelled`, `priority: low|medium|high`, `tags: string[]`, `progress: 0–100`, `location: string`.
|
|
23
|
+
- A custom field or custom option must be defined under `fields` before use. A custom status option maps to a built-in category: `{ id: shipped, title: Shipped, category: done, updatedAt }`.
|
|
24
|
+
- Colors are `#rrggbb`.
|
|
25
|
+
- Unknown keys anywhere are kept, except inside `recurrence`, where they're an error.
|
|
26
|
+
|
|
27
|
+
## Rules for writing code
|
|
28
|
+
|
|
29
|
+
- Dates are strings throughout; the library never returns `Date` objects.
|
|
30
|
+
- `parse`, `stringify`, `validate`, `parseMarkdown`, `stringifyMarkdown`, `toICS` and `fromICS` throw `TasksFormatError` (`.issues: { path, message }[]`; `.message` is ready to show). `isTaskFile` never throws.
|
|
31
|
+
- Resolve `const fields = resolveFields(doc)` once, then use the helpers instead of comparing ids, because custom options like `shipped` mean `done`. The helpers: `statusOf(task, fields)` (todo|doing|done|cancelled), `priorityOf`, `isComplete`, `isOpen` (not deleted, todo or doing), `isOverdue(task, fields, { now?, timeZone? })` and `blockers(task, doc.tasks, fields)`. For other fields, read `fields[id].options` and each option's `.category`.
|
|
32
|
+
- To draw a calendar or timeline, call `occurrences(task, { from, to, timeZone? })` for each task (`to` is exclusive). Don't expand recurrence by hand.
|
|
33
|
+
- To complete a task, use `completeTask(task, new Date().toISOString())`. It returns a new task: repeating tasks move to their next occurrence, everything else becomes `status: done`. Don't move recurring dates by hand.
|
|
34
|
+
- For sync, call `merge(local, remote)`. It returns `{ document, repairs }`; show `repairs` to the user.
|
|
35
|
+
- `parseMarkdown` checks one file only. Combine tasks from many files with `validate({ version: "1.0", lists, fields, tasks })` to check references and values.
|
|
36
|
+
- `fromICS` returns `{ document, dropped }`; `dropped` lists what couldn't be imported.
|
|
37
|
+
|
|
38
|
+
## Docs
|
|
39
|
+
|
|
40
|
+
- [README.md](./README.md): usage guide with examples for each job, common mistakes, API table
|
|
41
|
+
- [SPEC.md](./SPEC.md): the format specification, with every field, rule, the merge algorithm, recurrence expansion and the iCalendar mapping
|
|
42
|
+
- [dist/index.d.mts](./dist/index.d.mts): type declarations with a doc comment on every export and field
|
|
43
|
+
- [conformance/errors.yaml](./conformance/errors.yaml), [conformance/valid.yaml](./conformance/valid.yaml): example inputs with exact expected results
|
package/package.json
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@type32/tasks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "One format for todos, events and timelines: schema, validation and parsing",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"files": [
|
|
7
|
-
"dist"
|
|
7
|
+
"dist",
|
|
8
|
+
"SPEC.md",
|
|
9
|
+
"llms.txt",
|
|
10
|
+
"conformance"
|
|
8
11
|
],
|
|
9
12
|
"type": "module",
|
|
10
13
|
"sideEffects": false,
|
|
@@ -19,6 +22,7 @@
|
|
|
19
22
|
"dev": "tsdown --watch",
|
|
20
23
|
"test": "vitest run",
|
|
21
24
|
"test:watch": "vitest",
|
|
25
|
+
"bench": "tsdown --logLevel silent && node bench/index.ts",
|
|
22
26
|
"typecheck": "tsc --noEmit",
|
|
23
27
|
"lint": "oxlint",
|
|
24
28
|
"format": "oxfmt",
|
|
@@ -29,6 +33,7 @@
|
|
|
29
33
|
"prepublishOnly": "bun run build"
|
|
30
34
|
},
|
|
31
35
|
"dependencies": {
|
|
36
|
+
"js-yaml": "^5.5.0",
|
|
32
37
|
"smol-toml": "^1.9.1",
|
|
33
38
|
"temporal-polyfill": "^1.0.8",
|
|
34
39
|
"yaml": "^2.9.1",
|
|
@@ -39,6 +44,7 @@
|
|
|
39
44
|
"@types/node": "^26.6.6",
|
|
40
45
|
"oxfmt": "^0.77.0",
|
|
41
46
|
"oxlint": "^1.92.0",
|
|
47
|
+
"tinybench": "^6.2.3",
|
|
42
48
|
"tsdown": "^0.23.7",
|
|
43
49
|
"typescript": "^7.0.2",
|
|
44
50
|
"vitest": "^5.1.0"
|