-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
880 lines (863 loc) · 38.3 KB
/
Copy pathmain.js
File metadata and controls
880 lines (863 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => CustodianPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian = require("obsidian");
// src/authoring-prompt.ts
function buildRuleAuthoringPrompt(ruleset) {
return `You are writing a Custodian ruleset for Obsidian. Read the user's filing request, update the current ruleset, and return only valid JSON. Do not use Markdown fences or explanatory text.
Ruleset format:
{
"version": 1,
"rules": [
{
"id": "unique-id",
"name": "Readable name",
"enabled": true,
"destination": "Folder/{{property:project|Unassigned}}",
"conflict": "skip",
"manualOnly": false,
"when": { "all": [] }
}
]
}
Rules run from top to bottom. The first matching rule owns the file. Use nested condition groups:
{"all": [condition, condition]}
{"any": [condition, condition]}
{"not": condition}
A leaf condition has this format:
{"field": "title", "operator": "glob", "value": "Meeting *", "caseSensitive": false}
Supported fields:
- title
- path
- folder
- extension
- tag
- frontmatter, which requires a key such as "project.status"
- created
- modified
Supported operators:
- exists, not-exists
- equals, not-equals
- contains, not-contains
- starts-with, ends-with
- glob, regex
- in, with an array value
- greater-than, less-than
- before, after, with an ISO date value
String comparisons are case-insensitive unless caseSensitive is true. Glob supports the * wildcard.
Destination tokens:
- {{year}}, {{month}}, {{day}}
- {{title}}, {{extension}}
- {{property:key}}
- {{created:year}}, {{created:month}}, {{created:day}}
- {{modified:year}}, {{modified:month}}, {{modified:day}}
- Add a fallback with |, such as {{property:project|Unassigned}}
Use conflict "skip" to leave an existing destination untouched. Use conflict "suffix" to create a unique numbered filename. Set manualOnly to true for rules that must run only from Custodian's manual commands.
Keep existing rules unless the user asks to replace or remove them. Preserve unique IDs when editing existing rules. Do not invent fields, operators, tokens, comments, trailing commas, or executable code.
Current ruleset:
${JSON.stringify(ruleset, null, 2)}
User request follows:`;
}
// src/model.ts
var RULESET_VERSION = 1;
var FIELDS = [
"title",
"path",
"folder",
"extension",
"tag",
"frontmatter",
"created",
"modified"
];
var OPERATORS = [
"exists",
"not-exists",
"equals",
"not-equals",
"contains",
"not-contains",
"starts-with",
"ends-with",
"glob",
"regex",
"in",
"greater-than",
"less-than",
"before",
"after"
];
var DEFAULT_RULESET = {
version: RULESET_VERSION,
rules: []
};
var DEFAULT_SETTINGS = {
autoOrganize: true,
notifyOnMove: false,
excludedFolders: [".trash", "Templates"],
ruleset: DEFAULT_RULESET
};
// src/migration.ts
function escapeRegex(value) {
return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
}
function safeId(value, index, used) {
const base = (value != null ? value : "").trim().replace(/[^a-z0-9_-]+/gi, "-").replace(/^-+|-+$/g, "") || `migrated-${index + 1}`;
let candidate = base;
let suffix = 2;
while (used.has(candidate)) {
candidate = `${base}-${suffix}`;
suffix += 1;
}
used.add(candidate);
return candidate;
}
function migrateLegacyRule(rule, index, used) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
const conditions = [];
if ((_a = rule.titlePattern) == null ? void 0 : _a.trim()) conditions.push({ field: "title", operator: "glob", value: rule.titlePattern.trim() });
if ((_b = rule.frontmatterProperty) == null ? void 0 : _b.trim()) {
const operator = rule.frontmatterOperator === "not-exists" ? "not-exists" : rule.frontmatterOperator === "exists" ? "exists" : rule.frontmatterOperator === "contains" ? "contains" : "equals";
conditions.push({
field: "frontmatter",
key: rule.frontmatterProperty.trim(),
operator,
...operator === "exists" || operator === "not-exists" ? {} : { value: (_c = rule.frontmatterValue) != null ? _c : "" }
});
}
const tags = (_e = (_d = rule.tags) == null ? void 0 : _d.map((tag) => tag.replace(/^#/, "")).filter(Boolean)) != null ? _e : [];
if (tags.length > 0) {
const tagConditions = tags.map((tag) => ({ field: "tag", operator: "equals", value: tag }));
conditions.push(rule.tagMode === "all" ? { all: tagConditions } : { any: tagConditions });
}
const extensions = (_g = (_f = rule.extensions) == null ? void 0 : _f.map((extension) => extension.replace(/^\./, "")).filter(Boolean)) != null ? _g : [];
if (extensions.length > 0) conditions.push({ field: "extension", operator: "in", value: extensions });
if ((_h = rule.sourceFolder) == null ? void 0 : _h.trim()) {
const source = rule.sourceFolder.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
conditions.push({ field: "folder", operator: "regex", value: `^${escapeRegex(source)}(?:/|$)` });
}
return {
id: safeId(rule.id, index, used),
name: ((_i = rule.name) == null ? void 0 : _i.trim()) || `Migrated rule ${index + 1}`,
enabled: rule.enabled !== false,
destination: ((_j = rule.destination) == null ? void 0 : _j.trim()) || "Organized",
conflict: "skip",
when: conditions.length === 0 ? { field: "path", operator: "exists" } : { all: conditions }
};
}
function migrateLegacyRules(rules) {
const used = /* @__PURE__ */ new Set();
return { version: RULESET_VERSION, rules: rules.map((rule, index) => migrateLegacyRule(rule, index, used)) };
}
// src/rules.ts
var MAX_RULES = 250;
var MAX_CONDITION_DEPTH = 12;
var MAX_CONDITIONS_PER_RULE = 200;
var MAX_PATTERN_LENGTH = 250;
var MAX_REGEX_INPUT_LENGTH = 4096;
var MAX_RULESET_JSON_LENGTH = 524288;
function normalizeSlashes(value) {
return value.replace(/\\/g, "/").replace(/\/+/g, "/");
}
function normalizeFolder(value) {
const normalized2 = normalizeSlashes(value).trim().replace(/^\/+|\/+$/g, "");
const unsafeSegment = (part) => !part.trim() || part === "." || part === ".." || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(part);
if (!normalized2 || normalized2 === "." || /[:*?"<>|\u0000-\u001f]/.test(normalized2) || normalized2.split("/").some(unsafeSegment)) {
return null;
}
return normalized2;
}
function parentFolder(path) {
const index = path.lastIndexOf("/");
return index < 0 ? "" : path.slice(0, index);
}
function escapeRegExp(value) {
return value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
}
function matchesGlob(value, glob, caseSensitive) {
const expression = glob.split("*").map(escapeRegExp).join(".*");
return new RegExp(`^${expression}$`, caseSensitive ? "" : "i").test(value);
}
function readProperty(source, path) {
let current = source;
for (const segment of path.split(".").filter(Boolean)) {
if (!current || typeof current !== "object" || Array.isArray(current)) {
return { exists: false, value: void 0 };
}
const record = current;
if (!Object.prototype.hasOwnProperty.call(record, segment)) {
return { exists: false, value: void 0 };
}
current = record[segment];
}
return { exists: path.trim().length > 0, value: current };
}
function valuesOf(value) {
return Array.isArray(value) ? value : [value];
}
function normalized(value, caseSensitive) {
if (typeof value !== "string") return value;
return caseSensitive ? value : value.toLocaleLowerCase();
}
function equal(actual, expected, caseSensitive) {
if (typeof actual === "number" && typeof expected === "string" && expected.trim() !== "") {
return actual === Number(expected);
}
if (typeof actual === "boolean" && typeof expected === "string") {
return String(actual) === expected.toLocaleLowerCase();
}
return normalized(actual, caseSensitive) === normalized(expected, caseSensitive);
}
function compareStrings(actual, expected, caseSensitive, operation) {
if (typeof actual !== "string" || typeof expected !== "string") return false;
const left = caseSensitive ? actual : actual.toLocaleLowerCase();
const right = caseSensitive ? expected : expected.toLocaleLowerCase();
return operation(left, right);
}
function fieldValue(facts, condition) {
var _a;
switch (condition.field) {
case "title":
return { exists: true, value: facts.basename };
case "path":
return { exists: true, value: facts.path };
case "folder":
return { exists: true, value: parentFolder(facts.path) };
case "extension":
return { exists: true, value: facts.extension };
case "tag":
return { exists: facts.tags.length > 0, value: facts.tags.map((tag) => tag.replace(/^#/, "")) };
case "frontmatter":
return readProperty(facts.frontmatter, (_a = condition.key) != null ? _a : "");
case "created":
return { exists: true, value: facts.created };
case "modified":
return { exists: true, value: facts.modified };
}
}
function expectedValues(value) {
return value === void 0 ? [] : valuesOf(value);
}
function predicateMatches(facts, condition) {
const resolved = fieldValue(facts, condition);
if (condition.operator === "exists") return resolved.exists;
if (condition.operator === "not-exists") return !resolved.exists;
if (!resolved.exists) return false;
const actual = valuesOf(resolved.value);
const expected = expectedValues(condition.value);
const caseSensitive = condition.caseSensitive === true;
const anyPair = (test) => actual.some((left) => expected.some((right) => test(left, right)));
switch (condition.operator) {
case "equals":
return anyPair((left, right) => equal(left, right, caseSensitive));
case "not-equals":
return !anyPair((left, right) => equal(left, right, caseSensitive));
case "in":
return anyPair((left, right) => equal(left, right, caseSensitive));
case "contains":
return anyPair((left, right) => compareStrings(left, right, caseSensitive, (a, b) => a.includes(b)));
case "not-contains":
return !anyPair((left, right) => compareStrings(left, right, caseSensitive, (a, b) => a.includes(b)));
case "starts-with":
return anyPair((left, right) => compareStrings(left, right, caseSensitive, (a, b) => a.startsWith(b)));
case "ends-with":
return anyPair((left, right) => compareStrings(left, right, caseSensitive, (a, b) => a.endsWith(b)));
case "glob":
return anyPair((left, right) => typeof left === "string" && typeof right === "string" && matchesGlob(left, right, caseSensitive));
case "regex": {
return expected.some((pattern) => {
if (typeof pattern !== "string") return false;
try {
const expression = new RegExp(pattern, caseSensitive ? "" : "i");
return actual.some((value) => typeof value === "string" && expression.test(value.slice(0, MAX_REGEX_INPUT_LENGTH)));
} catch (e) {
return false;
}
});
}
case "greater-than":
return anyPair((left, right) => Number(left) > Number(right));
case "less-than":
return anyPair((left, right) => Number(left) < Number(right));
case "before":
return anyPair((left, right) => Number(left) < Date.parse(String(right)));
case "after":
return anyPair((left, right) => Number(left) > Date.parse(String(right)));
default:
return false;
}
}
function conditionMatches(facts, condition) {
if ("all" in condition) return condition.all.every((child) => conditionMatches(facts, child));
if ("any" in condition) return condition.any.some((child) => conditionMatches(facts, child));
if ("not" in condition) return !conditionMatches(facts, condition.not);
return predicateMatches(facts, condition);
}
function ruleMatches(facts, rule, automatic = false) {
return rule.enabled && !(automatic && rule.manualOnly) && conditionMatches(facts, rule.when);
}
function safeSegment(value) {
const text = Array.isArray(value) ? value.map(String).join("-") : String(value != null ? value : "");
return text.replace(/[\\/:*?"<>|#^[\]]/g, "-").replace(/\s+/g, " ").replace(/^\.+|\.+$/g, "").trim() || "Unassigned";
}
function datePart(timestamp, part) {
const date = new Date(timestamp);
if (Number.isNaN(date.getTime())) return null;
if (part === "year") return String(date.getFullYear());
if (part === "month") return String(date.getMonth() + 1).padStart(2, "0");
if (part === "day") return String(date.getDate()).padStart(2, "0");
return null;
}
function renderDestination(template, facts) {
const rendered = template.replace(/\{\{([^}]+)}}/g, (_match, rawToken) => {
const [rawName, rawFallback] = rawToken.split("|", 2);
const token = rawName.trim();
const fallback = (rawFallback == null ? void 0 : rawFallback.trim()) || "Unassigned";
let value;
if (token === "year") value = facts.now.getFullYear();
else if (token === "month") value = String(facts.now.getMonth() + 1).padStart(2, "0");
else if (token === "day") value = String(facts.now.getDate()).padStart(2, "0");
else if (token === "title") value = facts.basename;
else if (token === "extension") value = facts.extension.toLocaleLowerCase();
else if (token.startsWith("property:")) value = readProperty(facts.frontmatter, token.slice(9).trim()).value;
else if (token.startsWith("created:")) value = datePart(facts.created, token.slice(8).trim());
else if (token.startsWith("modified:")) value = datePart(facts.modified, token.slice(9).trim());
return safeSegment(value === void 0 || value === null || value === "" ? fallback : value);
});
return normalizeFolder(rendered);
}
function planMove(facts, rules, excludedFolders, automatic = false) {
const currentFolder = parentFolder(facts.path);
const excluded = excludedFolders.map((folder) => normalizeSlashes(folder).replace(/^\/+|\/+$/g, "")).filter(Boolean);
if (excluded.some((folder) => currentFolder === folder || currentFolder.startsWith(`${folder}/`))) return null;
const rule = rules.find((candidate) => ruleMatches(facts, candidate, automatic));
if (!rule) return null;
const destination = renderDestination(rule.destination, facts);
if (!destination || destination === currentFolder) return null;
const filename = facts.path.slice(facts.path.lastIndexOf("/") + 1);
return {
ruleId: rule.id,
ruleName: rule.name,
conflict: rule.conflict,
from: facts.path,
to: `${destination}/${filename}`
};
}
function isRecord(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function unknownKeys(record, allowed) {
return Object.keys(record).filter((key) => !allowed.includes(key));
}
function validateDestinationTemplate(template) {
if (typeof template !== "string") return "must be a string.";
if (template.length > 1e3) return "must not exceed 1000 characters.";
const tokenPattern = /\{\{([^}]+)}}/g;
let invalidToken = null;
const staticPath = template.replace(tokenPattern, (_match, rawToken) => {
const token = rawToken.split("|", 1)[0].trim();
const valid = ["year", "month", "day", "title", "extension"].includes(token) || /^property:\s*\S/.test(token) || /^(created|modified):(year|month|day)$/.test(token);
if (!valid) invalidToken = token;
return "Value";
});
if (invalidToken) return `contains unsupported token {{${invalidToken}}}.`;
if (staticPath.includes("{{") || staticPath.includes("}}")) return "contains malformed template braces.";
if (!normalizeFolder(staticPath)) return "must be a safe vault folder or template.";
return null;
}
function validateValue(value, path, errors) {
const primitive = (item) => ["string", "number", "boolean"].includes(typeof item);
if (primitive(value)) return;
if (!Array.isArray(value) || value.length === 0 || !value.every(primitive)) {
errors.push(`${path} must be a string, number, boolean, or non-empty array of those values.`);
return;
}
const types = new Set(value.map((item) => typeof item));
if (types.size > 1) errors.push(`${path} array values must use one data type.`);
}
function validateCondition(condition, path, depth, count, errors) {
count.value += 1;
if (depth > MAX_CONDITION_DEPTH) {
errors.push(`${path} exceeds the maximum nesting depth of ${MAX_CONDITION_DEPTH}.`);
return;
}
if (count.value > MAX_CONDITIONS_PER_RULE) {
errors.push(`${path} exceeds the maximum of ${MAX_CONDITIONS_PER_RULE} conditions per rule.`);
return;
}
if (!isRecord(condition)) {
errors.push(`${path} must be an object.`);
return;
}
const groupKeys = ["all", "any", "not"].filter((key) => key in condition);
if (groupKeys.length > 0) {
if (groupKeys.length !== 1 || "field" in condition || "operator" in condition) {
errors.push(`${path} must contain exactly one group operator.`);
return;
}
const key = groupKeys[0];
const extras2 = unknownKeys(condition, [key]);
if (extras2.length > 0) errors.push(`${path} contains unsupported keys: ${extras2.join(", ")}.`);
if (key === "not") {
validateCondition(condition.not, `${path}.not`, depth + 1, count, errors);
return;
}
const children = condition[key];
if (!Array.isArray(children) || children.length === 0) {
errors.push(`${path}.${key} must be a non-empty array.`);
return;
}
children.forEach((child, index) => validateCondition(child, `${path}.${key}[${index}]`, depth + 1, count, errors));
return;
}
const extras = unknownKeys(condition, ["field", "operator", "value", "key", "caseSensitive"]);
if (extras.length > 0) errors.push(`${path} contains unsupported keys: ${extras.join(", ")}.`);
if (!FIELDS.includes(condition.field)) errors.push(`${path}.field is not supported.`);
if (!OPERATORS.includes(condition.operator)) errors.push(`${path}.operator is not supported.`);
if (condition.field === "frontmatter" && (typeof condition.key !== "string" || !condition.key.trim())) {
errors.push(`${path}.key is required for frontmatter conditions.`);
}
if (condition.field !== "frontmatter" && condition.key !== void 0) {
errors.push(`${path}.key is supported only for frontmatter conditions.`);
}
if (condition.operator !== "exists" && condition.operator !== "not-exists" && condition.value === void 0) {
errors.push(`${path}.value is required for ${String(condition.operator)}.`);
}
if ((condition.operator === "exists" || condition.operator === "not-exists") && condition.value !== void 0) {
errors.push(`${path}.value must be omitted for ${String(condition.operator)}.`);
}
if (condition.operator === "in" && !Array.isArray(condition.value)) {
errors.push(`${path}.value must be an array for in.`);
}
if (condition.value !== void 0) validateValue(condition.value, `${path}.value`, errors);
if (condition.caseSensitive !== void 0 && typeof condition.caseSensitive !== "boolean") {
errors.push(`${path}.caseSensitive must be true or false.`);
}
if (typeof condition.value === "string" && condition.value.length > MAX_PATTERN_LENGTH) {
errors.push(`${path}.value exceeds ${MAX_PATTERN_LENGTH} characters.`);
}
if ((condition.operator === "greater-than" || condition.operator === "less-than") && valuesOf(condition.value).some((value) => typeof value === "boolean" || Number.isNaN(Number(value)))) {
errors.push(`${path}.value must contain numbers for ${String(condition.operator)}.`);
}
if ((condition.operator === "greater-than" || condition.operator === "less-than") && condition.field !== "frontmatter" && condition.field !== "created" && condition.field !== "modified") {
errors.push(`${path}.${String(condition.operator)} is supported only for frontmatter, created, or modified fields.`);
}
if ((condition.operator === "before" || condition.operator === "after") && condition.field !== "created" && condition.field !== "modified") {
errors.push(`${path}.${String(condition.operator)} is supported only for created or modified fields.`);
}
if (condition.operator === "regex") {
for (const pattern of valuesOf(condition.value)) {
if (typeof pattern !== "string") {
errors.push(`${path}.value must contain only strings for regex.`);
break;
}
try {
new RegExp(pattern);
} catch (e) {
errors.push(`${path}.value contains an invalid regular expression.`);
}
}
}
if ((condition.operator === "before" || condition.operator === "after") && valuesOf(condition.value).some((value) => Number.isNaN(Date.parse(String(value))))) {
errors.push(`${path}.value must contain valid ISO dates for ${String(condition.operator)}.`);
}
}
function validateRuleset(value) {
const errors = [];
if (!isRecord(value)) return { valid: false, errors: ["Ruleset must be a JSON object."] };
const rootExtras = unknownKeys(value, ["version", "rules"]);
if (rootExtras.length > 0) errors.push(`Ruleset contains unsupported keys: ${rootExtras.join(", ")}.`);
if (value.version !== RULESET_VERSION) errors.push(`version must be ${RULESET_VERSION}.`);
if (!Array.isArray(value.rules)) return { valid: false, errors: [...errors, "rules must be an array."] };
if (value.rules.length > MAX_RULES) errors.push(`rules exceeds the maximum of ${MAX_RULES}.`);
const ids = /* @__PURE__ */ new Set();
value.rules.forEach((rawRule, index) => {
const path = `rules[${index}]`;
if (!isRecord(rawRule)) {
errors.push(`${path} must be an object.`);
return;
}
const extras = unknownKeys(rawRule, ["id", "name", "enabled", "destination", "conflict", "manualOnly", "when"]);
if (extras.length > 0) errors.push(`${path} contains unsupported keys: ${extras.join(", ")}.`);
if (typeof rawRule.id !== "string" || rawRule.id.length > 100 || !/^[a-z0-9][a-z0-9_-]*$/i.test(rawRule.id)) errors.push(`${path}.id must use at most 100 letters, numbers, underscores, or hyphens.`);
else if (ids.has(rawRule.id)) errors.push(`${path}.id duplicates ${rawRule.id}.`);
else ids.add(rawRule.id);
if (typeof rawRule.name !== "string" || !rawRule.name.trim() || rawRule.name.length > 200) errors.push(`${path}.name is required and must not exceed 200 characters.`);
if (typeof rawRule.enabled !== "boolean") errors.push(`${path}.enabled must be true or false.`);
const destinationError = validateDestinationTemplate(rawRule.destination);
if (destinationError) errors.push(`${path}.destination ${destinationError}`);
if (rawRule.conflict !== "skip" && rawRule.conflict !== "suffix") errors.push(`${path}.conflict must be skip or suffix.`);
if (rawRule.manualOnly !== void 0 && typeof rawRule.manualOnly !== "boolean") errors.push(`${path}.manualOnly must be true or false.`);
validateCondition(rawRule.when, `${path}.when`, 0, { value: 0 }, errors);
});
return { valid: errors.length === 0, errors };
}
function parseRuleset(json) {
if (json.length > MAX_RULESET_JSON_LENGTH) {
return { errors: [`Ruleset JSON exceeds the ${MAX_RULESET_JSON_LENGTH} character limit.`] };
}
let value;
try {
value = JSON.parse(json);
} catch (error) {
return { errors: [`Invalid JSON: ${error instanceof Error ? error.message : String(error)}`] };
}
const validation = validateRuleset(value);
return validation.valid ? { ruleset: value, errors: [] } : { errors: validation.errors };
}
// src/main.ts
function splitList(value) {
return value.split(",").map((item) => item.trim()).filter(Boolean);
}
function clone(value) {
return JSON.parse(JSON.stringify(value));
}
var CustodianPlugin = class extends import_obsidian.Plugin {
constructor() {
super(...arguments);
__publicField(this, "settings", clone(DEFAULT_SETTINGS));
__publicField(this, "pending", /* @__PURE__ */ new Map());
__publicField(this, "suppressUntil", /* @__PURE__ */ new WeakMap());
__publicField(this, "autoMoveHistory", /* @__PURE__ */ new WeakMap());
__publicField(this, "blockedNoticeUntil", /* @__PURE__ */ new WeakMap());
__publicField(this, "moveQueue", Promise.resolve());
__publicField(this, "invalidRulesetDraft", null);
}
async onload() {
await this.loadSettings();
this.addSettingTab(new CustodianSettingTab(this.app, this));
this.addCommand({
id: "preview-file-organization",
name: "Preview file organization",
callback: () => this.previewAll()
});
this.addCommand({
id: "organize-all-files",
name: "Organize all files now",
callback: () => this.organizeAll()
});
this.addCommand({
id: "copy-rule-authoring-prompt",
name: "Copy rule-authoring prompt",
callback: () => this.copyRuleAuthoringPrompt(this.settings.ruleset)
});
this.registerEvent(this.app.vault.on("create", (file) => {
if (file instanceof import_obsidian.TFile) this.schedule(file);
}));
this.registerEvent(this.app.vault.on("rename", (file, oldPath) => {
const timeout = this.pending.get(oldPath);
if (timeout !== void 0) window.clearTimeout(timeout);
this.pending.delete(oldPath);
if (file instanceof import_obsidian.TFile) this.schedule(file);
}));
this.registerEvent(this.app.metadataCache.on("changed", (file) => this.schedule(file)));
}
onunload() {
for (const timeout of this.pending.values()) window.clearTimeout(timeout);
this.pending.clear();
}
async loadSettings() {
var _a, _b;
const saved = await this.loadData();
const defaults = clone(DEFAULT_SETTINGS);
let ruleset = defaults.ruleset;
let migrated = false;
if ((saved == null ? void 0 : saved.ruleset) && validateRuleset(saved.ruleset).valid) {
ruleset = saved.ruleset;
} else if (Array.isArray(saved == null ? void 0 : saved.rules)) {
ruleset = migrateLegacyRules(saved.rules);
migrated = true;
} else if (saved == null ? void 0 : saved.ruleset) {
this.invalidRulesetDraft = JSON.stringify(saved.ruleset, null, 2);
}
this.settings = {
autoOrganize: (_a = saved == null ? void 0 : saved.autoOrganize) != null ? _a : defaults.autoOrganize,
notifyOnMove: (_b = saved == null ? void 0 : saved.notifyOnMove) != null ? _b : defaults.notifyOnMove,
excludedFolders: Array.isArray(saved == null ? void 0 : saved.excludedFolders) ? saved.excludedFolders : defaults.excludedFolders,
ruleset
};
if (migrated) {
await this.saveSettings();
new import_obsidian.Notice("Custodian upgraded the existing rules to ruleset version 1.");
} else if ((saved == null ? void 0 : saved.ruleset) && !validateRuleset(saved.ruleset).valid) {
new import_obsidian.Notice("Custodian found an invalid saved ruleset and loaded the safe default. Open settings to repair it.");
}
}
async saveSettings() {
await this.saveData(this.settings);
}
rulesetEditorText() {
var _a;
return (_a = this.invalidRulesetDraft) != null ? _a : JSON.stringify(this.settings.ruleset, null, 2);
}
async saveRuleset(ruleset) {
this.settings.ruleset = ruleset;
this.invalidRulesetDraft = null;
await this.saveSettings();
}
async copyRuleAuthoringPrompt(ruleset) {
try {
await navigator.clipboard.writeText(buildRuleAuthoringPrompt(ruleset));
new import_obsidian.Notice("Custodian rule-authoring prompt copied.");
} catch (error) {
console.error("Custodian could not copy the rule-authoring prompt", error);
new import_obsidian.Notice("Custodian could not access the clipboard.");
}
}
schedule(file) {
var _a;
if (!this.settings.autoOrganize || Date.now() < ((_a = this.suppressUntil.get(file)) != null ? _a : 0)) return;
const existing = this.pending.get(file.path);
if (existing !== void 0) window.clearTimeout(existing);
const timeout = window.setTimeout(() => {
this.pending.delete(file.path);
const current = this.app.vault.getAbstractFileByPath(file.path);
if (current instanceof import_obsidian.TFile) this.enqueueOrganization(current);
}, 750);
this.pending.set(file.path, timeout);
}
enqueueOrganization(file) {
this.moveQueue = this.moveQueue.then(async () => {
await this.organizeFile(file, true);
}).catch((error) => {
console.error("Custodian automatic organization failed", error);
});
}
factsFor(file) {
var _a, _b;
const cache = this.app.metadataCache.getFileCache(file);
return {
path: file.path,
basename: file.basename,
extension: file.extension,
frontmatter: (_a = cache == null ? void 0 : cache.frontmatter) != null ? _a : {},
tags: cache ? (_b = (0, import_obsidian.getAllTags)(cache)) != null ? _b : [] : [],
created: file.stat.ctime,
modified: file.stat.mtime,
now: /* @__PURE__ */ new Date()
};
}
planFor(file, automatic) {
return planMove(
this.factsFor(file),
this.settings.ruleset.rules,
this.settings.excludedFolders,
automatic
);
}
async ensureFolder(folder) {
const parts = (0, import_obsidian.normalizePath)(folder).split("/");
let current = "";
for (const part of parts) {
current = current ? `${current}/${part}` : part;
if (!this.app.vault.getAbstractFileByPath(current)) await this.app.vault.createFolder(current);
}
}
uniqueDestination(path) {
if (!this.app.vault.getAbstractFileByPath(path)) return path;
const slash = path.lastIndexOf("/");
const folder = slash < 0 ? "" : path.slice(0, slash + 1);
const filename = slash < 0 ? path : path.slice(slash + 1);
const dot = filename.lastIndexOf(".");
const basename = dot > 0 ? filename.slice(0, dot) : filename;
const extension = dot > 0 ? filename.slice(dot) : "";
for (let index = 1; index <= 9999; index += 1) {
const candidate = `${folder}${basename} (${index})${extension}`;
if (!this.app.vault.getAbstractFileByPath(candidate)) return candidate;
}
return null;
}
autoMoveAllowed(file) {
var _a, _b;
const now = Date.now();
const recent = ((_a = this.autoMoveHistory.get(file)) != null ? _a : []).filter((time) => now - time < 6e4);
this.autoMoveHistory.set(file, recent);
if (recent.length < 3) return true;
if (now >= ((_b = this.blockedNoticeUntil.get(file)) != null ? _b : 0)) {
this.blockedNoticeUntil.set(file, now + 6e4);
new import_obsidian.Notice(`Custodian stopped repeated moves for ${file.name}. Review overlapping rules.`);
}
return false;
}
async applyPlan(file, plan, automatic) {
var _a;
if (automatic && !this.autoMoveAllowed(file)) return false;
const destination = plan.conflict === "suffix" ? this.uniqueDestination(plan.to) : this.app.vault.getAbstractFileByPath(plan.to) ? null : plan.to;
if (!destination) {
new import_obsidian.Notice(`Custodian skipped ${plan.from}: the destination is unavailable.`);
return false;
}
const destinationFolder = destination.slice(0, destination.lastIndexOf("/"));
const originalPath = file.path;
this.suppressUntil.set(file, Date.now() + 3e3);
try {
await this.ensureFolder(destinationFolder);
await this.app.fileManager.renameFile(file, destination);
if (automatic) {
const history = (_a = this.autoMoveHistory.get(file)) != null ? _a : [];
history.push(Date.now());
this.autoMoveHistory.set(file, history);
}
if (this.settings.notifyOnMove) new import_obsidian.Notice(`Custodian moved ${originalPath} to ${destination}.`);
return true;
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
console.error("Custodian could not move a file", error);
new import_obsidian.Notice(`Custodian could not move ${originalPath}: ${detail}`);
return false;
}
}
async organizeFile(file, automatic) {
const plan = this.planFor(file, automatic);
return plan ? this.applyPlan(file, plan, automatic) : false;
}
plansForVault() {
return this.app.vault.getFiles().map((file) => this.planFor(file, false)).filter((plan) => plan !== null);
}
previewAll() {
new PreviewModal(this.app, this.plansForVault()).open();
}
async organizeAll() {
await this.moveQueue;
const planned = this.plansForVault();
if (planned.length === 0) {
new import_obsidian.Notice("Custodian: every file is already in place.");
return;
}
let moved = 0;
let pending = [...planned];
while (pending.length > 0) {
const sources = new Set(pending.map((plan) => plan.from));
const deferred = [];
let processed = 0;
for (const plan of pending) {
if (this.app.vault.getAbstractFileByPath(plan.to) && sources.has(plan.to)) {
deferred.push(plan);
continue;
}
const file = this.app.vault.getAbstractFileByPath(plan.from);
if (file instanceof import_obsidian.TFile && await this.applyPlan(file, plan, false)) moved += 1;
processed += 1;
}
if (processed === 0) {
for (const plan of deferred) {
const file = this.app.vault.getAbstractFileByPath(plan.from);
if (file instanceof import_obsidian.TFile && await this.applyPlan(file, plan, false)) moved += 1;
}
break;
}
pending = deferred;
}
new import_obsidian.Notice(`Custodian moved ${moved} of ${planned.length} planned files.`);
}
};
var PreviewModal = class extends import_obsidian.Modal {
constructor(app, plans) {
super(app);
this.plans = plans;
}
onOpen() {
this.titleEl.setText("Custodian preview");
if (this.plans.length === 0) {
this.contentEl.createEl("p", { text: "Every file is already in place." });
return;
}
this.contentEl.createEl("p", {
text: `${this.plans.length} file${this.plans.length === 1 ? "" : "s"} would move. No changes have been made.`
});
const list = this.contentEl.createEl("ul", { cls: "custodian-preview" });
for (const plan of this.plans) list.createEl("li", { text: `${plan.from} to ${plan.to} (${plan.ruleName})` });
}
};
var CustodianSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Custodian" });
new import_obsidian.Setting(containerEl).setName("Automatic organization").setDesc("Evaluate files after they are created, renamed, or their metadata changes.").addToggle((toggle) => toggle.setValue(this.plugin.settings.autoOrganize).onChange(async (value) => {
this.plugin.settings.autoOrganize = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Move notifications").setDesc("Show a notice after each automatic move.").addToggle((toggle) => toggle.setValue(this.plugin.settings.notifyOnMove).onChange(async (value) => {
this.plugin.settings.notifyOnMove = value;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Excluded folders").setDesc("Comma-separated folders that Custodian will never move files out of.").addText((text) => text.setPlaceholder(".trash, Templates").setValue(this.plugin.settings.excludedFolders.join(", ")).onChange(async (value) => {
this.plugin.settings.excludedFolders = splitList(value);
await this.plugin.saveSettings();
}));
containerEl.createEl("h3", { text: "Ruleset JSON" });
containerEl.createEl("p", {
text: "Edit the complete ruleset below, or copy the authoring prompt and give it to an assistant with your filing request. Paste the returned JSON here, then validate and save."
});
let editorValue = this.plugin.rulesetEditorText();
let editorInput;
const editorSetting = new import_obsidian.Setting(containerEl).setClass("custodian-ruleset-setting");
editorSetting.addTextArea((text) => {
editorInput = text.inputEl;
text.setValue(editorValue).onChange((value) => {
editorValue = value;
});
text.inputEl.rows = 24;
text.inputEl.spellcheck = false;
text.inputEl.setAttribute("aria-label", "Custodian ruleset JSON");
});
const status = containerEl.createEl("p", { cls: "custodian-validation-status" });
status.setText("Saved ruleset is valid.");
new import_obsidian.Setting(containerEl).addButton((button) => button.setButtonText("Validate and save").setCta().onClick(async () => {
const parsed = parseRuleset(editorValue);
if (!parsed.ruleset) {
status.setText(parsed.errors.slice(0, 8).join(" "));
status.addClass("custodian-validation-status--error");
new import_obsidian.Notice(`Custodian found ${parsed.errors.length} ruleset error${parsed.errors.length === 1 ? "" : "s"}.`);
return;
}
await this.plugin.saveRuleset(parsed.ruleset);
editorValue = JSON.stringify(parsed.ruleset, null, 2);
editorInput.value = editorValue;
status.removeClass("custodian-validation-status--error");
status.setText(`Saved ${parsed.ruleset.rules.length} validated rule${parsed.ruleset.rules.length === 1 ? "" : "s"}.`);
new import_obsidian.Notice("Custodian ruleset saved.");
})).addButton((button) => button.setButtonText("Reset editor").onClick(() => {
editorValue = JSON.stringify(this.plugin.settings.ruleset, null, 2);
editorInput.value = editorValue;
status.removeClass("custodian-validation-status--error");
status.setText("Editor reset to the saved ruleset.");
})).addButton((button) => button.setButtonText("Copy authoring prompt").onClick(async () => {
var _a;
const parsed = parseRuleset(editorValue);
await this.plugin.copyRuleAuthoringPrompt((_a = parsed.ruleset) != null ? _a : this.plugin.settings.ruleset);
}));
containerEl.createEl("p", {
cls: "custodian-rule-help",
text: "Rules run from top to bottom. The first match wins. Nested all, any, and not groups are supported. Invalid JSON never replaces the saved ruleset."
});
}
};