ownledger 0.0.0-stage → 1.0.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.
Files changed (94) hide show
  1. package/AGENTS.md +93 -0
  2. package/CHANGELOG.md +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +102 -2
  5. package/assets/_headers +5 -0
  6. package/assets/app.css +61 -0
  7. package/assets/app.js +369 -0
  8. package/assets/icon.svg +1 -0
  9. package/assets/index.html +30 -0
  10. package/assets/manifest.webmanifest +1 -0
  11. package/dist/cli/check.d.ts +3 -0
  12. package/dist/cli/check.js +21 -0
  13. package/dist/cli/deploy.d.ts +1 -0
  14. package/dist/cli/deploy.js +258 -0
  15. package/dist/cli/dev.d.ts +3 -0
  16. package/dist/cli/dev.js +107 -0
  17. package/dist/cli/import.d.ts +3 -0
  18. package/dist/cli/import.js +151 -0
  19. package/dist/cli/index.d.ts +2 -0
  20. package/dist/cli/index.js +47 -0
  21. package/dist/cli/init.d.ts +1 -0
  22. package/dist/cli/init.js +73 -0
  23. package/dist/cli/jsonc.d.ts +2 -0
  24. package/dist/cli/jsonc.js +39 -0
  25. package/dist/engine/actions.d.ts +53 -0
  26. package/dist/engine/actions.js +205 -0
  27. package/dist/engine/balances.d.ts +30 -0
  28. package/dist/engine/balances.js +75 -0
  29. package/dist/engine/categories.d.ts +17 -0
  30. package/dist/engine/categories.js +35 -0
  31. package/dist/engine/check.d.ts +11 -0
  32. package/dist/engine/check.js +220 -0
  33. package/dist/engine/dates.d.ts +15 -0
  34. package/dist/engine/dates.js +56 -0
  35. package/dist/engine/defaults.d.ts +2 -0
  36. package/dist/engine/defaults.js +61 -0
  37. package/dist/engine/index.d.ts +13 -0
  38. package/dist/engine/index.js +13 -0
  39. package/dist/engine/load.d.ts +23 -0
  40. package/dist/engine/load.js +129 -0
  41. package/dist/engine/networth.d.ts +12 -0
  42. package/dist/engine/networth.js +73 -0
  43. package/dist/engine/registry.d.ts +24 -0
  44. package/dist/engine/registry.js +41 -0
  45. package/dist/engine/reports.d.ts +68 -0
  46. package/dist/engine/reports.js +149 -0
  47. package/dist/engine/schedules.d.ts +75 -0
  48. package/dist/engine/schedules.js +208 -0
  49. package/dist/engine/types.d.ts +122 -0
  50. package/dist/engine/types.js +2 -0
  51. package/dist/engine/write.d.ts +30 -0
  52. package/dist/engine/write.js +105 -0
  53. package/dist/import/hash.d.ts +1 -0
  54. package/dist/import/hash.js +17 -0
  55. package/dist/import/index.d.ts +6 -0
  56. package/dist/import/index.js +6 -0
  57. package/dist/import/mapping.d.ts +96 -0
  58. package/dist/import/mapping.js +54 -0
  59. package/dist/import/profile.d.ts +39 -0
  60. package/dist/import/profile.js +125 -0
  61. package/dist/import/run.d.ts +101 -0
  62. package/dist/import/run.js +416 -0
  63. package/dist/import/workbook.d.ts +13 -0
  64. package/dist/import/workbook.js +168 -0
  65. package/dist/import/xlsx-write.d.ts +6 -0
  66. package/dist/import/xlsx-write.js +38 -0
  67. package/dist/node/files.d.ts +3 -0
  68. package/dist/node/files.js +26 -0
  69. package/dist/node/scaffold.d.ts +14 -0
  70. package/dist/node/scaffold.js +45 -0
  71. package/dist/worker/api.d.ts +3 -0
  72. package/dist/worker/api.js +139 -0
  73. package/dist/worker/auth.d.ts +11 -0
  74. package/dist/worker/auth.js +176 -0
  75. package/dist/worker/env.d.ts +25 -0
  76. package/dist/worker/env.js +6 -0
  77. package/dist/worker/github.d.ts +29 -0
  78. package/dist/worker/github.js +154 -0
  79. package/dist/worker/index.d.ts +5 -0
  80. package/dist/worker/index.js +64 -0
  81. package/dist/worker/mcp.d.ts +4 -0
  82. package/dist/worker/mcp.js +292 -0
  83. package/dist/worker/store.d.ts +42 -0
  84. package/dist/worker/store.js +92 -0
  85. package/dist/worker/tar.d.ts +2 -0
  86. package/dist/worker/tar.js +62 -0
  87. package/dist/worker/version.d.ts +1 -0
  88. package/dist/worker/version.js +2 -0
  89. package/package.json +68 -4
  90. package/presets/misa.mapping.yaml +48 -0
  91. package/templates/repo/.github/dependabot.yml +11 -0
  92. package/templates/repo/.github/workflows/check.yml +15 -0
  93. package/templates/repo/.github/workflows/deploy.yml +21 -0
  94. package/templates/repo/README.md +10 -0
