actual-jev 0.1.0 → 0.1.2

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.
@@ -31,7 +31,7 @@ export interface Classification {
31
31
  }
32
32
  export interface JevChoiceClient {
33
33
  systemOne(request: {
34
- state: EntryType;
34
+ state: NonNullable<EntryType>;
35
35
  model: string;
36
36
  questions: {
37
37
  category: ReturnType<typeof choice>;
package/dist/cli.js CHANGED
@@ -97,29 +97,67 @@ async function main() {
97
97
  const { serverURL, password, syncId } = config;
98
98
  if (options.mode === 'interactive' && (!stdin.isTTY || !stdout.isTTY))
99
99
  throw new Error('Interactive mode requires a terminal; use --dry-run or --auto');
100
+ const actualAuthHint = source === 'environment'
101
+ ? 'Check ACTUAL_SERVER_URL and ACTUAL_PASSWORD.'
102
+ : 'Run actual-jev setup to check the Actual server URL and password.';
103
+ const typeSafeAuthHint = source === 'environment' ? 'Check TYPESAFE_API_KEY.' : 'Run actual-jev setup to check the TypeSafe API key.';
104
+ const secrets = [password, config.encryptionPassword, config.apiKey].filter((secret) => Boolean(secret));
105
+ async function attempt(operation, run, authHint) {
106
+ try {
107
+ return await run();
108
+ }
109
+ catch (cause) {
110
+ const message = cause instanceof Error ? cause.message : typeof cause === 'string' ? cause : 'Unknown error';
111
+ const status = cause instanceof Error && 'status' in cause ? cause.status : undefined;
112
+ const rejected = status === 401 || status === 403;
113
+ const detail = rejected
114
+ ? `HTTP ${status}`
115
+ : secrets.reduce((text, secret) => text.replaceAll(secret, '[redacted]'), message);
116
+ const hint = authHint && (rejected || /\b(?:unauthorized|forbidden|invalid-password|token-expired)\b/i.test(message))
117
+ ? ` ${authHint}`
118
+ : '';
119
+ throw new Error(`${operation}: ${detail}${hint}`, { cause });
120
+ }
121
+ }
100
122
  let initialized = false;
101
123
  let writes = false;
124
+ let failed = false;
125
+ async function cleanup(operation, run, authHint) {
126
+ try {
127
+ await attempt(operation, run, authHint);
128
+ }
129
+ catch (error) {
130
+ if (failed && error instanceof Error) {
131
+ console.error(error.message);
132
+ return;
133
+ }
134
+ failed = true;
135
+ throw error;
136
+ }
137
+ }
102
138
  try {
103
139
  await mkdir(dataDir, { recursive: true, mode: 0o700 });
104
- await actual.init({ serverURL: serverURL, password: password, dataDir, verbose: false });
140
+ await attempt('Actual: could not connect to the server', () => actual.init({ serverURL: serverURL, password: password, dataDir, verbose: false }), actualAuthHint);
105
141
  initialized = true;
106
- await actual.downloadBudget(syncId, { password: config.encryptionPassword });
107
- await actual.sync();
142
+ await attempt('Actual: could not download or open the budget', () => actual.downloadBudget(syncId, { password: config.encryptionPassword }), actualAuthHint);
143
+ await attempt('Actual: could not sync the budget', () => actual.sync(), actualAuthHint);
108
144
  const [accounts, payees, queryResult] = await Promise.all([
109
- actual.getAccounts(),
110
- actual.getPayees(),
111
- actual.aqlQuery(actual.q('transactions').select('*').options({ splits: 'grouped' })),
145
+ attempt('Actual: could not load accounts', () => actual.getAccounts()),
146
+ attempt('Actual: could not load payees', () => actual.getPayees()),
147
+ attempt('Actual: could not load transactions', () => actual.aqlQuery(actual.q('transactions').select('*').options({ splits: 'grouped' }))),
112
148
  ]);
113
149
  const transactions = queryResult.data;
114
150
  if (!Array.isArray(transactions))
115
151
  throw new Error('ActualQL did not return transaction rows');
116
152
  const jev = new TypeSafeClient({ apiKey: config.apiKey });
117
- const classifier = await createActualClassifier(actual, {
118
- client: jev,
153
+ const classifier = await attempt('Actual: could not load the classification data', () => createActualClassifier(actual, {
154
+ client: {
155
+ systemOne: (request) => attempt('TypeSafe: could not classify the transaction', () => jev.systemOne(request), typeSafeAuthHint),
156
+ },
119
157
  maxExamplesPerCategory,
120
158
  history: transactions,
121
159
  eligibleAccountIds: new Set(accounts.filter((account) => !account.offbudget).map((account) => account.id)),
122
- });
160
+ }));
123
161
  const transferPayeeAccountIds = new Map(payees.flatMap((payee) => (payee.transfer_acct ? [[payee.id, payee.transfer_acct]] : [])));
124
162
  const categories = classifier.categories;
125
163
  const summary = await runCategorization({
@@ -130,7 +168,7 @@ async function main() {
130
168
  categories,
131
169
  classify: (transaction) => classifier.classify(transaction),
132
170
  updateTransaction: async (id, fields) => {
133
- await actual.updateTransaction(id, fields);
171
+ await attempt('Actual: could not update the transaction', () => actual.updateTransaction(id, fields));
134
172
  writes = true;
135
173
  },
136
174
  print: (line) => console.log(line),
@@ -146,14 +184,18 @@ async function main() {
146
184
  }, options);
147
185
  console.log(`Examined ${summary.examined}; applied ${summary.applied}; would apply ${summary.wouldApply}; skipped ${summary.skipped}; transfers skipped ${summary.transfersSkipped}.`);
148
186
  }
187
+ catch (error) {
188
+ failed = true;
189
+ throw error;
190
+ }
149
191
  finally {
150
192
  if (initialized) {
151
193
  try {
152
194
  if (writes)
153
- await actual.sync();
195
+ await cleanup('Actual: could not sync transaction changes', () => actual.sync(), actualAuthHint);
154
196
  }
155
197
  finally {
156
- await actual.shutdown();
198
+ await cleanup('Actual: could not close the budget', () => actual.shutdown());
157
199
  }
158
200
  }
159
201
  }
package/dist/cli.test.js CHANGED
@@ -31,21 +31,37 @@ import ts from ${JSON.stringify(import.meta.resolve('typescript'))};
31
31
  const actual = ${JSON.stringify(`
32
32
  import { writeFile } from 'node:fs/promises';
33
33
  export async function init(options) {
34
+ if (process.env.FIXTURE_FAILURE === 'actual') throw new Error('unauthorized');
34
35
  if (options.password !== 'fixture-password') throw new Error('Incorrect resolved password');
35
36
  await writeFile(process.env.FIXTURE_LOG, JSON.stringify(options));
36
37
  }
37
- export async function downloadBudget(id) { if (id !== 'fixture-budget') throw new Error('Incorrect budget'); }
38
+ export async function downloadBudget(id) {
39
+ if (process.env.FIXTURE_FAILURE === 'budget') throw new Error('budget-not-found');
40
+ if (id !== 'fixture-budget') throw new Error('Incorrect budget');
41
+ }
38
42
  export async function sync() {}
39
- export async function shutdown() {}
40
- export async function getAccounts() { return []; }
43
+ export async function shutdown() {
44
+ if (process.env.FIXTURE_FAILURE === 'budget') throw new Error('close failed');
45
+ }
46
+ export async function getAccounts() { return [{ id: 'account', name: 'Checking' }]; }
41
47
  export async function getPayees() { return []; }
42
- export async function getCategoryGroups() { return []; }
48
+ export async function getCategoryGroups() {
49
+ return [{ name: 'Expenses', categories: [{ id: 'category', name: 'Groceries' }] }];
50
+ }
43
51
  export async function getNote() { return {}; }
44
- export async function aqlQuery() { return { data: [] }; }
52
+ export async function aqlQuery() {
53
+ return { data: process.env.FIXTURE_FAILURE === 'typesafe' ? [{ id: 'transaction', account: 'account' }] : [] };
54
+ }
45
55
  export function q() { return { select() { return this; }, options() { return this; } }; }
46
56
  export async function updateTransaction() { throw new Error('Unexpected write'); }
47
57
  `)};
48
- const sdk = "export function choice() { throw new Error('Unexpected classification'); } export class TypeSafeClient { constructor(config) { if (config.apiKey !== 'fixture-key') throw new Error('Incorrect resolved API key'); } }";
58
+ const sdk = ${JSON.stringify(`
59
+ export function choice() { return {}; }
60
+ export class TypeSafeClient {
61
+ constructor(config) { if (config.apiKey !== 'fixture-key') throw new Error('Incorrect resolved API key'); }
62
+ async systemOne() { throw Object.assign(new Error('unauthorized: fixture-key'), { status: 401 }); }
63
+ }
64
+ `)};
49
65
  registerHooks({ resolve(specifier, context, next) {
50
66
  if (specifier === '@actual-app/api' || specifier === '@typesafe-ai/sdk') return { url: 'data:text/javascript,' + encodeURIComponent(specifier === '@actual-app/api' ? actual : sdk), shortCircuit: true };
51
67
  if (context.parentURL?.endsWith('.ts') && specifier.startsWith('./') && specifier.endsWith('.js')) return next(specifier.slice(0, -3) + '.ts', context);
@@ -121,6 +137,11 @@ registerHooks({ resolve(specifier, context, next) {
121
137
  // Automation does not even read the personal config, including when it is malformed.
122
138
  await writeFile(userPaths(env, process.platform, root).configFile, 'invalid JSON');
123
139
  assert.match((await run(['--dry-run'], first, connection)).stdout, /Examined 0; applied 0/);
140
+ await assert.rejects(run(['--dry-run'], first, { ...connection, FIXTURE_FAILURE: 'actual' }), /Actual.*connect.*unauthorized.*ACTUAL_PASSWORD/i);
141
+ await assert.rejects(run(['--dry-run'], first, { ...connection, FIXTURE_FAILURE: 'budget' }), /Actual.*close.*close failed\nActual.*download.*budget-not-found/i);
142
+ await assert.rejects(run(['--dry-run'], first, { ...connection, FIXTURE_FAILURE: 'typesafe' }), (error) => error instanceof Error &&
143
+ /TypeSafe.*classify.*401.*TYPESAFE_API_KEY/i.test(error.message) &&
144
+ !error.message.includes('fixture-key'));
124
145
  assert.match((await run(['--env-file', envFile, '--dry-run'])).stdout, /Examined 0; applied 0/);
125
146
  const exportedSummary = (await run(['config', 'show'], first, connection)).stdout;
126
147
  const fileSummary = (await run(['config', 'show', '--env-file', envFile])).stdout;
package/package.json CHANGED
@@ -1,9 +1,20 @@
1
1
  {
2
2
  "name": "actual-jev",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Categorize Actual Budget transactions with TypeSafe Jev",
5
+ "author": "Alessandro Cifani <alessandro.cifani@gmail.com>",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/acifani/actual-jev.git"
10
+ },
11
+ "keywords": [
12
+ "actual",
13
+ "actual-budget",
14
+ "jev"
15
+ ],
5
16
  "type": "module",
6
- "packageManager": "pnpm@12.1.0",
17
+ "packageManager": "pnpm@12.23.0",
7
18
  "engines": {
8
19
  "node": ">=24.10 <25"
9
20
  },
@@ -33,19 +44,19 @@
33
44
  "format": "prettier --write ."
34
45
  },
35
46
  "dependencies": {
36
- "@actual-app/api": "^26.9.0",
37
- "@inquirer/prompts": "^8.7.2",
38
- "@inquirer/search": "^4.3.3",
39
- "@typesafe-ai/sdk": "^0.6.0"
47
+ "@actual-app/api": "^26.11.0",
48
+ "@inquirer/prompts": "^8.8.1",
49
+ "@inquirer/search": "^4.4.1",
50
+ "@typesafe-ai/sdk": "^0.7.0"
40
51
  },
41
52
  "devDependencies": {
42
53
  "@eslint/js": "^10.0.1",
43
54
  "@types/node": "^24.13.6",
44
55
  "@typescript/native": "npm:typescript@^7.0.2",
45
- "eslint": "^10.11.0",
46
- "prettier": "^3.9.9",
56
+ "eslint": "^10.16.0",
57
+ "prettier": "^3.10.1",
47
58
  "tsx": "^4.23.15",
48
59
  "typescript": "npm:@typescript/typescript6@^6.0.2",
49
- "typescript-eslint": "^8.70.1"
60
+ "typescript-eslint": "^8.74.0"
50
61
  }
51
62
  }