@sachfolio/cas-reader 0.0.0-stage → 0.2.0-beta.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +71 -0
  3. package/NOTICE +41 -0
  4. package/README.md +198 -2
  5. package/dist/analytics/contract.d.ts +110 -0
  6. package/dist/analytics/contract.js +79 -0
  7. package/dist/analytics/eligibility.d.ts +66 -0
  8. package/dist/analytics/eligibility.js +93 -0
  9. package/dist/analytics/gains-schema.d.ts +898 -0
  10. package/dist/analytics/gains-schema.js +170 -0
  11. package/dist/analytics/gains.d.ts +319 -0
  12. package/dist/analytics/gains.js +649 -0
  13. package/dist/analytics/modules.d.ts +33 -0
  14. package/dist/analytics/modules.js +74 -0
  15. package/dist/analytics/returns-schema.d.ts +931 -0
  16. package/dist/analytics/returns-schema.js +152 -0
  17. package/dist/analytics/returns.d.ts +126 -0
  18. package/dist/analytics/returns.js +453 -0
  19. package/dist/analytics/schedule112a.d.ts +77 -0
  20. package/dist/analytics/schedule112a.js +134 -0
  21. package/dist/analytics/xirr.d.ts +75 -0
  22. package/dist/analytics/xirr.js +314 -0
  23. package/dist/bin/cas.d.ts +2 -0
  24. package/dist/bin/cas.js +137 -0
  25. package/dist/checks.d.ts +49 -0
  26. package/dist/checks.js +227 -0
  27. package/dist/compat/casparser.d.ts +121 -0
  28. package/dist/compat/casparser.js +193 -0
  29. package/dist/detect.d.ts +10 -0
  30. package/dist/detect.js +69 -0
  31. package/dist/errors.d.ts +26 -0
  32. package/dist/errors.js +95 -0
  33. package/dist/export/csv.d.ts +21 -0
  34. package/dist/export/csv.js +49 -0
  35. package/dist/extract/browser.d.ts +17 -0
  36. package/dist/extract/browser.js +34 -0
  37. package/dist/extract/budget.d.ts +46 -0
  38. package/dist/extract/budget.js +88 -0
  39. package/dist/extract/node.d.ts +11 -0
  40. package/dist/extract/node.js +31 -0
  41. package/dist/extract/pdfjs.d.ts +71 -0
  42. package/dist/extract/pdfjs.js +244 -0
  43. package/dist/extract/types.d.ts +106 -0
  44. package/dist/extract/types.js +11 -0
  45. package/dist/index.d.ts +27 -0
  46. package/dist/index.js +26 -0
  47. package/dist/layout/lines.d.ts +51 -0
  48. package/dist/layout/lines.js +115 -0
  49. package/dist/licence/app-licence.d.ts +53 -0
  50. package/dist/licence/app-licence.js +139 -0
  51. package/dist/licence/ed25519.d.ts +2 -0
  52. package/dist/licence/ed25519.js +103 -0
  53. package/dist/model.d.ts +148 -0
  54. package/dist/model.js +1 -0
  55. package/dist/num.d.ts +19 -0
  56. package/dist/num.js +27 -0
  57. package/dist/parse.d.ts +4 -0
  58. package/dist/parse.js +13 -0
  59. package/dist/parsers/cams/classify.d.ts +25 -0
  60. package/dist/parsers/cams/classify.js +103 -0
  61. package/dist/parsers/cams/detailed.d.ts +15 -0
  62. package/dist/parsers/cams/detailed.js +343 -0
  63. package/dist/parsers/cams/header.d.ts +47 -0
  64. package/dist/parsers/cams/header.js +170 -0
  65. package/dist/parsers/cams/investor.d.ts +28 -0
  66. package/dist/parsers/cams/investor.js +139 -0
  67. package/dist/parsers/cams/summary.d.ts +29 -0
  68. package/dist/parsers/cams/summary.js +413 -0
  69. package/dist/parsers/cams/table.d.ts +55 -0
  70. package/dist/parsers/cams/table.js +144 -0
  71. package/dist/parsers/cams/total.d.ts +17 -0
  72. package/dist/parsers/cams/total.js +105 -0
  73. package/dist/parsers/depository/mf.d.ts +22 -0
  74. package/dist/parsers/depository/mf.js +438 -0
  75. package/dist/privacy.d.ts +243 -0
  76. package/dist/privacy.js +256 -0
  77. package/dist/schema.d.ts +779 -0
  78. package/dist/schema.js +214 -0
  79. package/examples/nextjs/app/page.jsx +34 -0
  80. package/examples/node/server.mjs +45 -0
  81. package/examples/python/read_cas.py +67 -0
  82. package/examples/vite/index.html +14 -0
  83. package/examples/vite/main.js +22 -0
  84. package/package.json +54 -4