@@ -0,0 +1,39 @@
1
+ /** JSON with comments and trailing commas (wrangler.jsonc). */
2
+ export function parse(text) {
3
+ let out = "";
4
+ let i = 0;
5
+ let inStr = false;
6
+ while (i < text.length) {
7
+ const ch = text[i];
8
+ if (inStr) {
9
+ out += ch;
10
+ if (ch === "\\") {
11
+ out += text[i + 1] ?? "";
12
+ i += 2;
13
+ continue;
14
+ }
15
+ if (ch === '"')
16
+ inStr = false;
17
+ i++;
18
+ continue;
19
+ }
20
+ if (ch === '"') {
21
+ inStr = true;
22
+ out += ch;
23
+ i++;
24
+ }
25
+ else if (ch === "/" && text[i + 1] === "/") {
26
+ while (i < text.length && text[i] !== "\n")
27
+ i++;
28
+ }
29
+ else if (ch === "/" && text[i + 1] === "*") {
30
+ i = text.indexOf("*/", i + 2);
31
+ i = i < 0 ? text.length : i + 2;
32
+ }
33
+ else {
34
+ out += ch;
35
+ i++;
36
+ }
37
+ }
38
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
39
+ }
@@ -0,0 +1,53 @@
1
+ import { type FileMap } from "./load.js";
2
+ import { type Change } from "./write.js";
3
+ import type { Account, Issue, Line, Plan, Price } from "./types.js";
4
+ /**
5
+ * Write actions: each builds a Change from a request, applies it in memory and checks the result.
6
+ * Nothing is committed here; the caller previews, gets the owner's go, then commits.
7
+ */
8
+ export interface Planned {
9
+ change: Change;
10
+ files: FileMap;
11
+ summary: string[];
12
+ message: string;
13
+ warnings: Issue[];
14
+ }
15
+ export declare class ActionError extends Error {
16
+ }
17
+ export declare function plan(files: FileMap, change: Change, message: string): Planned;
18
+ export interface SimpleTx {
19
+ date: string;
20
+ time?: string | null;
21
+ note?: string;
22
+ who?: string | null;
23
+ event?: string | null;
24
+ tags?: string[];
25
+ plan?: string | null;
26
+ /** Full form: balanced lines. */
27
+ lines?: Line[];
28
+ /** Simple forms (when lines is not given): */
29
+ kind?: "expense" | "income" | "transfer";
30
+ amount?: number;
31
+ account?: string;
32
+ to_account?: string;
33
+ category?: string;
34
+ }
35
+ export declare function linesOf(t: SimpleTx): Line[];
36
+ export declare function addTransaction(files: FileMap, t: SimpleTx): Planned;
37
+ export declare function editTransaction(files: FileMap, id: string, patch: Partial<SimpleTx>): Planned;
38
+ export declare function voidTransaction(files: FileMap, id: string, reason?: string): Planned;
39
+ export declare function addAccount(files: FileMap, a: Account): Planned;
40
+ export declare function editAccount(files: FileMap, id: string, set: Record<string, unknown>): Planned;
41
+ export declare function addPlan(files: FileMap, p: Plan): Planned;
42
+ export declare function addPrice(files: FileMap, p: Price): Planned;
43
+ export declare function addCategory(files: FileMap, c: {
44
+ kind: "income" | "expense";
45
+ parent?: string;
46
+ id: string;
47
+ name: string;
48
+ }): Planned;
49
+ /** Rename a category (name), or move/rename its path and remap every line that uses it (or its children). */
50
+ export declare function editCategory(files: FileMap, path: string, set: {
51
+ name?: string;
52
+ new_path?: string;
53
+ }): Planned;
@@ -0,0 +1,205 @@
1
+ import { parse as parseYaml, stringify } from "yaml";
2
+ import { checkFiles } from "./check.js";
3
+ import { flattenCategories } from "./categories.js";
4
+ import { isDate } from "./dates.js";
5
+ import { LEDGER_FILE_RE, loadLedger, parseJsonl, PATHS } from "./load.js";
6
+ import { applyChange, describeChange } from "./write.js";
7
+ export class ActionError extends Error {
8
+ }
9
+ function newId(prefix = "t_") {
10
+ const b = new Uint8Array(7);
11
+ crypto.getRandomValues(b);
12
+ return prefix + [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
13
+ }
14
+ export function plan(files, change, message) {
15
+ const out = applyChange(files, change);
16
+ const r = checkFiles({ ...files, ...out });
17
+ if (!r.ok)
18
+ throw new ActionError(`refused, the result would not pass check:\n${r.errors.slice(0, 10).map((e) => `- ${e.where ? `[${e.where}] ` : ""}${e.message}`).join("\n")}`);
19
+ const before = new Set(checkFiles(files).warnings.map((w) => `${w.file}|${w.where}|${w.message}`));
20
+ return {
21
+ change,
22
+ files: out,
23
+ summary: describeChange(change),
24
+ message,
25
+ warnings: r.warnings.filter((w) => !before.has(`${w.file}|${w.where}|${w.message}`)),
26
+ };
27
+ }
28
+ export function linesOf(t) {
29
+ if (t.lines?.length)
30
+ return t.lines;
31
+ const a = t.amount;
32
+ if (!a || !Number.isInteger(a) || a <= 0)
33
+ throw new ActionError("amount must be a positive whole number (base currency)");
34
+ if (!t.account)
35
+ throw new ActionError("account is required");
36
+ if (t.kind === "transfer") {
37
+ if (!t.to_account)
38
+ throw new ActionError("to_account is required for a transfer");
39
+ return [{ account: t.account, amount: -a }, { account: t.to_account, amount: a }];
40
+ }
41
+ if (!t.category)
42
+ throw new ActionError("category is required for an expense or income");
43
+ return t.kind === "income"
44
+ ? [{ account: t.account, amount: a }, { category: t.category, amount: -a }]
45
+ : [{ account: t.account, amount: -a }, { category: t.category, amount: a }];
46
+ }
47
+ export function addTransaction(files, t) {
48
+ if (!isDate(t.date))
49
+ throw new ActionError("date must be yyyy-mm-dd");
50
+ const tx = {
51
+ id: newId(),
52
+ date: t.date,
53
+ ...(t.time ? { time: t.time } : {}),
54
+ note: t.note ?? "",
55
+ ...(t.who ? { who: t.who } : {}),
56
+ ...(t.event ? { event: t.event } : {}),
57
+ ...(t.tags?.length ? { tags: t.tags } : {}),
58
+ ...(t.plan ? { plan: t.plan } : {}),
59
+ lines: linesOf(t),
60
+ };
61
+ return plan(files, { addTransactions: [tx] }, `Add: ${t.date} ${t.note ?? ""}`.trim());
62
+ }
63
+ function findTx(files, id) {
64
+ for (const [p, text] of Object.entries(files)) {
65
+ if (!LEDGER_FILE_RE.test(p) || !text.includes(`"${id}"`))
66
+ continue;
67
+ const t = parseJsonl(text, p, []).find((x) => x.id === id);
68
+ if (t)
69
+ return t;
70
+ }
71
+ throw new ActionError(`no transaction ${id}`);
72
+ }
73
+ export function editTransaction(files, id, patch) {
74
+ const old = findTx(files, id);
75
+ const next = { ...old };
76
+ for (const k of ["date", "time", "note", "who", "event", "tags", "plan"]) {
77
+ if (patch[k] !== undefined)
78
+ next[k] = patch[k];
79
+ }
80
+ if (patch.lines || patch.amount || patch.kind || patch.account || patch.category || patch.to_account) {
81
+ next.lines = linesOf({ ...simpleOf(old), ...patch });
82
+ }
83
+ if (!isDate(next.date))
84
+ throw new ActionError("date must be yyyy-mm-dd");
85
+ return plan(files, { replaceTransactions: [next] }, `Edit: ${next.date} ${next.note ?? ""}`.trim());
86
+ }
87
+ /** Best-effort simple view of a transaction (to let an edit change just one field). */
88
+ function simpleOf(t) {
89
+ const acc = t.lines.filter((l) => l.account);
90
+ const cat = t.lines.filter((l) => l.category);
91
+ if (t.lines.length === 2 && acc.length === 1 && cat.length === 1) {
92
+ const a = acc[0];
93
+ return { kind: a.amount < 0 ? "expense" : "income", amount: Math.abs(a.amount), account: a.account, category: cat[0].category };
94
+ }
95
+ if (t.lines.length === 2 && acc.length === 2) {
96
+ const from = acc.find((l) => l.amount < 0);
97
+ const to = acc.find((l) => l.amount > 0);
98
+ return { kind: "transfer", amount: to.amount, account: from.account, to_account: to.account };
99
+ }
100
+ return { lines: t.lines };
101
+ }
102
+ export function voidTransaction(files, id, reason) {
103
+ const old = findTx(files, id);
104
+ if (old.void)
105
+ throw new ActionError(`${id} is already void`);
106
+ const next = { ...old, void: true, ...(reason ? { void_reason: reason } : {}) };
107
+ return plan(files, { replaceTransactions: [next] }, `Void: ${old.date} ${old.note ?? ""}`.trim());
108
+ }
109
+ /* ------------------------------------------------------------------ accounts, plans, prices */
110
+ export function addAccount(files, a) {
111
+ return plan(files, { addAccounts: [a] }, `Add account: ${a.name} (${a.type})`);
112
+ }
113
+ export function editAccount(files, id, set) {
114
+ const { ledger } = loadLedger(files);
115
+ if (!ledger.accounts.some((a) => a.id === id))
116
+ throw new ActionError(`no account ${id}`);
117
+ if ("id" in set)
118
+ throw new ActionError("an account id can't be changed");
119
+ return plan(files, { updateAccounts: [{ id, set }] }, set.closed ? `Close account: ${id}` : `Edit account: ${id}`);
120
+ }
121
+ export function addPlan(files, p) {
122
+ const { ledger } = loadLedger(files);
123
+ if (ledger.plans.some((x) => x.id === p.id))
124
+ throw new ActionError(`plan ${p.id} exists`);
125
+ return plan(files, { upsertList: [{ path: PATHS.plans, items: [p] }] }, `Add plan: ${p.name ?? p.id}`);
126
+ }
127
+ export function addPrice(files, p) {
128
+ return plan(files, { addPrices: [p] }, `Price: ${p.asset} ${p.date}`);
129
+ }
130
+ /* ------------------------------------------------------------------ categories */
131
+ function readCats(files) {
132
+ const v = parseYaml(files[PATHS.categories] ?? "");
133
+ return { income: v?.income ?? [], expense: v?.expense ?? [] };
134
+ }
135
+ function nodeAt(cats, path) {
136
+ const parts = path.split("/");
137
+ for (const kind of ["income", "expense"]) {
138
+ let list = cats[kind];
139
+ for (let i = 0; i < parts.length; i++) {
140
+ const n = list.find((x) => x.id === parts[i]);
141
+ if (!n)
142
+ break;
143
+ if (i === parts.length - 1)
144
+ return { list, node: n };
145
+ list = n.children ??= [];
146
+ }
147
+ }
148
+ return null;
149
+ }
150
+ export function addCategory(files, c) {
151
+ const cats = readCats(files);
152
+ let list = cats[c.kind];
153
+ if (c.parent) {
154
+ const p = nodeAt(cats, c.parent);
155
+ if (!p)
156
+ throw new ActionError(`no category ${c.parent}`);
157
+ list = p.node.children ??= [];
158
+ }
159
+ if (list.some((x) => x.id === c.id))
160
+ throw new ActionError(`category ${c.parent ? c.parent + "/" : ""}${c.id} exists`);
161
+ list.push({ id: c.id, name: c.name });
162
+ return plan(files, { putFiles: { [PATHS.categories]: stringify(cats, { lineWidth: 0 }) } }, `Add category: ${c.parent ? c.parent + "/" : ""}${c.id}`);
163
+ }
164
+ /** Rename a category (name), or move/rename its path and remap every line that uses it (or its children). */
165
+ export function editCategory(files, path, set) {
166
+ const cats = readCats(files);
167
+ const at = nodeAt(cats, path);
168
+ if (!at)
169
+ throw new ActionError(`no category ${path}`);
170
+ if (set.name)
171
+ at.node.name = set.name;
172
+ const change = {};
173
+ if (set.new_path && set.new_path !== path) {
174
+ const { map } = flattenCategories(cats);
175
+ if (map.has(set.new_path))
176
+ throw new ActionError(`category ${set.new_path} exists; merging is not supported here`);
177
+ const kind = map.get(path).kind;
178
+ at.list.splice(at.list.indexOf(at.node), 1);
179
+ const parts = set.new_path.split("/");
180
+ const leaf = parts.pop();
181
+ let list = cats[kind];
182
+ if (parts.length) {
183
+ const p = nodeAt(cats, parts.join("/"));
184
+ if (!p)
185
+ throw new ActionError(`no parent category ${parts.join("/")}`);
186
+ list = p.node.children ??= [];
187
+ }
188
+ list.push({ ...at.node, id: leaf });
189
+ const remap = (c) => (c === path ? set.new_path : c.startsWith(path + "/") ? set.new_path + c.slice(path.length) : c);
190
+ const replace = [];
191
+ for (const t of loadLedger(files).ledger.transactions) {
192
+ if (!t.lines.some((l) => l.category && remap(l.category) !== l.category))
193
+ continue;
194
+ replace.push({ ...t, lines: t.lines.map((l) => (l.category ? { ...l, category: remap(l.category) } : l)) });
195
+ }
196
+ if (replace.length)
197
+ change.replaceTransactions = replace;
198
+ const budgets = parseYaml(files[PATHS.budgets] ?? "[]");
199
+ if (budgets?.some((b) => remap(b.category) !== b.category)) {
200
+ change.putFiles = { [PATHS.budgets]: stringify(budgets.map((b) => ({ ...b, category: remap(b.category) })), { lineWidth: 0 }) };
201
+ }
202
+ }
203
+ change.putFiles = { ...(change.putFiles ?? {}), [PATHS.categories]: stringify(cats, { lineWidth: 0 }) };
204
+ return plan(files, change, set.new_path ? `Move category: ${path} → ${set.new_path}` : `Rename category: ${path}`);
205
+ }
@@ -0,0 +1,30 @@
1
+ import type { Account, ISODate, Ledger, Price, Transaction } from "./types.js";
2
+ export interface Holding {
3
+ /** Sum of line amounts (base currency). For base-currency accounts this is the balance; for holdings it is the net cost. */
4
+ amount: number;
5
+ /** Sum of qty (non-base assets only). */
6
+ qty: number;
7
+ }
8
+ export declare function live(l: Ledger): Transaction[];
9
+ /** Balances of every account at the end of `asOf` (inclusive). Accounts with no lines are 0. */
10
+ export declare function holdingsAt(l: Ledger, asOf?: ISODate): Map<string, Holding>;
11
+ export declare class PriceBook {
12
+ private by;
13
+ constructor(prices: Price[]);
14
+ /** Latest price on or before `date`, or undefined. */
15
+ at(asset: string, date: ISODate): Price | undefined;
16
+ }
17
+ export interface AccountValue {
18
+ account: Account;
19
+ asset: string;
20
+ /** Value in base currency: balance for base accounts; qty × latest price for holdings (net cost if no price). */
21
+ value: number;
22
+ /** Net cost (sum of amounts). */
23
+ cost: number;
24
+ qty: number | null;
25
+ price: Price | null;
26
+ priced: boolean;
27
+ }
28
+ export declare function valueAccount(l: Ledger, a: Account, h: Holding, prices: PriceBook, asOf: ISODate): AccountValue;
29
+ export declare function accountValues(l: Ledger, asOf: ISODate): AccountValue[];
30
+ export declare function isLiabilityType(type: string): boolean;
@@ -0,0 +1,75 @@
1
+ import { typeDef } from "./registry.js";
2
+ export function live(l) {
3
+ return l.transactions.filter((t) => !t.void);
4
+ }
5
+ /** Balances of every account at the end of `asOf` (inclusive). Accounts with no lines are 0. */
6
+ export function holdingsAt(l, asOf) {
7
+ const out = new Map();
8
+ for (const a of l.accounts)
9
+ out.set(a.id, { amount: 0, qty: 0 });
10
+ for (const t of l.transactions) {
11
+ if (t.void)
12
+ continue;
13
+ if (asOf && t.date > asOf)
14
+ break; // sorted by date
15
+ for (const ln of t.lines) {
16
+ if (ln.account == null)
17
+ continue;
18
+ const h = out.get(ln.account) ?? { amount: 0, qty: 0 };
19
+ h.amount += ln.amount;
20
+ if (typeof ln.qty === "number")
21
+ h.qty += ln.qty;
22
+ out.set(ln.account, h);
23
+ }
24
+ }
25
+ return out;
26
+ }
27
+ export class PriceBook {
28
+ by = new Map();
29
+ constructor(prices) {
30
+ for (const p of prices) {
31
+ const arr = this.by.get(p.asset) ?? [];
32
+ arr.push(p);
33
+ this.by.set(p.asset, arr);
34
+ }
35
+ for (const arr of this.by.values())
36
+ arr.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
37
+ }
38
+ /** Latest price on or before `date`, or undefined. */
39
+ at(asset, date) {
40
+ const arr = this.by.get(asset);
41
+ if (!arr)
42
+ return undefined;
43
+ let lo = 0;
44
+ let hi = arr.length - 1;
45
+ let found;
46
+ while (lo <= hi) {
47
+ const mid = (lo + hi) >> 1;
48
+ if (arr[mid].date <= date) {
49
+ found = arr[mid];
50
+ lo = mid + 1;
51
+ }
52
+ else
53
+ hi = mid - 1;
54
+ }
55
+ return found;
56
+ }
57
+ }
58
+ export function valueAccount(l, a, h, prices, asOf) {
59
+ const base = l.meta.base;
60
+ const asset = a.asset ?? base;
61
+ if (asset === base)
62
+ return { account: a, asset, value: h.amount, cost: h.amount, qty: null, price: null, priced: true };
63
+ const p = prices.at(asset, asOf);
64
+ if (!p)
65
+ return { account: a, asset, value: h.amount, cost: h.amount, qty: h.qty, price: null, priced: false };
66
+ return { account: a, asset, value: Math.round(h.qty * p.price), cost: h.amount, qty: h.qty, price: p, priced: true };
67
+ }
68
+ export function accountValues(l, asOf) {
69
+ const hs = holdingsAt(l, asOf);
70
+ const prices = new PriceBook(l.prices);
71
+ return l.accounts.map((a) => valueAccount(l, a, hs.get(a.id) ?? { amount: 0, qty: 0 }, prices, asOf));
72
+ }
73
+ export function isLiabilityType(type) {
74
+ return Boolean(typeDef(type)?.liability);
75
+ }
@@ -0,0 +1,17 @@
1
+ import type { CategoriesFile, Category } from "./types.js";
2
+ /**
3
+ * System categories (prefix "_"): they balance transactions that are neither income nor spending.
4
+ * Reports never count them as income or spending.
5
+ */
6
+ export declare const SYSTEM_CATEGORIES: Record<string, {
7
+ en: string;
8
+ vi: string;
9
+ }>;
10
+ export declare function isSystemCategory(path: string): boolean;
11
+ /** Flattens the tree into a map path → Category. Duplicate paths are reported by check. */
12
+ export declare function flattenCategories(file: CategoriesFile): {
13
+ map: Map<string, Category>;
14
+ dupes: string[];
15
+ };
16
+ /** The top-level segment of a category path. */
17
+ export declare function topOf(path: string): string;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * System categories (prefix "_"): they balance transactions that are neither income nor spending.
3
+ * Reports never count them as income or spending.
4
+ */
5
+ export const SYSTEM_CATEGORIES = {
6
+ _opening: { en: "Opening balance", vi: "Số dư ban đầu" },
7
+ _adjust: { en: "Balance adjustment", vi: "Điều chỉnh số dư" },
8
+ };
9
+ export function isSystemCategory(path) {
10
+ return path.startsWith("_");
11
+ }
12
+ /** Flattens the tree into a map path → Category. Duplicate paths are reported by check. */
13
+ export function flattenCategories(file) {
14
+ const map = new Map();
15
+ const dupes = [];
16
+ const walk = (nodes, kind, parent) => {
17
+ for (const n of nodes ?? []) {
18
+ if (!n || typeof n.id !== "string")
19
+ continue;
20
+ const path = parent ? `${parent}/${n.id}` : n.id;
21
+ if (map.has(path))
22
+ dupes.push(path);
23
+ map.set(path, { path, name: String(n.name ?? n.id), kind, parent });
24
+ walk(n.children, kind, path);
25
+ }
26
+ };
27
+ walk(file.income, "income", null);
28
+ walk(file.expense, "expense", null);
29
+ return { map, dupes };
30
+ }
31
+ /** The top-level segment of a category path. */
32
+ export function topOf(path) {
33
+ const i = path.indexOf("/");
34
+ return i < 0 ? path : path.slice(0, i);
35
+ }
@@ -0,0 +1,11 @@
1
+ import { type FileMap } from "./load.js";
2
+ import { type Issue, type Ledger } from "./types.js";
3
+ export interface CheckResult {
4
+ ok: boolean;
5
+ errors: Issue[];
6
+ warnings: Issue[];
7
+ ledger: Ledger;
8
+ }
9
+ /** Load + check. `ok` is false when there is any error. Warnings never fail. */
10
+ export declare function checkFiles(files: FileMap): CheckResult;
11
+ export declare function checkLedger(l: Ledger): Issue[];