@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
package/dist/schema.js ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * CasDocument v1 as a runtime schema (zod 4). model.ts stays the source of the
3
+ * TypeScript types; this file mirrors it for validating documents that cross a
4
+ * boundary (worker messages, saved JSON, other tools), and generates the
5
+ * committed JSON Schema (schema/cas-document.v1.schema.json, docs/SCHEMA.md).
6
+ * The guards at the bottom fail the typecheck when the two drift apart.
7
+ *
8
+ * Field descriptions repeat the model.ts / num.ts comments verbatim where they
9
+ * exist, so the JSON Schema documents the same contract.
10
+ */
11
+ import * as z from "zod";
12
+ import { annotatePrivacy } from "./privacy.js";
13
+ // The web app's CSP has no 'unsafe-eval' (PLAN.md §7). Zod probes `new Function`
14
+ // whenever an object schema is built, and a strict CSP reports that probe as a
15
+ // violation even though zod catches the throw. Turn the JIT off before building any.
16
+ z.config({ jitless: true });
17
+ export const CAS_DOCUMENT_SCHEMA_ID = "urn:foliolens:schema:cas-document:v1";
18
+ // Canonical decimal as produced by big.js `toFixed`: no exponent, no grouping.
19
+ const DECIMAL_RE = /^-?\d+(?:\.\d+)?$/;
20
+ const SHA256_RE = /^[0-9a-f]{64}$/;
21
+ // ISO 6166 shape only; the check digit is a parse-time check, not a schema rule.
22
+ const ISIN_RE = /^[A-Z]{2}[A-Z0-9]{9}\d$/;
23
+ const fractionDigits = (v) => (v.includes(".") ? v.length - v.indexOf(".") - 1 : 0);
24
+ const decimalString = z.string().regex(DECIMAL_RE, "must be a canonical decimal string, e.g. \"-1234.50\"");
25
+ const count = z.int().min(0);
26
+ export const isoDateSchema = z.iso
27
+ .date()
28
+ .meta({ id: "IsoDate", description: "ISO 8601 calendar date (YYYY-MM-DD). No time and no time zone: the date as printed on the statement." });
29
+ export const numSchema = z
30
+ .strictObject({
31
+ raw: z.string().describe('Exactly as printed, e.g. "(1,234.50)". "derived" when the engine computed the value because the statement does not print it (see Transaction.price).'),
32
+ value: decimalString.describe('Canonical decimal string with sign applied, e.g. "-1234.50". Never a JSON number: parse it with a decimal library.'),
33
+ scale: count.describe("Digits after the decimal point as printed. Tolerances derive from it."),
34
+ })
35
+ .refine((n) => fractionDigits(n.value) === n.scale, { message: "value must have exactly `scale` digits after the decimal point", path: ["value"] })
36
+ .meta({ id: "Num", description: "A printed number kept exact: the printed text, its canonical decimal value and its printed precision." });
37
+ export const sourceSchema = z
38
+ .strictObject({
39
+ page: z.int().min(1).describe("1-based page number."),
40
+ y: z.number().describe("Baseline y of the line (top-down points)."),
41
+ })
42
+ .meta({ id: "Source", description: "Where a value was read: the page and the baseline of its line." });
43
+ export const txnTypeSchema = z
44
+ .enum([
45
+ "PURCHASE", "PURCHASE_SIP", "REDEMPTION", "SWP", "SWITCH_IN", "SWITCH_IN_MERGER", "SWITCH_OUT", "SWITCH_OUT_MERGER",
46
+ "DIVIDEND_PAYOUT", "DIVIDEND_REINVEST", "SEGREGATION", "GIFT_IN", "GIFT_OUT", "REVERSAL",
47
+ "TRANSFER_IN", "TRANSFER_OUT", "BONUS", "UNIT_ADJUSTMENT", "PLEDGE", "PLEDGE_RELEASE", "PLEDGE_INVOKED",
48
+ "STAMP_DUTY_TAX", "STT_TAX", "TDS_TAX", "MISC", "UNKNOWN",
49
+ ])
50
+ .meta({ id: "TxnType", description: "Transaction type from the description wording. UNKNOWN when the wording is not recognised; never inferred from the units sign alone." });
51
+ export const transactionSchema = z
52
+ .strictObject({
53
+ order: count.describe("Position in the statement, preserving order for same-date rows."),
54
+ date: isoDateSchema.describe("Date as printed on the row, as an ISO calendar date."),
55
+ description: z.string().describe("Transaction text as printed, with wrapped continuation lines joined by a space."),
56
+ amount: numSchema.nullable().describe("Amount in INR as printed; negative for outflows. null when the row prints none."),
57
+ units: numSchema.nullable().describe("Units as printed; negative for outflows. null when the row prints none (tax and *** marker rows)."),
58
+ price: numSchema
59
+ .nullable()
60
+ .describe('NAV per unit for the row. When the template has no Price column it is |amount / units| to 4 places, with raw = "derived". null when it cannot be read or derived.'),
61
+ balance: numSchema.nullable().describe("Unit balance printed after this row: the statement's own running checksum. null when not printed."),
62
+ type: txnTypeSchema,
63
+ dividendRate: z.string().nullable().describe('IDCW rate per unit as printed after "@ Rs." (e.g. "0.50"); null on other rows.'),
64
+ giftFolio: z.string().nullable().describe("Counterparty folio number printed on a gift row; null on other rows."),
65
+ signCorrected: z.boolean().describe("Set when a printed sign was corrected from the running balance; the raw values stay in `raw`."),
66
+ source: sourceSchema,
67
+ })
68
+ .meta({ id: "Transaction", description: "One transaction row, in document order." });
69
+ export const checkStatusSchema = z
70
+ .enum(["pass", "fail", "unavailable", "not_applicable"])
71
+ .meta({
72
+ id: "CheckStatus",
73
+ description: "pass: the identity holds. fail: it does not. unavailable: the statement lacks the evidence to run it (never display as verified). not_applicable: nothing to check.",
74
+ });
75
+ export const checkSchema = z
76
+ .strictObject({
77
+ id: z.string().describe('Check identifier, e.g. "ledger.units". docs/SCHEMA.md lists every id.'),
78
+ status: checkStatusSchema,
79
+ expected: z.exactOptional(z.string()).describe("The value the statement prints, when the check compares a printed value with a computed one."),
80
+ observed: z.exactOptional(z.string()).describe("The value the engine computed or found."),
81
+ tolerance: z.exactOptional(z.string()).describe("Allowed absolute difference, derived only from printed precision (never a percentage of value)."),
82
+ detail: z.exactOptional(z.string()).describe("Plain-language explanation."),
83
+ source: z.exactOptional(sourceSchema.describe("The first offending row or line, when there is one.")),
84
+ })
85
+ .meta({ id: "Check", description: "One verification result, with the evidence behind it." });
86
+ export const planSchema = z.enum(["DIRECT", "REGULAR", "UNKNOWN"]).meta({ id: "Plan", description: "Direct or Regular plan, from the scheme name. The (Advisor: DIRECT) label is the folio's broker code, not the plan." });
87
+ export const planOptionSchema = z
88
+ .enum(["GROWTH", "IDCW_PAYOUT", "IDCW_REINVEST", "UNKNOWN"])
89
+ .meta({ id: "PlanOption", description: "Growth or IDCW option, from the scheme name." });
90
+ const datedValue = (what) => z.strictObject({ date: isoDateSchema, value: numSchema }).nullable().describe(`${what} and its date, as printed in the scheme footer; null when not printed.`);
91
+ export const schemeSchema = z
92
+ .strictObject({
93
+ name: z.string().describe("Scheme name as printed, without the registrar code, ISIN, advisor label or (formerly …)/(Non-Demat) trailers."),
94
+ rtaCode: z.string().describe('Registrar\'s scheme code printed before the name (the part before the first "-").'),
95
+ rta: z.string().describe("Registrar as printed in the scheme header (e.g. CAMS, KFINTECH); UNKNOWN when not printed."),
96
+ isin: z.string().regex(ISIN_RE, "must be a 12-character ISIN").nullable().describe("ISIN as printed; null when the header has none."),
97
+ advisor: z.string().nullable().describe('As labelled on the CAS: "(Advisor: ARN-…/INA…/DIRECT)". Not an advisory relationship.'),
98
+ plan: planSchema,
99
+ option: planOptionSchema,
100
+ nominees: z.array(z.string()).describe("Nominee names as printed. Empty means none are printed, not that there is no nominee."),
101
+ open: numSchema.nullable().describe("Opening unit balance as printed; null when not found."),
102
+ close: numSchema.nullable().describe("Closing unit balance as printed; null when not found."),
103
+ closeCalculated: decimalString
104
+ .nullable()
105
+ .describe("Opening balance plus every row's units, at the closing balance's printed scale. null when either balance is missing. Compared with close by ledger.units."),
106
+ nav: datedValue("NAV per unit"),
107
+ valuation: datedValue("Market value in INR"),
108
+ cost: numSchema.nullable().describe("Total cost value in INR as printed; null when not printed."),
109
+ transactions: z.array(transactionSchema).describe("Rows in document order. Printed balances and order are kept, never re-sorted or recomputed."),
110
+ checks: z.array(checkSchema).describe("Per-scheme checks; see docs/SCHEMA.md."),
111
+ source: sourceSchema.describe("Where the scheme header region starts."),
112
+ footerSource: sourceSchema.nullable().describe("Where the closing balance / NAV / value footer was read (the valuation line when printed). For a summary statement, the holding row. null when no footer was found."),
113
+ })
114
+ .meta({ id: "Scheme", description: "One scheme within a folio, with its rows, footer values and checks. Zero-balance schemes are kept." });
115
+ export const folioSchema = z
116
+ .strictObject({
117
+ folio: z.string().describe('Folio number as printed, e.g. "1234567 / 89". Always a string.'),
118
+ amc: z.string().describe("AMC heading the folio appears under, as printed; UNKNOWN when none was seen."),
119
+ pan: z.string().nullable().describe("PAN printed on the folio line; null when not printed. Never derived from the PDF password."),
120
+ kyc: z.string().nullable().describe('KYC status as printed (e.g. "OK", "NOT OK"); null when not printed.'),
121
+ panKyc: z.string().nullable().describe('PAN status as printed (the second "PAN:" label on the folio line); null when not printed.'),
122
+ holderName: z.string().nullable().describe("Holder name printed under the folio line; null when not recognised."),
123
+ schemes: z.array(schemeSchema),
124
+ })
125
+ .meta({ id: "Folio", description: "One folio at one AMC, in order of first appearance." });
126
+ export const printedTotalSchema = z
127
+ .strictObject({
128
+ label: z.string().describe('The row\'s label as printed, e.g. "Total" or "Grand Total".'),
129
+ cost: numSchema.nullable().describe("Total cost value as printed on the row; null when the row prints none we could place."),
130
+ marketValue: numSchema
131
+ .nullable()
132
+ .describe("Total market value as printed on the row; null when the row prints none we could place. Compared with the schemes' printed values by total.market_value."),
133
+ source: sourceSchema.describe("The total row's line."),
134
+ })
135
+ .meta({
136
+ id: "PrintedTotal",
137
+ description: "The portfolio total a statement prints: the Total row of the PORTFOLIO SUMMARY table (detailed CAS) or of the holdings table (summary CAS). Read as printed, never computed.",
138
+ });
139
+ export const coverageSchema = z
140
+ .strictObject({
141
+ pages: count.describe("Pages in the document."),
142
+ datedRowsSeen: count.describe("Lines in transaction tables that start with a date."),
143
+ transactionsParsed: count.describe("Dated lines kept as transactions."),
144
+ datedRowsSkipped: z.array(z.strictObject({ source: sourceSchema, reason: z.string() })).describe("Dated lines not kept as transactions, with the reason."),
145
+ ambiguousCells: z
146
+ .array(z.strictObject({ source: sourceSchema, text: z.string().describe("The item as printed."), reason: z.string() }))
147
+ .describe("Items on dated rows that fit no column. The text is statement content."),
148
+ schemeRegionsUnbuilt: z.array(z.strictObject({ source: sourceSchema, reason: z.string() })).describe("Scheme header regions that could not be read; their transactions are missing."),
149
+ })
150
+ .meta({ id: "Coverage", description: "What the parser saw and what it could not use: the basis of the coverage report." });
151
+ export const provenanceSchema = z
152
+ .strictObject({
153
+ sha256: z.string().regex(SHA256_RE, "must be 64 lowercase hex digits").describe("SHA-256 of the PDF bytes, lowercase hex. For diagnostics; not a signature."),
154
+ pageCount: count.describe("Pages reported by the PDF."),
155
+ producer: z.string().nullable().describe("PDF Producer metadata as stored in the file; null when absent."),
156
+ creator: z.string().nullable().describe("PDF Creator metadata as stored in the file; null when absent."),
157
+ pdfVersion: z.string().nullable().describe("PDF version from the file header; null when unknown."),
158
+ encrypted: z.boolean().describe("Whether the PDF was password-protected."),
159
+ extractor: z.string().describe('Extractor backend id + version, e.g. "pdfjs-dist@6.3.289".'),
160
+ })
161
+ .meta({ id: "Provenance", description: "Facts about the PDF file itself." });
162
+ export const issuerSchema = z.enum(["CAMS", "KFINTECH", "NSDL", "CDSL"]).meta({ id: "Issuer", description: "Who issued the statement." });
163
+ export const variantSchema = z.enum(["DETAILED", "SUMMARY", "DEMAT"]).meta({ id: "Variant", description: "Statement kind: detailed (with transactions), summary (holdings only) or depository (demat)." });
164
+ const nullableText = (d) => z.string().nullable().describe(d);
165
+ export const casDocumentSchema = z
166
+ .strictObject({
167
+ schemaVersion: z.literal("1").describe("Changes whenever the shape of this document changes."),
168
+ source: z
169
+ .strictObject({
170
+ issuer: issuerSchema,
171
+ variant: variantSchema,
172
+ engineVersion: z.string().describe("Version of the engine that produced this document."),
173
+ })
174
+ .describe("The statement's issuer and variant as detected, and the engine version."),
175
+ provenance: provenanceSchema,
176
+ statementPeriod: z.strictObject({ from: isoDateSchema, to: isoDateSchema }).nullable().describe("Statement period as printed; null when not found."),
177
+ addressee: z
178
+ .strictObject({
179
+ name: nullableText("Name as printed on page 1; null when not found."),
180
+ email: nullableText("Email address as printed; null when not found or not a whole address."),
181
+ mobile: nullableText("Mobile number as printed, separators removed; null when not found or not a whole number."),
182
+ address: nullableText("Postal address as printed, one printed line per line (joined with \\n); null when not found."),
183
+ })
184
+ .describe("The person the statement is addressed to (page 1). Not necessarily every holder."),
185
+ folios: z.array(folioSchema).describe("Folios in order of first appearance."),
186
+ printedTotal: printedTotalSchema.nullable().describe("The statement's own portfolio total row, as printed; null when none was found. Never computed."),
187
+ checks: z.array(checkSchema).describe("Statement-level checks (per-scheme checks are on each scheme), e.g. total.market_value. See docs/SCHEMA.md."),
188
+ coverage: coverageSchema,
189
+ warnings: z.array(z.string()).describe("Plain-language warnings about the parse, e.g. scheme headers that could not be read."),
190
+ })
191
+ .meta({
192
+ $id: CAS_DOCUMENT_SCHEMA_ID,
193
+ title: "CasDocument v1",
194
+ description: "Parsed evidence from one Indian mutual-fund Consolidated Account Statement (CAS). Analytics live in a separate, versioned object. " +
195
+ "Contains personal data (names, PAN, contact details, folios, holdings and transactions): handle it like the statement itself.",
196
+ });
197
+ const pointer = (path) => path.map((p) => `/${String(p).replace(/~/g, "~0").replace(/\//g, "~1")}`).join("");
198
+ /**
199
+ * Checks an untrusted value against CasDocument v1. Unknown properties are
200
+ * rejected. On success `document` is a validated copy of the input.
201
+ */
202
+ export function validateCasDocument(x) {
203
+ const r = casDocumentSchema.safeParse(x);
204
+ if (r.success)
205
+ return { ok: true, document: r.data };
206
+ return { ok: false, issues: r.error.issues.map((i) => ({ path: pointer(i.path), code: i.code, message: i.message })) };
207
+ }
208
+ /** The JSON Schema (draft 2020-12) committed as schema/cas-document.v1.schema.json. */
209
+ export function casDocumentJsonSchema() {
210
+ const { $schema, $id, title, description, ...rest } = z.toJSONSchema(casDocumentSchema, { target: "draft-2020-12" });
211
+ // Identifying keywords first, so the committed file reads top-down.
212
+ // Every property carries its privacy class ("x-privacy"); a field without one throws (privacy.ts).
213
+ return annotatePrivacy({ $schema, $id, title, description, ...rest });
214
+ }
@@ -0,0 +1,34 @@
1
+ "use client";
2
+ // Next.js (App Router) recipe: the CAS is read in the user's browser, never on your server.
3
+ //
4
+ // npm install @sachfolio/cas-reader
5
+ // npx sachfolio-cas copy-assets public/pdfjs
6
+ //
7
+ // pdf.js needs a browser, so the reader is imported when the user picks a file, not during
8
+ // server rendering.
9
+ import { useState } from "react";
10
+
11
+ export default function ReadCas() {
12
+ const [result, setResult] = useState("");
13
+ const [password, setPassword] = useState("");
14
+
15
+ async function onFile(event) {
16
+ const file = event.target.files?.[0];
17
+ if (!file) return;
18
+ const { createCasReader, isCasError } = await import("@sachfolio/cas-reader/browser");
19
+ try {
20
+ const cas = await createCasReader({ assetsUrl: "/pdfjs/" }).readCas(new Uint8Array(await file.arrayBuffer()), password ? { password } : {});
21
+ setResult(JSON.stringify(cas, null, 2));
22
+ } catch (e) {
23
+ setResult(isCasError(e) ? e.code : "Could not read this file.");
24
+ }
25
+ }
26
+
27
+ return (
28
+ <main>
29
+ <input type="password" placeholder="PDF password" autoComplete="off" value={password} onChange={(e) => setPassword(e.target.value)} />
30
+ <input type="file" accept="application/pdf" onChange={onFile} />
31
+ <pre>{result}</pre>
32
+ </main>
33
+ );
34
+ }
@@ -0,0 +1,45 @@
1
+ // A small HTTP service on your own server: POST a CAS PDF, get JSON back.
2
+ // The statement is read in this process; nothing is sent anywhere else.
3
+ //
4
+ // node server.mjs
5
+ // curl --data-binary @statement.pdf -H "X-PDF-Password: ..." "http://127.0.0.1:8080/parse?format=casparser"
6
+ //
7
+ // Put it behind your own authentication. Never log request bodies, passwords or results:
8
+ // they hold the investor's personal data.
9
+ import http from "node:http";
10
+ import { isCasError, parseCas, toCasparser } from "@sachfolio/cas-reader";
11
+ import { createNodeExtractor } from "@sachfolio/cas-reader/node";
12
+
13
+ const MAX_BYTES = 20 * 1024 * 1024;
14
+ const extractor = createNodeExtractor();
15
+
16
+ const server = http.createServer(async (req, res) => {
17
+ const url = new URL(req.url ?? "/", "http://localhost");
18
+ if (req.method !== "POST" || url.pathname !== "/parse") {
19
+ res.writeHead(404).end();
20
+ return;
21
+ }
22
+ const chunks = [];
23
+ let size = 0;
24
+ for await (const chunk of req) {
25
+ size += chunk.length;
26
+ if (size > MAX_BYTES) {
27
+ res.writeHead(413).end();
28
+ return;
29
+ }
30
+ chunks.push(chunk);
31
+ }
32
+ const password = req.headers["x-pdf-password"];
33
+ try {
34
+ const pdf = await extractor.extract(new Uint8Array(Buffer.concat(chunks)), typeof password === "string" ? { password } : {});
35
+ const cas = parseCas(pdf);
36
+ const body = url.searchParams.get("format") === "casparser" ? toCasparser(cas) : cas;
37
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(body));
38
+ } catch (e) {
39
+ // Error codes are safe to return and log; messages never contain statement data.
40
+ if (isCasError(e)) res.writeHead(422, { "content-type": "application/json" }).end(JSON.stringify({ code: e.code, message: e.message }));
41
+ else res.writeHead(500).end();
42
+ }
43
+ });
44
+
45
+ server.listen(8080, "127.0.0.1", () => console.log("listening on http://127.0.0.1:8080/parse"));
@@ -0,0 +1,67 @@
1
+ """Drop-in replacement for casparser.read_cas_pdf, backed by @sachfolio/cas-reader.
2
+
3
+ # before
4
+ import casparser
5
+ data = casparser.read_cas_pdf("cas.pdf", "password", output="json")
6
+ # after
7
+ from read_cas import read_cas_pdf
8
+ data = read_cas_pdf("cas.pdf", "password", output="json")
9
+
10
+ Needs Node 22.13+ and the package installed in a folder (npm install ./sachfolio-cas-reader-*.tgz).
11
+ Set SACHFOLIO_CAS_DIR to that folder if it isn't the current directory.
12
+
13
+ output="json" returns the JSON string casparser would return. output="dict" returns that
14
+ JSON as plain dicts and lists (casparser returns a pydantic model; the keys are the same).
15
+ Decimals stay exact strings, e.g. "4999.75": convert them with decimal.Decimal, never float.
16
+ The password goes over stdin, never on the command line.
17
+ """
18
+
19
+ import json
20
+ import os
21
+ import shutil
22
+ import subprocess
23
+
24
+
25
+ class CasReaderError(Exception):
26
+ """The statement could not be read. `code` is e.g. INCORRECT_PASSWORD or UNKNOWN_TEMPLATE."""
27
+
28
+ def __init__(self, code, message):
29
+ super().__init__(f"{code}: {message}")
30
+ self.code = code
31
+
32
+
33
+ def _command():
34
+ node = shutil.which("node")
35
+ if node is None:
36
+ raise RuntimeError("Node 22.13 or later is needed: https://nodejs.org")
37
+ folder = os.environ.get("SACHFOLIO_CAS_DIR", os.getcwd())
38
+ cli = os.path.join(folder, "node_modules", "@sachfolio", "cas-reader", "dist", "bin", "cas.js")
39
+ if not os.path.exists(cli):
40
+ raise RuntimeError(f"@sachfolio/cas-reader is not installed in {folder}")
41
+ return [node, cli]
42
+
43
+
44
+ def read_cas_pdf(filename, password, output="dict", sort_transactions=True):
45
+ args = _command() + [os.fspath(filename), "--format", "casparser", "--password-stdin"]
46
+ if not sort_transactions:
47
+ args.append("--keep-order")
48
+ proc = subprocess.run(args, input=password + "\n", capture_output=True, text=True, encoding="utf-8")
49
+ if proc.returncode != 0:
50
+ code, _, message = proc.stderr.strip().partition(": ")
51
+ raise CasReaderError(code, message)
52
+ if output == "json":
53
+ return proc.stdout
54
+ if output == "dict":
55
+ return json.loads(proc.stdout)
56
+ raise ValueError('output must be "dict" or "json"')
57
+
58
+
59
+ if __name__ == "__main__":
60
+ import getpass
61
+ import sys
62
+
63
+ if len(sys.argv) != 2:
64
+ sys.exit("usage: python read_cas.py <statement.pdf>")
65
+ data = read_cas_pdf(sys.argv[1], getpass.getpass("PDF password: "))
66
+ schemes = sum(len(f["schemes"]) for f in data["folios"])
67
+ print(f'{data["file_type"]} {data["cas_type"]}: {len(data["folios"])} folios, {schemes} schemes, {len(data["parse_warnings"])} warnings')
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Read a CAS on this device</title>
7
+ </head>
8
+ <body>
9
+ <input type="file" id="cas" accept="application/pdf" />
10
+ <input type="password" id="pw" placeholder="PDF password" autocomplete="off" />
11
+ <pre id="out"></pre>
12
+ <script type="module" src="/main.js"></script>
13
+ </body>
14
+ </html>
@@ -0,0 +1,22 @@
1
+ // Vite recipe: the CAS is read in the user's browser; only what you choose to send leaves it.
2
+ //
3
+ // npm install @sachfolio/cas-reader vite
4
+ // npx sachfolio-cas copy-assets public/pdfjs # pdf.js worker, fonts, cmaps and wasm, served by your own site
5
+ // npx vite build # or: npx vite
6
+ import { createCasReader, isCasError, toCasparser } from "@sachfolio/cas-reader/browser";
7
+
8
+ const reader = createCasReader({ assetsUrl: "/pdfjs/" });
9
+
10
+ document.getElementById("cas").addEventListener("change", async (event) => {
11
+ const file = event.target.files?.[0];
12
+ if (!file) return;
13
+ const out = document.getElementById("out");
14
+ const password = document.getElementById("pw").value;
15
+ try {
16
+ const cas = await reader.readCas(new Uint8Array(await file.arrayBuffer()), password ? { password } : {});
17
+ // Show it, or send it to your server. Holdings for NSDL/CDSL; transactions too for a detailed CAMS/KFintech CAS.
18
+ out.textContent = JSON.stringify(cas.source.variant === "DEMAT" ? cas : toCasparser(cas), null, 2);
19
+ } catch (e) {
20
+ out.textContent = isCasError(e) ? e.code : "Could not read this file.";
21
+ }
22
+ });
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@sachfolio/cas-reader",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-beta.1",
4
+ "description": "Read mutual fund CAS PDFs (CAMS, KFintech, NSDL, CDSL) inside your own app or browser. The PDF and password go to no third party.",
5
+ "keywords": [
6
+ "cas",
7
+ "mutual-fund",
8
+ "cams",
9
+ "kfintech",
10
+ "nsdl",
11
+ "cdsl",
12
+ "casparser",
13
+ "india",
14
+ "pdf"
15
+ ],
16
+ "license": "BUSL-1.1",
17
+ "homepage": "https://sachfolio.com",
18
+ "type": "module",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./node": {
25
+ "types": "./dist/extract/node.d.ts",
26
+ "default": "./dist/extract/node.js"
27
+ },
28
+ "./browser": {
29
+ "types": "./dist/extract/browser.d.ts",
30
+ "default": "./dist/extract/browser.js"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "bin": {
35
+ "sachfolio-cas": "./dist/bin/cas.js"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "examples",
40
+ "LICENSE",
41
+ "NOTICE",
42
+ "README.md",
43
+ "CHANGELOG.md"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "engines": {
49
+ "node": ">=22.13"
50
+ },
51
+ "dependencies": {
52
+ "big.js": "7.0.1",
53
+ "pdfjs-dist": "6.3.289",
54
+ "zod": "4.6.5"
55
+ }
56
+ }