@@ -0,0 +1,75 @@
1
+ /**
2
+ * XIRR solver in big.js (PLAN.md §6.2 "Solver", docs/SPEC-metrics.md). No JS
3
+ * `Number` touches a money value or a rate: big.js has no ln/exp, so both are
4
+ * series evaluated here to a fixed precision.
5
+ *
6
+ * Definition. Flows c_i on dates D_i (negative = paid in by the investor,
7
+ * positive = received or held at the end). Day count Actual/365 (fixed),
8
+ * measured from the earliest flow: t_i = (D_i − D_0) / 365, the convention of
9
+ * spreadsheet XIRR. The rate r is the root of
10
+ *
11
+ * f(r) = Σ c_i · (1 + r)^(−t_i) = 0, r > −1.
12
+ *
13
+ * Method.
14
+ * 1. Flows are summed per date (exact). Fewer than two dates, or flows of one
15
+ * sign only, have no rate: `unavailable`, never a guess.
16
+ * 2. f is evaluated on a fixed grid of rates from −99.9999 % to +10⁸ %. No
17
+ * sign change → `no_root`; more than one → `multiple_roots`.
18
+ * 3. Inside the one bracket: Newton steps safeguarded by bisection
19
+ * (Numerical Recipes "rtsafe"). Stopping rule: the last correction is
20
+ * below 1e-12 (absolute, in the rate as a fraction), then f must change
21
+ * sign across r* ± 1e-12, so the root is bracketed within ±1e-12. At most
22
+ * 200 iterations.
23
+ * 4. Residual check: |f(r*)| ≤ 1e-9 × Σ|c_i (1 + r*)^(−t_i)|.
24
+ * 5. Uniqueness certificate (Laguerre's rule of signs, the basis of Norstrøm's
25
+ * criterion): with x = 1/(1+r), f is Σ c_i x^(t_i). The number of roots in
26
+ * x ∈ (0, X) is at most the number of sign changes in the running sums of
27
+ * c_i X^(t_i) taken in date order; for x > X, in the running sums taken
28
+ * from the last date backwards. Evaluated just either side of the root
29
+ * (X = x*(1 ∓ 1e-6)); both counts must be zero, or the result is
30
+ * `multiple_roots` (another rate could fit the same flows).
31
+ *
32
+ * Precision: every product is rounded to 32 significant digits, divisions to
33
+ * 50 decimal places (half-even); series stop below 1e-40. The reported rate is rounded half-up to 10
34
+ * decimal places; it is accurate to ±1e-12 before rounding.
35
+ */
36
+ import Big from "big.js";
37
+ export interface DatedFlow {
38
+ /** ISO calendar date. */
39
+ date: string;
40
+ /** Signed decimal string: negative = paid in by the investor. */
41
+ amount: string;
42
+ }
43
+ export type SolverFailure = "no_flows" | "single_date" | "one_sided_flows" | "no_root" | "multiple_roots" | "no_convergence" | "residual_too_large";
44
+ export type SolveResult = {
45
+ status: "computed";
46
+ /** The annual rate as a fraction, 10 decimal places, e.g. "0.1000000000" for 10 %. */
47
+ rate: string;
48
+ /** Earliest and latest flow dates and the days between them (Actual). */
49
+ from: string;
50
+ to: string;
51
+ days: number;
52
+ iterations: number;
53
+ newtonSteps: number;
54
+ bisectionSteps: number;
55
+ /** f(r*) in rupees, 6 decimal places. */
56
+ residual: string;
57
+ } | {
58
+ status: "unavailable";
59
+ failure: SolverFailure;
60
+ from: string | null;
61
+ to: string | null;
62
+ days: number | null;
63
+ };
64
+ /** Natural log of x > 0: x = m·2^k with m in [0.75, 1.5], ln m = 2·atanh((m−1)/(m+1)). */
65
+ export declare function ln(x: Big): Big;
66
+ /** e^x: halve the argument below 1/64, Taylor series, square back. */
67
+ export declare function exp(x: Big): Big;
68
+ /** Whole days between two ISO calendar dates (UTC, no time zone involved). */
69
+ export declare function daysBetween(from: string, to: string): number;
70
+ export declare function solveXirr(flows: readonly DatedFlow[]): SolveResult;
71
+ /** Exposed for tests: the Laguerre bounds on other roots around `root`, for the given flows. */
72
+ export declare function otherRootBoundsFor(flows: readonly DatedFlow[], root: string): {
73
+ above: number;
74
+ below: number;
75
+ };
@@ -0,0 +1,314 @@
1
+ /**
2
+ * XIRR solver in big.js (PLAN.md §6.2 "Solver", docs/SPEC-metrics.md). No JS
3
+ * `Number` touches a money value or a rate: big.js has no ln/exp, so both are
4
+ * series evaluated here to a fixed precision.
5
+ *
6
+ * Definition. Flows c_i on dates D_i (negative = paid in by the investor,
7
+ * positive = received or held at the end). Day count Actual/365 (fixed),
8
+ * measured from the earliest flow: t_i = (D_i − D_0) / 365, the convention of
9
+ * spreadsheet XIRR. The rate r is the root of
10
+ *
11
+ * f(r) = Σ c_i · (1 + r)^(−t_i) = 0, r > −1.
12
+ *
13
+ * Method.
14
+ * 1. Flows are summed per date (exact). Fewer than two dates, or flows of one
15
+ * sign only, have no rate: `unavailable`, never a guess.
16
+ * 2. f is evaluated on a fixed grid of rates from −99.9999 % to +10⁸ %. No
17
+ * sign change → `no_root`; more than one → `multiple_roots`.
18
+ * 3. Inside the one bracket: Newton steps safeguarded by bisection
19
+ * (Numerical Recipes "rtsafe"). Stopping rule: the last correction is
20
+ * below 1e-12 (absolute, in the rate as a fraction), then f must change
21
+ * sign across r* ± 1e-12, so the root is bracketed within ±1e-12. At most
22
+ * 200 iterations.
23
+ * 4. Residual check: |f(r*)| ≤ 1e-9 × Σ|c_i (1 + r*)^(−t_i)|.
24
+ * 5. Uniqueness certificate (Laguerre's rule of signs, the basis of Norstrøm's
25
+ * criterion): with x = 1/(1+r), f is Σ c_i x^(t_i). The number of roots in
26
+ * x ∈ (0, X) is at most the number of sign changes in the running sums of
27
+ * c_i X^(t_i) taken in date order; for x > X, in the running sums taken
28
+ * from the last date backwards. Evaluated just either side of the root
29
+ * (X = x*(1 ∓ 1e-6)); both counts must be zero, or the result is
30
+ * `multiple_roots` (another rate could fit the same flows).
31
+ *
32
+ * Precision: every product is rounded to 32 significant digits, divisions to
33
+ * 50 decimal places (half-even); series stop below 1e-40. The reported rate is rounded half-up to 10
34
+ * decimal places; it is accurate to ±1e-12 before rounding.
35
+ */
36
+ import Big from "big.js";
37
+ /** A private constructor so these settings never leak into money arithmetic elsewhere. */
38
+ const D = Big();
39
+ D.DP = 50;
40
+ D.RM = Big.roundHalfEven;
41
+ D.NE = -100;
42
+ D.PE = 100;
43
+ const SD = 32;
44
+ const SERIES_EPS = new D("1e-40");
45
+ const RATE_TOL = new D("1e-12");
46
+ const RESIDUAL_REL = new D("1e-9");
47
+ const CERT_DELTA = new D("1e-6");
48
+ const MAX_ITER = 200;
49
+ const DAYS_PER_YEAR = 365;
50
+ const ZERO = new D(0);
51
+ const ONE = new D(1);
52
+ /** Rates (as fractions) where f is sampled to bracket the root. */
53
+ const GRID = [
54
+ "-0.999999", "-0.9999", "-0.99", "-0.9", "-0.75", "-0.5", "-0.25", "-0.1", "0", "0.1", "0.25", "0.5", "1", "2", "5",
55
+ "10", "100", "1000", "10000", "100000", "1000000",
56
+ ].map((s) => new D(s));
57
+ /* ---------- elementary functions to fixed precision ---------- */
58
+ const mul = (a, b) => a.times(b).prec(SD);
59
+ /** atanh(z) for |z| < 1 by its series z + z³/3 + z⁵/5 + … */
60
+ function atanh(z) {
61
+ const z2 = mul(z, z);
62
+ let term = new D(z);
63
+ let sum = new D(z);
64
+ for (let n = 3;; n += 2) {
65
+ term = mul(term, z2);
66
+ const add = term.div(n);
67
+ sum = sum.plus(add);
68
+ if (add.abs().lt(SERIES_EPS))
69
+ return sum;
70
+ }
71
+ }
72
+ const LN2 = atanh(ONE.div(3)).times(2);
73
+ /** Natural log of x > 0: x = m·2^k with m in [0.75, 1.5], ln m = 2·atanh((m−1)/(m+1)). */
74
+ export function ln(x) {
75
+ if (x.lte(0))
76
+ throw new RangeError("ln of a non-positive number");
77
+ let m = new D(x);
78
+ let k = 0;
79
+ while (m.gt(1.5)) {
80
+ m = m.div(2);
81
+ k++;
82
+ }
83
+ while (m.lt(0.75)) {
84
+ m = m.times(2);
85
+ k--;
86
+ }
87
+ return atanh(m.minus(1).div(m.plus(1))).times(2).plus(LN2.times(k));
88
+ }
89
+ /** e^x: halve the argument below 1/64, Taylor series, square back. */
90
+ export function exp(x) {
91
+ let y = new D(x);
92
+ let halvings = 0;
93
+ while (y.abs().gt("0.015625")) {
94
+ y = y.div(2);
95
+ halvings++;
96
+ }
97
+ let term = new D(1);
98
+ let sum = new D(1);
99
+ for (let n = 1;; n++) {
100
+ term = mul(term, y).div(n);
101
+ sum = sum.plus(term);
102
+ if (term.abs().lt(SERIES_EPS))
103
+ break;
104
+ }
105
+ for (let i = 0; i < halvings; i++)
106
+ sum = mul(sum, sum);
107
+ return sum;
108
+ }
109
+ /** b^n for an integer n ≥ 0, by squaring, rounding each product. */
110
+ function powInt(b, n) {
111
+ let result = ONE;
112
+ let base = b;
113
+ let e = n;
114
+ while (e > 0) {
115
+ if (e & 1)
116
+ result = mul(result, base);
117
+ e >>= 1;
118
+ if (e > 0)
119
+ base = mul(base, base);
120
+ }
121
+ return result;
122
+ }
123
+ /* ---------- dates ---------- */
124
+ /** Whole days between two ISO calendar dates (UTC, no time zone involved). */
125
+ export function daysBetween(from, to) {
126
+ const t = (iso) => {
127
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
128
+ if (!m)
129
+ throw new RangeError(`not an ISO date: ${iso}`);
130
+ return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
131
+ };
132
+ return Math.round((t(to) - t(from)) / 86_400_000);
133
+ }
134
+ function evaluate(s, r) {
135
+ const onePlus = ONE.plus(r);
136
+ // w = (1+r)^(−1/365); then (1+r)^(−t_i) = w^(days_i).
137
+ const w = exp(ln(onePlus).neg().div(DAYS_PER_YEAR));
138
+ let v = ONE;
139
+ let prev = 0;
140
+ let f = ZERO;
141
+ let g = ZERO;
142
+ const terms = [];
143
+ // Gaps between dates repeat (monthly SIPs), so each power of w is built once.
144
+ const powers = new Map();
145
+ for (let i = 0; i < s.days.length; i++) {
146
+ const d = s.days[i];
147
+ const gap = d - prev;
148
+ let p = powers.get(gap);
149
+ if (!p)
150
+ powers.set(gap, (p = powInt(w, gap)));
151
+ v = mul(v, p);
152
+ prev = d;
153
+ const term = mul(s.amounts[i], v);
154
+ terms.push(term);
155
+ f = f.plus(term);
156
+ g = g.plus(term.times(d));
157
+ }
158
+ // d/dr of c (1+r)^(−d/365) is −(d/365) c (1+r)^(−d/365) / (1+r).
159
+ const df = g.neg().div(onePlus.times(DAYS_PER_YEAR));
160
+ return { f, df, terms };
161
+ }
162
+ const sign = (b) => (b.gt(0) ? 1 : b.lt(0) ? -1 : 0);
163
+ /** Sign changes in the running sums of `xs`, zeros skipped. */
164
+ function runningSumSignChanges(xs) {
165
+ let sum = ZERO;
166
+ let last = 0;
167
+ let changes = 0;
168
+ for (const x of xs) {
169
+ sum = sum.plus(x);
170
+ const s = sign(sum);
171
+ if (s === 0)
172
+ continue;
173
+ if (last !== 0 && s !== last)
174
+ changes++;
175
+ last = s;
176
+ }
177
+ return changes;
178
+ }
179
+ /** Upper bounds on the number of other roots above and below r* (Laguerre's rule of signs). */
180
+ function otherRootBounds(s, root) {
181
+ const x = ONE.div(ONE.plus(root));
182
+ const rateAt = (X) => ONE.div(X).minus(1);
183
+ // Roots at rates above r* are x in (0, x*(1−δ)): running sums in date order.
184
+ const above = runningSumSignChanges(evaluate(s, rateAt(x.times(ONE.minus(CERT_DELTA)))).terms);
185
+ // Roots at rates below r* are x > x*(1+δ): running sums from the last date back.
186
+ const below = runningSumSignChanges(evaluate(s, rateAt(x.times(ONE.plus(CERT_DELTA)))).terms.reverse());
187
+ return { above, below };
188
+ }
189
+ /* ---------- solve ---------- */
190
+ export function solveXirr(flows) {
191
+ const byDate = new Map();
192
+ for (const fl of flows)
193
+ byDate.set(fl.date, (byDate.get(fl.date) ?? ZERO).plus(new D(fl.amount)));
194
+ const dates = [...byDate.keys()].sort();
195
+ const from = dates[0] ?? null;
196
+ const to = dates[dates.length - 1] ?? null;
197
+ const span = from && to ? daysBetween(from, to) : null;
198
+ const fail = (failure) => ({ status: "unavailable", failure, from, to, days: span });
199
+ if (!from || !to)
200
+ return fail("no_flows");
201
+ const nonZero = dates.filter((d) => !byDate.get(d).eq(0));
202
+ if (nonZero.length === 0)
203
+ return fail("no_flows");
204
+ if (nonZero.length === 1)
205
+ return fail("single_date");
206
+ const series = { days: nonZero.map((d) => daysBetween(from, d)), amounts: nonZero.map((d) => byDate.get(d)) };
207
+ if (!series.amounts.some((a) => a.gt(0)) || !series.amounts.some((a) => a.lt(0)))
208
+ return fail("one_sided_flows");
209
+ // 2. Bracket on the grid.
210
+ const brackets = [];
211
+ let exact = null;
212
+ let prevR = null;
213
+ let prevF = 0;
214
+ for (const r of GRID) {
215
+ const s = sign(evaluate(series, r).f);
216
+ if (s === 0) {
217
+ if (exact)
218
+ return fail("multiple_roots");
219
+ exact = r;
220
+ // The zero is the crossing: don't count it again as a bracket.
221
+ prevR = null;
222
+ prevF = 0;
223
+ continue;
224
+ }
225
+ if (prevR && prevF !== 0 && s !== prevF)
226
+ brackets.push([prevR, r]);
227
+ prevR = r;
228
+ prevF = s;
229
+ }
230
+ if (brackets.length + (exact ? 1 : 0) > 1)
231
+ return fail("multiple_roots");
232
+ let root;
233
+ let iterations = 0;
234
+ let newtonSteps = 0;
235
+ let bisectionSteps = 0;
236
+ if (exact)
237
+ root = exact;
238
+ else {
239
+ const bracket = brackets[0];
240
+ if (!bracket)
241
+ return fail("no_root");
242
+ // 3. rtsafe: keep f(lo) < 0 < f(hi).
243
+ let [lo, hi] = bracket;
244
+ if (sign(evaluate(series, lo).f) > 0)
245
+ [lo, hi] = [hi, lo];
246
+ let r = lo.plus(hi).div(2);
247
+ let dxOld = hi.minus(lo).abs();
248
+ let dx = dxOld;
249
+ let ev = evaluate(series, r);
250
+ let converged = false;
251
+ for (; iterations < MAX_ITER;) {
252
+ iterations++;
253
+ const outside = r.minus(hi).times(ev.df).minus(ev.f).times(r.minus(lo).times(ev.df).minus(ev.f)).gt(0);
254
+ const slow = ev.f.times(2).abs().gt(dxOld.times(ev.df).abs());
255
+ if (ev.df.eq(0) || outside || slow) {
256
+ dxOld = dx;
257
+ dx = hi.minus(lo).div(2);
258
+ r = lo.plus(dx);
259
+ bisectionSteps++;
260
+ }
261
+ else {
262
+ dxOld = dx;
263
+ dx = ev.f.div(ev.df);
264
+ r = r.minus(dx);
265
+ newtonSteps++;
266
+ }
267
+ if (dx.abs().lt(RATE_TOL)) {
268
+ converged = true;
269
+ break;
270
+ }
271
+ ev = evaluate(series, r);
272
+ if (ev.f.eq(0)) {
273
+ converged = true;
274
+ break;
275
+ }
276
+ if (ev.f.lt(0))
277
+ lo = r;
278
+ else
279
+ hi = r;
280
+ }
281
+ if (!converged)
282
+ return fail("no_convergence");
283
+ // The root must be bracketed within ±1e-12 of r.
284
+ const left = sign(evaluate(series, r.minus(RATE_TOL)).f);
285
+ const right = sign(evaluate(series, r.plus(RATE_TOL)).f);
286
+ if (left !== 0 && right !== 0 && left === right && !evaluate(series, r).f.eq(0))
287
+ return fail("no_convergence");
288
+ root = r;
289
+ }
290
+ // 4. Residual.
291
+ const at = evaluate(series, root);
292
+ const scale = at.terms.reduce((acc, t) => acc.plus(t.abs()), ZERO);
293
+ if (at.f.abs().gt(scale.times(RESIDUAL_REL)))
294
+ return fail("residual_too_large");
295
+ // 5. No other root on either side.
296
+ const others = otherRootBounds(series, root);
297
+ if (others.above > 0 || others.below > 0)
298
+ return fail("multiple_roots");
299
+ return {
300
+ status: "computed",
301
+ rate: root.round(10, Big.roundHalfUp).toFixed(10),
302
+ from, to, days: span,
303
+ iterations, newtonSteps, bisectionSteps,
304
+ residual: at.f.round(6, Big.roundHalfUp).toFixed(6),
305
+ };
306
+ }
307
+ /** Exposed for tests: the Laguerre bounds on other roots around `root`, for the given flows. */
308
+ export function otherRootBoundsFor(flows, root) {
309
+ const byDate = new Map();
310
+ for (const fl of flows)
311
+ byDate.set(fl.date, (byDate.get(fl.date) ?? ZERO).plus(new D(fl.amount)));
312
+ const dates = [...byDate.keys()].sort();
313
+ return otherRootBounds({ days: dates.map((d) => daysBetween(dates[0], d)), amounts: dates.map((d) => byDate.get(d)) }, new D(root));
314
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * sachfolio-cas: statement PDF → JSON, for teams calling us from Python, Java
4
+ * or a shell. Runs entirely on this machine and makes no network requests.
5
+ *
6
+ * sachfolio-cas statement.pdf # prompts for the password if needed
7
+ * sachfolio-cas statement.pdf --password-stdin < pw # first line of stdin is the password
8
+ * sachfolio-cas statement.pdf --format casparser # casparser-compatible JSON
9
+ * sachfolio-cas statement.pdf --out result.json
10
+ * sachfolio-cas copy-assets public/pdfjs # pdf.js worker, fonts, cmaps, wasm for a browser app
11
+ * sachfolio-cas licence SF1.… # check an app licence code, offline
12
+ *
13
+ * There is no --password flag on purpose: arguments show up in shell history
14
+ * and the process list. Exit codes: 0 ok, 1 the statement could not be read
15
+ * (stderr starts with the error code, e.g. "INCORRECT_PASSWORD:"), 2 usage.
16
+ * The JSON holds the whole statement's personal data; don't log it.
17
+ */
18
+ import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
19
+ import { createRequire } from "node:module";
20
+ import path from "node:path";
21
+ import readline from "node:readline";
22
+ import { toCasparser, toCasparserDemat } from "../compat/casparser.js";
23
+ import { isCasError } from "../errors.js";
24
+ import { createNodeExtractor } from "../extract/node.js";
25
+ import { checkAppLicence } from "../licence/app-licence.js";
26
+ import { parseCas } from "../parse.js";
27
+ const USAGE = [
28
+ "usage: sachfolio-cas <statement.pdf> [--format sachfolio|casparser] [--keep-order] [--out <file>] [--password-stdin]",
29
+ " sachfolio-cas copy-assets <folder>",
30
+ " sachfolio-cas licence <code>",
31
+ ].join("\n");
32
+ async function readPassword(fromStdin) {
33
+ if (fromStdin || !process.stdin.isTTY) {
34
+ const rl = readline.createInterface({ input: process.stdin });
35
+ for await (const line of rl) {
36
+ rl.close();
37
+ return line.replace(/\r$/, "");
38
+ }
39
+ return "";
40
+ }
41
+ return new Promise((resolve) => {
42
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true });
43
+ const out = rl;
44
+ let muted = false;
45
+ out._writeToOutput = (s) => {
46
+ if (!muted || s.includes("\n"))
47
+ out.output.write(muted ? "\n" : s);
48
+ };
49
+ rl.question("PDF password: ", (answer) => {
50
+ rl.close();
51
+ resolve(answer);
52
+ });
53
+ muted = true;
54
+ });
55
+ }
56
+ function usage(message) {
57
+ if (message)
58
+ console.error(message);
59
+ console.error(USAGE);
60
+ process.exit(2);
61
+ }
62
+ const args = process.argv.slice(2);
63
+ /** pdf.js's worker and data folders, copied for a browser app to serve from its own site. */
64
+ async function copyAssets(dest) {
65
+ if (!dest)
66
+ usage("copy-assets needs a folder, e.g. public/pdfjs");
67
+ const root = path.dirname(createRequire(import.meta.url).resolve("pdfjs-dist/package.json"));
68
+ await mkdir(dest, { recursive: true });
69
+ for (const dir of ["cmaps", "standard_fonts", "wasm"])
70
+ await cp(path.join(root, dir), path.join(dest, dir), { recursive: true });
71
+ await cp(path.join(root, "legacy", "build", "pdf.worker.mjs"), path.join(dest, "pdf.worker.mjs"));
72
+ console.error(`Copied pdf.js's worker, cmaps, standard_fonts and wasm to ${dest}. Serve it as-is, e.g. createCasReader({ assetsUrl: "/pdfjs/" }).`);
73
+ process.exit(0);
74
+ }
75
+ async function licence(code) {
76
+ if (!code)
77
+ usage("licence needs the code");
78
+ const r = await checkAppLicence(code);
79
+ process.stdout.write(JSON.stringify(r, null, 2) + "\n");
80
+ process.exit(r.status === "valid" ? 0 : 1);
81
+ }
82
+ if (args[0] === "copy-assets")
83
+ await copyAssets(args[1]);
84
+ if (args[0] === "licence")
85
+ await licence(args[1]);
86
+ let file;
87
+ let format = "sachfolio";
88
+ let out;
89
+ let passwordStdin = false;
90
+ let keepOrder = false;
91
+ for (let i = 0; i < args.length; i++) {
92
+ const a = args[i];
93
+ if (a === "--format")
94
+ format = args[++i] ?? usage("--format needs a value");
95
+ else if (a === "--out")
96
+ out = args[++i] ?? usage("--out needs a file");
97
+ else if (a === "--password-stdin")
98
+ passwordStdin = true;
99
+ else if (a === "--keep-order")
100
+ keepOrder = true;
101
+ else if (a === "--help" || a === "-h")
102
+ usage();
103
+ else if (a.startsWith("-"))
104
+ usage(`unknown option ${a}`);
105
+ else if (file)
106
+ usage("one statement at a time");
107
+ else
108
+ file = a;
109
+ }
110
+ if (!file)
111
+ usage();
112
+ if (format !== "sachfolio" && format !== "casparser")
113
+ usage(`unknown format ${format}`);
114
+ try {
115
+ const bytes = new Uint8Array(await readFile(file));
116
+ const extractor = createNodeExtractor();
117
+ let doc;
118
+ try {
119
+ doc = await extractor.extract(bytes);
120
+ }
121
+ catch (e) {
122
+ if (!(isCasError(e) && e.code === "NEED_PASSWORD"))
123
+ throw e;
124
+ doc = await extractor.extract(bytes, { password: await readPassword(passwordStdin) });
125
+ }
126
+ const cas = parseCas(doc);
127
+ const result = format !== "casparser" ? cas : cas.source.variant === "DEMAT" ? toCasparserDemat(cas) : toCasparser(cas, { sortTransactions: !keepOrder });
128
+ const json = JSON.stringify(result, null, 2) + "\n";
129
+ if (out)
130
+ await writeFile(out, json);
131
+ else
132
+ process.stdout.write(json);
133
+ }
134
+ catch (e) {
135
+ console.error(isCasError(e) ? `${e.code}: ${e.message}` : `ERROR: ${e instanceof Error ? e.message : String(e)}`);
136
+ process.exit(1);
137
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Per-scheme checks (PLAN.md §5.4, docs/SPEC-metrics.md). Tolerances come only
3
+ * from printed precision, never from a percentage of value.
4
+ */
5
+ import type Big from "big.js";
6
+ import type { Check, PrintedTotal, Scheme, Transaction, TxnType } from "./model.js";
7
+ import { type Num } from "./num.js";
8
+ /** Rows checked as amount = units × price (rows.purchase_identity). */
9
+ export declare const PURCHASE_TYPES: ReadonlySet<TxnType>;
10
+ /** Bound for |a×b − c| when a, b, c are each rounded to their printed scale. */
11
+ export declare function productBound(a: Num, b: Num, c: Num): Big;
12
+ /**
13
+ * ISIN check digit (ISO 6166): letters become two digits (A=10 … Z=35), then
14
+ * Luhn over the expanded string. Catches a misread character in the ISIN.
15
+ */
16
+ export declare function isValidIsin(isin: string): boolean;
17
+ /** Group 3 validity: the scheme's ISIN, when printed, has a valid check digit. */
18
+ export declare function isinCheck(scheme: Pick<Scheme, "isin" | "source">): Check;
19
+ /**
20
+ * casparser `_apply_balance_sign_fix`: some templates print a reversed row's
21
+ * units in cosmetic parentheses. When prev − units = printed balance but
22
+ * prev + units ≠ it, the sign is flipped. The printed text stays in `raw`.
23
+ *
24
+ * Narrower than casparser, which flips any row that fits: here the row must
25
+ * be printed negative and say "reversed"/"reversal". Otherwise a dropped row
26
+ * whose units happen to be −2× the next row's is hidden by flipping that row,
27
+ * and both ledger checks then pass by construction. A row that prints a
28
+ * balance without units (unreadable, or a marker row) resyncs the chain
29
+ * instead of being skipped, for the same reason.
30
+ */
31
+ export declare function fixSigns(scheme: Scheme, reclassify: (t: Transaction) => void): void;
32
+ /**
33
+ * Statement level: the printed portfolio total's market value equals the
34
+ * schemes' printed values added up. Each printed value may be rounded by half
35
+ * a unit in its last place, and so may the total, so the bound is the sum of
36
+ * those half-units; never a percentage. A scheme with units but no printed
37
+ * value makes the sum impossible: "unavailable", never a guess. A
38
+ * zero-balance scheme without a value adds nothing. A scheme the parser
39
+ * couldn't build is missing from the sum, so this check also catches it.
40
+ */
41
+ export declare function portfolioTotalCheck(total: PrintedTotal | null, schemes: readonly Scheme[]): Check;
42
+ export interface CheckOptions {
43
+ /** Rows with a cell the parser saw but couldn't read (two values in one cell); recorded in coverage. */
44
+ unreadable?: ReadonlySet<Transaction>;
45
+ }
46
+ export declare function checkScheme(scheme: Scheme, period: {
47
+ from: string;
48
+ to: string;
49
+ } | null, options?: CheckOptions): Check[];