@mulmoclaude/accounting-plugin 2.1.0 → 2.2.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 (50) hide show
  1. package/README.md +37 -0
  2. package/dist/server/context.d.ts +45 -3
  3. package/dist/server/context.d.ts.map +1 -1
  4. package/dist/server/eventPublisher.d.ts +9 -4
  5. package/dist/server/eventPublisher.d.ts.map +1 -1
  6. package/dist/server/index.d.ts +1 -0
  7. package/dist/server/index.d.ts.map +1 -1
  8. package/dist/server/router.d.ts +27 -3
  9. package/dist/server/router.d.ts.map +1 -1
  10. package/dist/server/snapshotCache.d.ts +3 -3
  11. package/dist/server/snapshotCache.d.ts.map +1 -1
  12. package/dist/server.cjs +149 -80
  13. package/dist/server.cjs.map +1 -1
  14. package/dist/server.js +149 -80
  15. package/dist/server.js.map +1 -1
  16. package/dist/shared/api.d.ts +12 -0
  17. package/dist/shared/api.d.ts.map +1 -1
  18. package/dist/shared/channels.d.ts +22 -2
  19. package/dist/shared/channels.d.ts.map +1 -1
  20. package/dist/{shared-BZAAF-I4.js → shared-BccLo0Ux.js} +39 -5
  21. package/dist/shared-BccLo0Ux.js.map +1 -0
  22. package/dist/{shared-BpFVwa6Y.cjs → shared-Dgt-i23T.cjs} +50 -4
  23. package/dist/shared-Dgt-i23T.cjs.map +1 -0
  24. package/dist/shared.cjs +3 -1
  25. package/dist/shared.js +2 -2
  26. package/dist/style.css +19 -10
  27. package/dist/vue/View.vue.d.ts +5 -0
  28. package/dist/vue/View.vue.d.ts.map +1 -1
  29. package/dist/vue/api.d.ts +132 -100
  30. package/dist/vue/api.d.ts.map +1 -1
  31. package/dist/vue/components/AccountsModal.vue.d.ts.map +1 -1
  32. package/dist/vue/components/BalanceSheet.vue.d.ts.map +1 -1
  33. package/dist/vue/components/BookSettings.vue.d.ts.map +1 -1
  34. package/dist/vue/components/JournalEntryForm.vue.d.ts.map +1 -1
  35. package/dist/vue/components/JournalList.vue.d.ts.map +1 -1
  36. package/dist/vue/components/Ledger.vue.d.ts.map +1 -1
  37. package/dist/vue/components/NewBookForm.vue.d.ts.map +1 -1
  38. package/dist/vue/components/OpeningBalancesForm.vue.d.ts.map +1 -1
  39. package/dist/vue/components/ProfitLoss.vue.d.ts.map +1 -1
  40. package/dist/vue/hostContext.d.ts +15 -0
  41. package/dist/vue/hostContext.d.ts.map +1 -1
  42. package/dist/vue/useAccountingChannel.d.ts +13 -3
  43. package/dist/vue/useAccountingChannel.d.ts.map +1 -1
  44. package/dist/vue.cjs +227 -98
  45. package/dist/vue.cjs.map +1 -1
  46. package/dist/vue.js +228 -99
  47. package/dist/vue.js.map +1 -1
  48. package/package.json +2 -2
  49. package/dist/shared-BZAAF-I4.js.map +0 -1
  50. package/dist/shared-BpFVwa6Y.cjs.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mulmoclaude/accounting-plugin",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Double-entry accounting plugin for MulmoClaude and MulmoTerminal. Three surfaces: ./shared (isomorphic enums/meta, browser-safe), ./vue (chat View/Preview + canvas app), ./server (createAccountingRouter — the workspace-file-backed backend, wired via dependency injection so it pulls zero host-only infra).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "@mulmoclaude/common": "^1.2.0",
41
- "@mulmoclaude/core": "^3.0.0"
41
+ "@mulmoclaude/core": "^3.1.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "express": "^5.2.1",
@@ -1 +0,0 @@
1
- {"version":3,"file":"shared-BZAAF-I4.js","names":[],"sources":["../src/shared/actions.ts","../src/shared/api.ts","../src/shared/types.ts","../src/shared/channels.ts","../../../common/dist/index.js","../src/shared/paths.ts","../src/shared/fiscalYear.ts","../src/shared/countries.ts","../src/shared/currencies.ts","../src/shared/dates.ts","../src/shared/timeSeriesEnums.ts"],"sourcesContent":["// Single source of truth for the manageAccounting LLM-facing action\n// names. Used by:\n// - definition.ts (the JSON-schema action enum exposed to the LLM)\n// - api.ts (the View's REST helpers — `call(action, args)`)\n// - server/api/routes/accounting.ts (handler-table keys, PREVIEW\n// and MESSAGE_BUILDERS membership)\n// - e2e/fixtures/accounting.ts (mock dispatcher's handler-table)\n//\n// Stays in its own module so server-side callers can import the\n// const without pulling in apiPost / Vue plumbing from `api.ts`.\n//\n// CLAUDE.md \"no magic literals — use existing `as const` objects\"\n// applies here: never reference an action by raw string at any of\n// the call sites above.\n\nexport const ACCOUNTING_ACTIONS = {\n openBook: \"openBook\",\n getBooks: \"getBooks\",\n createBook: \"createBook\",\n updateBook: \"updateBook\",\n deleteBook: \"deleteBook\",\n getAccounts: \"getAccounts\",\n upsertAccount: \"upsertAccount\",\n addEntries: \"addEntries\",\n voidEntry: \"voidEntry\",\n getJournalEntries: \"getJournalEntries\",\n getOpeningBalances: \"getOpeningBalances\",\n setOpeningBalances: \"setOpeningBalances\",\n getReport: \"getReport\",\n getTimeSeries: \"getTimeSeries\",\n rebuildSnapshots: \"rebuildSnapshots\",\n} as const;\n\nexport type AccountingAction = (typeof ACCOUNTING_ACTIONS)[keyof typeof ACCOUNTING_ACTIONS];\n","// Single source of truth for the accounting REST contract — the one\n// dispatch route the plugin owns. Consumed by BOTH the Vue api client\n// (./vue/api.ts) and the server router (./server/router.ts) so the path\n// can't drift between them. Mirrors the host META's\n// `{ apiNamespace: \"accounting\", dispatch: { method: \"POST\", path: \"\" } }`\n// resolved to a full URL.\n//\n// (CLAUDE.md: API routes go through `as const` objects, never hardcoded\n// strings at the call site.)\n\nexport const ACCOUNTING_API = {\n dispatch: {\n path: \"/api/accounting\",\n method: \"POST\",\n },\n} as const;\n","// Single source of truth for the accounting domain + report shapes that\n// cross the server ↔ Vue boundary. Isomorphic (browser-safe): no `node:`\n// or Vue imports reach this graph, so both surfaces `import type` the SAME\n// declaration instead of hand-mirroring it. Adding a field here is seen by\n// server tsc and Vue tsc at once — the drift that lets an API response grow\n// while the frontend type stays stale (#2334) cannot happen.\n//\n// Server-only persistence shapes (AccountingConfig, MonthSnapshot) stay in\n// ./server/types.ts; those never reach the browser.\n\nimport type { SupportedCountryCode } from \"./countries\";\nimport type { FiscalYearEnd } from \"./fiscalYear\";\n\nexport const ACCOUNT_TYPES = [\"asset\", \"liability\", \"equity\", \"income\", \"expense\"] as const;\nexport type AccountType = (typeof ACCOUNT_TYPES)[number];\n\n/** B/S accounts (assets / liabilities / equity). Used by opening\n * balance validation: opening entries reference balance-sheet\n * accounts only. */\nexport const BALANCE_SHEET_ACCOUNT_TYPES: readonly AccountType[] = [\"asset\", \"liability\", \"equity\"];\n\nexport interface Account {\n /** Stable identifier the journal lines reference. Typically a\n * numeric string (\"1000\" / \"2000\" …) but free-form is allowed\n * so the user can adopt their existing numbering. */\n code: string;\n name: string;\n type: AccountType;\n /** Optional free-form note (tax bucket, parent group, …). Not\n * interpreted by the engine — passes through verbatim. */\n note?: string | undefined;\n /** Soft-delete flag. When `false`, the account is hidden from\n * entry/ledger dropdowns but stays visible in Manage Accounts\n * and historical entries — accounting integrity requires that\n * a code referenced by a journal line never disappears. Omitted\n * (treated as active) by default to keep the JSON files clean\n * for books created before this field existed. */\n active?: boolean | undefined;\n}\n\nexport interface BookSummary {\n id: string;\n name: string;\n /** ISO 4217 (e.g. \"USD\" / \"JPY\"). Single-currency per book — no\n * cross-book aggregation. */\n currency: string;\n /** ISO 3166-1 alpha-2 country code (e.g. \"US\" / \"JP\" / \"GB\").\n * Identifies the tax jurisdiction the book is kept under so the\n * Accounting role can give country-aware advice (Japanese T-number\n * under インボイス制度, EU VAT ID, GSTIN, ABN, etc.). Constrained\n * to `SupportedCountryCode` (the curated list shared with the UI\n * dropdown and the LLM tool's JSON-schema enum) so a typo from any\n * ingress path is rejected at the service layer rather than silently\n * persisted. Optional for backward compatibility with books created\n * before the field was introduced; the UI prompts existing books\n * to set it. */\n country?: SupportedCountryCode | undefined;\n /** Calendar month (1-12) on whose LAST DAY the book's fiscal year\n * closes — e.g. 8 = August 31, 12 = December 31 (calendar year).\n * Drives the UI's \"current quarter / current year\" date-range\n * shortcuts. Optional in the persisted shape for backward\n * compatibility with books written before this field existed (and\n * with the earlier \"Q1\"..\"Q4\" token form) — read-side code\n * normalises both via `resolveFiscalYearEnd`, treating an absent\n * value as December. New books require it at the create boundary;\n * the default is 12 (December). */\n fiscalYearEnd?: FiscalYearEnd | undefined;\n createdAt: string;\n}\n\nexport const JOURNAL_ENTRY_KINDS = [\"normal\", \"opening\", \"void\", \"void-marker\"] as const;\nexport type JournalEntryKind = (typeof JOURNAL_ENTRY_KINDS)[number];\n\nexport interface JournalLine {\n accountCode: string;\n /** Use exactly one of debit / credit per line, both as positive\n * numbers. The engine treats them as separate fields rather than\n * a single signed amount so the input matches a standard\n * bookkeeping form. */\n debit?: number | undefined;\n credit?: number | undefined;\n /** Per-line memo (the entry-level memo lives on JournalEntry). */\n memo?: string | undefined;\n /** Counterparty's tax-authority-issued registration ID for this\n * line — Japanese 適格請求書発行事業者登録番号 (T-number), EU\n * VAT identification number, UK VAT registration number, India\n * GSTIN, Australia ABN, etc. Required for input-tax-credit\n * eligibility under the Japanese インボイス制度 (effective\n * 2023-10-01) and equivalent regimes elsewhere. Free-form string;\n * format validation belongs upstream (per-jurisdiction). */\n taxRegistrationId?: string | undefined;\n}\n\nexport interface JournalEntry {\n /** Globally unique within a book — ULID-style; ordering by id\n * reproduces creation order. */\n id: string;\n /** Calendar date the entry is booked for (YYYY-MM-DD). The month\n * part decides which `journal/YYYY-MM.jsonl` file the entry lives\n * in; entries can be for any past / future date. */\n date: string;\n kind: JournalEntryKind;\n lines: JournalLine[];\n /** Entry-level memo. */\n memo?: string | undefined;\n /** When `kind === \"void-marker\"`: id of the entry being voided.\n * When `kind === \"void\"`: the system-generated reverse entry\n * references the original via this field. */\n voidedEntryId?: string | undefined;\n /** Reason supplied by the user when voiding. */\n voidReason?: string | undefined;\n /** When this entry was posted via the \"edit\" flow (void-then-add),\n * this is the id of the entry it replaces. The void + new-entry\n * pair is *not* atomic on the server — the client issues two\n * sequential calls — but recording the link here makes the\n * edit chain queryable later (e.g. \"what corrected entry X?\"). */\n replacesEntryId?: string | undefined;\n /** ISO timestamp the entry was appended to the journal — the\n * authoritative \"when did this hit the books\" clock. Distinct\n * from `date`, which is the user-visible booking date. */\n createdAt: string;\n}\n\n/** Aggregated balance per account at a point in time. The signed\n * number is debit − credit; downstream display logic converts to\n * natural sign per account type (assets debit-positive, liabilities\n * credit-positive). */\nexport interface AccountBalance {\n accountCode: string;\n /** Σ debit − Σ credit across all entries up to and including the\n * snapshot's period end. */\n netDebit: number;\n}\n\n/** Period selector for reports. Either a single closing month or a\n * date range. Always inclusive on both ends. */\nexport type ReportPeriod = { kind: \"month\"; period: string } | { kind: \"range\"; from: string; to: string };\n\n// ── Report result shapes (server computes, Vue renders) ──────────────\n\nexport interface BalanceSheetSection {\n type: AccountType;\n rows: { accountCode: string; accountName: string; balance: number }[];\n total: number;\n}\n\nexport interface BalanceSheet {\n asOf: string; // ISO date; period end\n sections: BalanceSheetSection[];\n /** Σ assets − Σ (liabilities + equity). Should be 0 (the\n * accounting equation); a non-zero here indicates either a\n * rounding artefact or a data problem. */\n imbalance: number;\n}\n\nexport interface ProfitLoss {\n from: string; // inclusive ISO date\n to: string; // inclusive ISO date\n income: { rows: { accountCode: string; accountName: string; amount: number }[]; total: number };\n expense: { rows: { accountCode: string; accountName: string; amount: number }[]; total: number };\n netIncome: number; // income − expense\n}\n\nexport interface LedgerRow {\n entryId: string;\n date: string;\n kind: JournalEntryKind;\n memo?: string | undefined;\n debit: number;\n credit: number;\n /** Running netDebit balance for this account, in entry order. */\n runningBalance: number;\n /** Counterparty tax-registration ID copied from the source\n * journal line (T-number / VAT ID / GSTIN / ABN). Surfaced as a\n * Ledger column when the active account is in the input-tax\n * band (14xx — see `isTaxAccountCode` in\n * src/vue/components/accountNumbering.ts). Carried per row even on\n * non-tax accounts so a future view that wants to show it\n * elsewhere doesn't need a server change. */\n taxRegistrationId?: string | undefined;\n}\n\nexport interface Ledger {\n accountCode: string;\n accountName: string;\n rows: LedgerRow[];\n /** Closing netDebit balance — the sum at the bottom of `rows`. */\n closingBalance: number;\n}\n","// Per-book event-stream contract for the accounting plugin — the\n// reusable channel-name factory + event-kind enum + payload shape.\n// Single source of truth for both publishers (the package's server\n// surface, `eventPublisher`) and subscribers (the Vue View's\n// `useAccountingChannel`), so anyone branching on event kind imports\n// from here and the type system catches drift on either side.\n//\n// Lives in the package's `./shared` (browser-safe) rather than the\n// host META because the backend needs it too — keeping it host-side\n// would force an uphill import. The host-wiring META (toolName /\n// apiNamespace / workspaceDirs / staticChannels) stays in the host's\n// `src/plugins/accounting/meta.ts` so the plugin-barrel codegen\n// discovers it.\n//\n// Browser-safe: no Vue imports, no server-only imports.\n\n/** Channel factory for per-book event streams. Subscribers:\n * `useAccountingChannel(bookId)`. Publisher: the package's server\n * surface `eventPublisher`. */\nexport function bookChannel(bookId: string): string {\n return `accounting:${bookId}`;\n}\n\n/** Book-list-level channel — a book was created / deleted. Subscribers\n * refetch the BookSwitcher dropdown. Mirrors the host META's\n * `staticChannels.accountingBooks` literal (kept in sync by value;\n * the host META stays the codegen-discoverable source for the\n * aggregator merge). */\nexport const ACCOUNTING_BOOKS_CHANNEL = \"accounting:books\";\n\n/** Event kinds that ride `bookChannel(bookId)`. Single source of\n * truth for both publishers (server/accounting) and subscribers\n * (the View) — anyone branching on event kind imports from here\n * and the type system catches drift on either side.\n *\n * - `journal` — addEntry / voidEntry hit the books at `period`.\n * Refetch the journal list and (if the View is\n * showing balances at or after `period`) the\n * relevant report.\n * - `opening` — setOpeningBalances. Affects every period from\n * the opening date forward; refetch everything.\n * - `accounts` — chart-of-accounts mutation that may affect\n * aggregation (account type changed). Refetch\n * accounts and the active report.\n * - `snapshotsRebuilding` / `snapshotsReady` — purely informational;\n * the View can show a \"calculating\" spinner\n * during rebuild, but the lazy-rebuild safety\n * net means a refetch always returns the right\n * answer regardless. */\nexport const BOOK_EVENT_KINDS = {\n journal: \"journal\",\n opening: \"opening\",\n accounts: \"accounts\",\n snapshotsRebuilding: \"snapshots-rebuilding\",\n snapshotsReady: \"snapshots-ready\",\n} as const;\n\nexport type BookEventKind = (typeof BOOK_EVENT_KINDS)[keyof typeof BOOK_EVENT_KINDS];\n\n/** Payload published on `bookChannel(bookId)`. */\nexport interface BookChannelPayload {\n kind: BookEventKind;\n /** YYYY-MM. Present for `journal` (entry month) and the snapshot\n * events (the earliest invalidated month). Absent for `opening`\n * (which invalidates everything) and `accounts`. */\n period?: string;\n}\n","// General-purpose runtime type guards, shared across the MulmoClaude host,\n// bridges, and plugins. This is a leaf package — pure and dependency-free — so\n// any tier can import it without creating an uphill edge.\n//\n// These originated as `server/utils/types.ts` (#504), which centralised 40+\n// hand-written inline `typeof x === \"object\"` checks. They are promoted here so\n// the same guards stop being re-hand-written in every bridge and plugin too.\n/** Narrow `unknown` to a plain object (not null, not array). */\nexport function isRecord(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n/** Narrow `unknown` to any object (not null, arrays allowed).\n * Use `isRecord` when you need to access string keys. */\nexport function isObj(value) {\n return typeof value === \"object\" && value !== null;\n}\n/** Non-empty string after trimming whitespace. */\nexport function isNonEmptyString(value) {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n/** Record whose values are all strings. */\nexport function isStringRecord(value) {\n if (!isRecord(value))\n return false;\n return Object.values(value).every((val) => typeof val === \"string\");\n}\n/** String array (every element is a string). */\nexport function isStringArray(value) {\n return Array.isArray(value) && value.every((val) => typeof val === \"string\");\n}\n/** An array of unknowns. Prefer this over a bare `Array.isArray` in typed code:\n * `Array.isArray(x: unknown)` narrows to `any[]`, silently reintroducing\n * `any`, whereas this keeps the element type `unknown`. */\nexport function isUnknownArray(value) {\n return Array.isArray(value);\n}\n/** Error-like object with a `code` property (e.g. Node.js fs errors). */\nexport function isErrorWithCode(value) {\n return isRecord(value) && typeof value.code === \"string\";\n}\n/** Check that a record has a specific key with a string value. */\nexport function hasStringProp(value, key) {\n return isRecord(value) && typeof value[key] === \"string\";\n}\n/** Check that a record has a specific key with a number value. */\nexport function hasNumberProp(value, key) {\n return isRecord(value) && typeof value[key] === \"number\";\n}\n/** Split a comma-separated env value into trimmed, non-empty entries.\n * `lowercase` folds case for identifiers compared case-insensitively\n * (JIDs, email addresses, hex pubkeys). Absent/empty input → empty list. */\nexport function parseCsvList(raw, opts) {\n return (raw ?? \"\")\n .split(\",\")\n .map((entry) => (opts?.lowercase ? entry.trim().toLowerCase() : entry.trim()))\n .filter(Boolean);\n}\n/** A comma-separated env value as a Set — the canonical allowlist shape,\n * where an empty set is the \"allow all\" sentinel (`set.size === 0`). */\nexport function parseCsvSet(raw, opts) {\n return new Set(parseCsvList(raw, opts));\n}\n/** Normalise an unknown thrown value into a human-readable string. Isomorphic\n * (host, bridges, plugins, Vue) — this is the single home for the helper that\n * #2217 could only consolidate for server code, since `@mulmoclaude/core/utils`\n * is server-only.\n *\n * A non-Error object with a non-empty string `details` (gRPC convention) or\n * `message` field surfaces that field — `details` wins — instead of the\n * `[object Object]` a bare `String(err)` would print; an empty-string field\n * falls through. `fallback` covers the error-boundary idiom where a thrown\n * non-Error should read as a descriptive message rather than `String(err)`\n * noise; omit it in logging contexts where `String(err)` is fine. */\nexport function errorMessage(err, fallback) {\n if (err instanceof Error)\n return err.message;\n if (hasStringProp(err, \"details\") && err.details)\n return err.details;\n if (hasStringProp(err, \"message\") && err.message)\n return err.message;\n if (fallback !== undefined)\n return fallback;\n return String(err);\n}\n/** `Date` → `YYYY-MM-DD` in UTC — for dates that must not shift with the\n * host's local timezone (tool-trace search dirs, API date keys). Isomorphic\n * single source (#2480): the host re-exports it from `server/utils/date.ts`,\n * x-plugin imports it directly. The `@receptron/task-scheduler` copy stays\n * local on purpose — that leaf package is published independently and kept\n * dependency-free. Wall-clock questions use the host's `toLocalIsoDate`. */\nexport function toUtcIsoDate(timestamp) {\n const year = timestamp.getUTCFullYear();\n const month = String(timestamp.getUTCMonth() + 1).padStart(2, \"0\");\n const day = String(timestamp.getUTCDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n}\n// A Map, not an object literal: `{}[char]` reads through the prototype chain,\n// so a future caller widening the regex would silently get `[object Object]`\n// for keys like `constructor`.\nconst HTML_ESCAPES = new Map([\n [\"&\", \"&amp;\"],\n [\"<\", \"&lt;\"],\n [\">\", \"&gt;\"],\n ['\"', \"&quot;\"],\n [\"'\", \"&#39;\"],\n]);\n/** HTML-escape text destined for markup or an attribute value — the fixed\n * five-character map, nothing more. Lives here rather than in\n * `@mulmoclaude/core/wiki` (#2483) because `@mulmoclaude/markdown-utils` is a\n * leaf that core depends on and so cannot import back up; core/wiki\n * re-exports this, keeping its consumers' import path unchanged.\n *\n * Escaping `&` first is what makes a single pass safe — the entities this\n * introduces contain none of the other four characters, so nothing is\n * double-escaped. Not a sanitiser: it neither strips tags nor validates URLs. */\nexport function escapeHtml(value) {\n return value.replace(/[&<>\"']/g, (char) => HTML_ESCAPES.get(char) ?? char);\n}\n/** Split a JWS compact serialization into its three segments, or `null` when the\n * token isn't well-formed. Pure string work, so the Node bridges and the\n * Cloudflare Workers relay — which decode the segments differently (`Buffer` vs\n * `atob`) — can still share this one guard.\n *\n * A JWS compact serialization is EXACTLY three segments. Both a short token and\n * a longer one (a five-segment JWE, or an attacker appending `.junk`) are\n * rejected outright — never parsed from their first three segments, which would\n * let the signed input disagree with the token. */\nexport function splitJwtSegments(token) {\n const [headerSegment, payloadSegment, signatureSegment, ...extraSegments] = token.split(\".\");\n if (headerSegment === undefined || payloadSegment === undefined || signatureSegment === undefined)\n return null;\n if (extraSegments.length > 0)\n return null;\n return { headerSegment, payloadSegment, signatureSegment };\n}\nexport { scanEnvOptions, snakeToLowerCamel } from \"./envScan.js\";\n","// Workspace-relative directories this plugin owns. Single source of\n// truth, consumed by BOTH the server io layer (./server/io.ts) and the\n// host META (src/plugins/accounting/meta.ts → the WORKSPACE_DIRS\n// aggregator), so the on-disk layout can't drift between the backend\n// and the rest of the app.\n//\n// Browser-safe: no node:* imports.\n\nexport const ACCOUNTING_DIRS = {\n /** `data/accounting/config.json` + the books tree below. */\n accounting: \"data/accounting\",\n /** `data/accounting/books/<bookId>/{accounts.json, journal/, snapshots/}`. */\n accountingBooks: \"data/accounting/books\",\n} as const;\n","// Fiscal-year arithmetic for the accounting plugin.\n//\n// Each book stores a `fiscalYearEnd` = the calendar month (1-12) on\n// whose LAST DAY the book's fiscal year closes:\n//\n// 3 → fiscal year ends March 31 (FY runs Apr 1 → Mar 31)\n// 6 → fiscal year ends June 30 (FY runs Jul 1 → Jun 30)\n// 8 → fiscal year ends August 31 (FY runs Sep 1 → Aug 31)\n// 12 → fiscal year ends December 31 (FY runs Jan 1 → Dec 31; default)\n//\n// Any month is allowed — a corporation whose statutory closing date\n// is August 31 stores 8. The quarter / year arithmetic below is fully\n// parametric on the closing month, so a non-calendar-quarter close\n// (e.g. 8) just shifts the fiscal quarters accordingly.\n//\n// \"Current quarter\" / \"current year\" everywhere in the UI refer to\n// the *fiscal* quarter / *fiscal* year that contains today, under the\n// active book's `fiscalYearEnd`. For a December (12) book fiscal\n// quarters and fiscal years coincide with calendar quarters / calendar\n// years; for any other close a shift applies.\n//\n// Legacy books (written when the field was a calendar-quarter token\n// \"Q1\"..\"Q4\") are absorbed by `resolveFiscalYearEnd`, which maps the\n// old tokens to their closing month (Q1→3, Q2→6, Q3→9, Q4→12). The\n// on-disk value is only rewritten the next time the user saves the\n// book — same no-auto-migrate policy the field has always had.\n//\n// All helpers return `YYYY-MM-DD` strings in the user's local\n// timezone — same convention as `dates.ts`.\n\nexport const FISCAL_YEAR_END_MONTHS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as const;\nexport type FiscalYearEnd = (typeof FISCAL_YEAR_END_MONTHS)[number];\n\nexport const DEFAULT_FISCAL_YEAR_END: FiscalYearEnd = 12;\n\n/** Legacy calendar-quarter tokens → closing month, for books written\n * before the field became a month number. */\n// A Map rather than a plain record: the key is caller-supplied, and a\n// record lookup would resolve inherited prototype members (\"constructor\")\n// as if they were stored quarters.\nconst LEGACY_QUARTER_MONTHS = new Map<string, FiscalYearEnd>([\n [\"Q1\", 3],\n [\"Q2\", 6],\n [\"Q3\", 9],\n [\"Q4\", 12],\n]);\n\nexport function isFiscalYearEnd(value: unknown): value is FiscalYearEnd {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= 12;\n}\n\n/** Normalise any stored / inbound value to a concrete closing month.\n * Absent or unrecognised → the default (December); a legacy \"Q1\"..\"Q4\"\n * token → its closing month; a valid 1-12 number → itself. Kept\n * tolerant (unknown input) so a legacy book read from disk — or shared\n * with an older MulmoTerminal — never breaks the UI or a report. */\nexport function resolveFiscalYearEnd(value: unknown): FiscalYearEnd {\n if (isFiscalYearEnd(value)) return value;\n const legacy = typeof value === \"string\" ? LEGACY_QUARTER_MONTHS.get(value) : undefined;\n return legacy ?? DEFAULT_FISCAL_YEAR_END;\n}\n\n/** Last calendar month (1-12) of the fiscal year. The stored token IS\n * the closing month now, so this reads as `resolveFiscalYearEnd` under\n * a name that states intent at the call sites (and still absorbs a\n * stray legacy token defensively). */\nexport function fiscalYearEndMonth(end: FiscalYearEnd): number {\n return resolveFiscalYearEnd(end);\n}\n\n/** Localised label for a fiscal-year-end month, showing that month's\n * last day — e.g. 8 → \"August 31\" / \"8月31日\" / \"31 de agosto\". Uses a\n * fixed non-leap reference year, so February reads as the 28th; this\n * is display only — the engine still computes the real last day\n * (Feb 29 in a leap year) at runtime. */\nexport function fiscalYearEndMonthLabel(month: FiscalYearEnd, locale: string): string {\n // UTC day 0 of the *next* month = last day of `month`, in a fixed\n // non-leap reference year (2001) so the label is stable and\n // timezone-independent.\n const lastDay = new Date(Date.UTC(2001, month, 0));\n try {\n return new Intl.DateTimeFormat(locale, { month: \"long\", day: \"numeric\", timeZone: \"UTC\" }).format(lastDay);\n } catch {\n return String(month);\n }\n}\n\nexport interface DateRange {\n /** Inclusive lower bound (YYYY-MM-DD). Empty string = unbounded. */\n from: string;\n /** Inclusive upper bound (YYYY-MM-DD). Empty string = unbounded. */\n to: string;\n}\n\nfunction pad2(num: number): string {\n return String(num).padStart(2, \"0\");\n}\n\nfunction lastDayOfMonth(year: number, monthZeroBased: number): number {\n // Day 0 of next month = last day of this month, all in local time.\n return new Date(year, monthZeroBased + 1, 0).getDate();\n}\n\nfunction ymd(year: number, monthOneBased: number, day: number): string {\n return `${year}-${pad2(monthOneBased)}-${pad2(day)}`;\n}\n\n/** Fiscal quarter index (0..3) of the given local date under `end`,\n * where 0 is the first quarter of the fiscal year (right after the\n * prior year's close) and 3 is the closing quarter. */\nfunction fiscalQuarterIndex(end: FiscalYearEnd, today: Date): number {\n const closingMonth = fiscalYearEndMonth(end); // 1-based\n const month = today.getMonth() + 1; // 1-based local month\n // Months past the close of the prior fiscal year, mod 12.\n const offset = (month - closingMonth - 1 + 12) % 12;\n return Math.floor(offset / 3);\n}\n\n/** Calendar (year, monthOneBased) of the *first* month of the fiscal\n * quarter at index `index` in the fiscal year that *contains*\n * `today`. Returned both as the first day of that month and as the\n * count of months covered (always 3 — exposed as a constant). */\nfunction fiscalQuarterStart(end: FiscalYearEnd, today: Date, index: number): { year: number; month: number } {\n const closingMonth = fiscalYearEndMonth(end);\n const todayMonth = today.getMonth() + 1;\n const todayYear = today.getFullYear();\n // Month after the close of the prior fiscal year — fiscal-year start month.\n const startMonth = (closingMonth % 12) + 1;\n // The fiscal year that contains `today` started in the calendar\n // year ≤ today's year. Specifically: if today's calendar month is\n // ≥ startMonth (or startMonth is 1, which is the Q4 case), the FY\n // started this calendar year; otherwise it started last year.\n const fyStartYear = todayMonth >= startMonth ? todayYear : todayYear - 1;\n // Month of the requested fiscal quarter's first month, expressed\n // as a 1-based offset from January of fyStartYear.\n const flatMonth = startMonth + index * 3; // 1-based, may exceed 12\n const year = fyStartYear + Math.floor((flatMonth - 1) / 12);\n const month = ((flatMonth - 1) % 12) + 1;\n return { year, month };\n}\n\nfunction quarterRangeAt(end: FiscalYearEnd, today: Date, index: number): DateRange {\n const start = fiscalQuarterStart(end, today, index);\n // Quarter spans 3 calendar months starting at `start`.\n const lastMonthFlat = start.month - 1 + 2; // 0-based offset of the third month\n const lastMonthYear = start.year + Math.floor(lastMonthFlat / 12);\n const lastMonth = (lastMonthFlat % 12) + 1; // 1-based\n const lastDay = lastDayOfMonth(lastMonthYear, lastMonth - 1);\n return {\n from: ymd(start.year, start.month, 1),\n to: ymd(lastMonthYear, lastMonth, lastDay),\n };\n}\n\nexport function currentQuarterRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n return quarterRangeAt(end, today, fiscalQuarterIndex(end, today));\n}\n\nexport function previousQuarterRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n const idx = fiscalQuarterIndex(end, today);\n if (idx > 0) return quarterRangeAt(end, today, idx - 1);\n // Wrap to Q4 of the prior fiscal year. Step `today` back 3 months\n // — that lands inside the prior fiscal year regardless of `end`,\n // and Q4 (closing) is index 3 within whichever FY contains it.\n const stepped = new Date(today.getFullYear(), today.getMonth() - 3, 1);\n return quarterRangeAt(end, stepped, 3);\n}\n\n/** Current fiscal year — Q0 start through Q3 close. */\nexport function currentFiscalYearRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n const first = quarterRangeAt(end, today, 0);\n const last = quarterRangeAt(end, today, 3);\n return { from: first.from, to: last.to };\n}\n\nexport function previousFiscalYearRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n // Step a year back so `quarterRangeAt` resolves the prior FY.\n const stepped = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate());\n return currentFiscalYearRange(end, stepped);\n}\n","// Country utilities for the accounting plugin.\n//\n// The book's country (ISO 3166-1 alpha-2) identifies the tax\n// jurisdiction the book is kept under. The Accounting role uses it\n// to give country-aware advice — Japanese T-number under\n// インボイス制度, EU VAT ID, UK VAT, GSTIN, ABN, etc.\n//\n// Curated against the supported currency list and the tax-regime\n// guidance in `src/config/roles.ts` (Accounting role prompt).\n// Intl.DisplayNames provides the localized human name at render\n// time, so this stays a flat list of codes.\n\n/** ISO 3166-1 alpha-2 country codes shown in the book country\n * dropdown. Curated to cover every jurisdiction the Accounting role\n * has explicit tax-registration advice for, plus the major economies\n * represented in `SUPPORTED_CURRENCY_CODES`. */\nexport const SUPPORTED_COUNTRY_CODES = [\n \"US\",\n \"JP\",\n \"GB\",\n \"CA\",\n \"AU\",\n \"NZ\",\n \"DE\",\n \"FR\",\n \"IT\",\n \"ES\",\n \"NL\",\n \"BE\",\n \"AT\",\n \"IE\",\n \"PT\",\n \"FI\",\n \"SE\",\n \"DK\",\n \"PL\",\n \"CH\",\n \"NO\",\n \"CN\",\n \"KR\",\n \"TW\",\n \"HK\",\n \"SG\",\n \"IN\",\n \"BR\",\n \"MX\",\n] as const;\n\nexport type SupportedCountryCode = (typeof SUPPORTED_COUNTRY_CODES)[number];\n\n/** EU member states as of 2026. Used by the role-prompt advice path\n * to recommend a VAT identification number when the book country is\n * in the EU. */\nexport const EU_COUNTRY_CODES: ReadonlySet<string> = new Set([\n \"AT\",\n \"BE\",\n \"BG\",\n \"CY\",\n \"CZ\",\n \"DE\",\n \"DK\",\n \"EE\",\n \"ES\",\n \"FI\",\n \"FR\",\n \"GR\",\n \"HR\",\n \"HU\",\n \"IE\",\n \"IT\",\n \"LT\",\n \"LU\",\n \"LV\",\n \"MT\",\n \"NL\",\n \"PL\",\n \"PT\",\n \"RO\",\n \"SE\",\n \"SI\",\n \"SK\",\n]);\n\n/** Localized human name for a country code. Falls back to the code\n * itself if the runtime can't resolve the name. */\nexport function localizedCountryName(code: string, locale: string): string {\n try {\n return new Intl.DisplayNames([locale], { type: \"region\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/** Runtime guard for `BookSummary.country`. The type is the union\n * `SupportedCountryCode`, but every entry point that takes user /\n * LLM input arrives as raw `string` (form submit, JSON-RPC body),\n * so the service layer narrows here before persisting. */\nexport function isSupportedCountryCode(value: unknown): value is SupportedCountryCode {\n return SUPPORTED_COUNTRY_CODES.some((code) => code === value);\n}\n\n/** Country-gated UI features. Each key is a feature name; the value\n * is the set of country codes for which the feature is enabled.\n * Components ask `countryHasFeature(\"...\", country)` instead of\n * hard-coding country lists at the call site.\n *\n * Add a new country-specific feature by adding a new key here and\n * reading it via `countryHasFeature`. An unknown / undefined\n * country never has any feature — components fall back to neutral\n * default UI rather than guessing.\n *\n * Mirrors the \"Country-aware tax behaviour\" prose in the\n * Accounting role prompt (`src/config/roles.ts`). The two MUST\n * stay in sync — drift means the LLM and the form give the user\n * contradictory advice. The prompt is the source of truth for\n * agent behaviour; this table is structured-data sibling for the\n * form. */\nexport const COUNTRY_FEATURES = {\n /** Show an amber \"missing tax ID\" warning + helper text on a\n * postable 14xx (input-tax) line whose taxRegistrationId is\n * blank. Limited to jurisdictions where the role prompt\n * explicitly requires the counterparty registration number\n * (JP T-number, EU VAT ID, GB VAT, GSTIN, ABN, NZ GST, CA BN).\n * The \"other countries\" bucket and US (no federal sales-tax\n * registration) intentionally stay quiet. 24xx output-tax\n * lines don't trigger the warning — see `isTaxAccountCode`. */\n warnMissingTaxRegistrationId: new Set<SupportedCountryCode>([\n \"JP\",\n \"GB\",\n \"DE\",\n \"FR\",\n \"IT\",\n \"ES\",\n \"NL\",\n \"BE\",\n \"AT\",\n \"IE\",\n \"PT\",\n \"FI\",\n \"SE\",\n \"DK\",\n \"PL\",\n \"IN\",\n \"AU\",\n \"NZ\",\n \"CA\",\n ]),\n} as const;\n\nexport type CountryFeature = keyof typeof COUNTRY_FEATURES;\n\n/** Resolve a country-gated feature flag. Returns `false` when the\n * country is undefined / unsupported — components default to the\n * neutral path (no warning, no extra UI) rather than guessing. */\nexport function countryHasFeature(feature: CountryFeature, country: SupportedCountryCode | undefined): boolean {\n if (!country) return false;\n return COUNTRY_FEATURES[feature].has(country);\n}\n","// Currency utilities for the accounting plugin.\n//\n// We expose a curated list of ISO 4217 codes for the New Book\n// dropdown — covering the major reserve currencies plus the most\n// requested Asian / regional ones — plus per-currency formatting\n// helpers built on Intl.NumberFormat.\n//\n// The book's currency is per-book metadata (BookSummary.currency)\n// and only matters once the user has opened the book; cross-book\n// aggregation isn't supported.\n\n/** ISO 4217 codes shown in the New Book dropdown. Curated for\n * recognisability — Intl.DisplayNames provides the localised\n * human name at render time, so this stays a flat list of codes. */\nexport const SUPPORTED_CURRENCY_CODES = [\"USD\", \"EUR\", \"JPY\", \"GBP\", \"CNY\", \"KRW\", \"TWD\", \"HKD\", \"SGD\", \"AUD\", \"CAD\", \"CHF\", \"INR\", \"BRL\", \"MXN\"] as const;\n\nexport type SupportedCurrencyCode = (typeof SUPPORTED_CURRENCY_CODES)[number];\n\nconst DEFAULT_FALLBACK_DIGITS = 2;\n\n/** Localised human name for a currency code. Falls back to the\n * code itself if the runtime can't resolve the name. */\nexport function localizedCurrencyName(code: string, locale: string): string {\n try {\n return new Intl.DisplayNames([locale], { type: \"currency\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/** Number of fraction digits ISO 4217 specifies for a currency.\n * JPY = 0, USD = 2, KWD = 3. Used both for amount formatting and\n * for the HTML input step on debit/credit fields. */\nexport function fractionDigitsFor(currency: string): number {\n try {\n const opts = new Intl.NumberFormat(\"en\", { style: \"currency\", currency }).resolvedOptions();\n return opts.maximumFractionDigits ?? DEFAULT_FALLBACK_DIGITS;\n } catch {\n return DEFAULT_FALLBACK_DIGITS;\n }\n}\n\n/** \"1\" for JPY, \"0.01\" for USD, \"0.001\" for KWD. Used as the HTML\n * input step on debit/credit fields so a JPY book doesn't let the\n * user type cents that would just round-trip back through the\n * decimal validator. */\nexport function inputStepFor(currency: string): string {\n const digits = fractionDigitsFor(currency);\n if (digits === 0) return \"1\";\n return (1 / 10 ** digits).toFixed(digits);\n}\n\n/** Locale-aware currency formatter — returns \"¥1,130\" / \"$1,130.00\"\n * etc. Falls back to fixed-point formatting if the runtime can't\n * resolve the currency code; the fallback still respects the\n * currency's natural fraction-digit count so JPY shows whole\n * numbers even on the slow path. */\nexport function formatAmount(value: number, currency: string, locale?: string): string {\n try {\n return new Intl.NumberFormat(locale, { style: \"currency\", currency }).format(value);\n } catch {\n return value.toFixed(fractionDigitsFor(currency));\n }\n}\n\n/** Currency-agnostic amount formatter — \"1,130.00\" — for places that\n * don't carry the currency code on the data path (compact preview\n * envelopes etc.). Use `formatAmount(value, currency)` whenever the\n * currency IS available — the currency-aware path picks the right\n * fraction-digit count automatically (JPY = 0, USD = 2).\n *\n * `locale` mirrors `formatAmount`'s signature: pass an explicit BCP-47\n * locale (`\"en-US\"`, `\"ja-JP\"`, …) when the caller knows the desired\n * grouping / digit-shape; omit to fall back to the runtime default. */\nexport function formatAmountNumeric(value: number, decimals = 2, locale?: string): string {\n return value.toLocaleString(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });\n}\n","// Local-calendar date helpers for the accounting forms.\n//\n// Why not `new Date().toISOString().slice(0, 10)`? `toISOString` is\n// UTC. In a negative-offset zone (US Pacific, Eastern, …) the UTC\n// date crosses to \"tomorrow\" several hours before midnight local,\n// so a naively prefilled date input would post entries into the\n// wrong accounting day. Same mistake near month boundaries flips\n// the default Balance Sheet period to the next month.\n//\n// All four helpers below are pure local-calendar formatters built\n// from `getFullYear` / `getMonth` / `getDate`, which the JS engine\n// resolves in the user's local timezone.\n\nfunction pad2(num: number): string {\n return String(num).padStart(2, \"0\");\n}\n\n/** Today as `YYYY-MM-DD` in the user's local timezone. */\nexport function localDateString(now: Date = new Date()): string {\n return `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}`;\n}\n\n/** Current month as `YYYY-MM` in the user's local timezone. */\nexport function localMonthString(now: Date = new Date()): string {\n return `${now.getFullYear()}-${pad2(now.getMonth() + 1)}`;\n}\n\n/** First day of the current calendar year as `YYYY-MM-DD`. */\nexport function localStartOfYearString(now: Date = new Date()): string {\n return `${now.getFullYear()}-01-01`;\n}\n\n/** Previous calendar month as `YYYY-MM` in the user's local timezone. */\nexport function previousMonthString(now: Date = new Date()): string {\n const target = new Date(now.getFullYear(), now.getMonth() - 1, 1);\n return `${target.getFullYear()}-${pad2(target.getMonth() + 1)}`;\n}\n\n/** Last month of the previous calendar quarter as `YYYY-MM`. Calendar\n * quarters: Q1=Jan–Mar, Q2=Apr–Jun, Q3=Jul–Sep, Q4=Oct–Dec. When the\n * current month is in Q1, this rolls back to December of last year. */\nexport function lastMonthOfPreviousQuarterString(now: Date = new Date()): string {\n const firstMonthOfCurrentQuarter = Math.floor(now.getMonth() / 3) * 3;\n const target = new Date(now.getFullYear(), firstMonthOfCurrentQuarter - 1, 1);\n return `${target.getFullYear()}-${pad2(target.getMonth() + 1)}`;\n}\n\n/** December of the previous calendar year as `YYYY-MM`. */\nexport function decemberOfPreviousYearString(now: Date = new Date()): string {\n return `${now.getFullYear() - 1}-12`;\n}\n","// Single source of truth for the `getTimeSeries` action's enum\n// surfaces — kept outside the server module so the frontend tool\n// definition (`definition.ts`) and the server validator\n// (`server/accounting/timeSeries.ts`) can both import without\n// crossing the src ↔ server boundary in the wrong direction.\n//\n// Adding a new metric / granularity: extend the array here, then\n// extend the corresponding switch / aggregation in\n// `server/accounting/timeSeries.ts`. The LLM tool schema picks up\n// the new value automatically via `definition.ts`'s `enum` field.\n\nexport const TIME_SERIES_METRICS = [\"revenue\", \"expense\", \"netIncome\", \"accountBalance\"] as const;\nexport type TimeSeriesMetric = (typeof TIME_SERIES_METRICS)[number];\n\nexport const TIME_SERIES_GRANULARITIES = [\"month\", \"quarter\", \"year\"] as const;\nexport type TimeSeriesGranularity = (typeof TIME_SERIES_GRANULARITIES)[number];\n"],"mappings":";AAeA,IAAa,qBAAqB;CAChC,UAAU;CACV,UAAU;CACV,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,aAAa;CACb,eAAe;CACf,YAAY;CACZ,WAAW;CACX,mBAAmB;CACnB,oBAAoB;CACpB,oBAAoB;CACpB,WAAW;CACX,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E,GAAG,KAAK,IAAI,SAAS,IAAI,CAAC;AACxD;;AAGA,SAAgB,uBAAuB,sBAAY,IAAI,KAAK,GAAW;CACrE,OAAO,GAAG,IAAI,YAAY,EAAE;AAC9B;;AAGA,SAAgB,oBAAoB,sBAAY,IAAI,KAAK,GAAW;CAClE,MAAM,SAAS,IAAI,KAAK,IAAI,YAAY,GAAG,IAAI,SAAS,IAAI,GAAG,CAAC;CAChE,OAAO,GAAG,OAAO,YAAY,EAAE,GAAG,KAAK,OAAO,SAAS,IAAI,CAAC;AAC9D;;;;AAKA,SAAgB,iCAAiC,sBAAY,IAAI,KAAK,GAAW;CAC/E,MAAM,6BAA6B,KAAK,MAAM,IAAI,SAAS,IAAI,CAAC,IAAI;CACpE,MAAM,SAAS,IAAI,KAAK,IAAI,YAAY,GAAG,6BAA6B,GAAG,CAAC;CAC5E,OAAO,GAAG,OAAO,YAAY,EAAE,GAAG,KAAK,OAAO,SAAS,IAAI,CAAC;AAC9D;;AAGA,SAAgB,6BAA6B,sBAAY,IAAI,KAAK,GAAW;CAC3E,OAAO,GAAG,IAAI,YAAY,IAAI,EAAE;AAClC;;;ACvCA,IAAa,sBAAsB;CAAC;CAAW;CAAW;CAAa;AAAgB;AAGvF,IAAa,4BAA4B;CAAC;CAAS;CAAW;AAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"shared-BpFVwa6Y.cjs","names":[],"sources":["../src/shared/actions.ts","../src/shared/api.ts","../src/shared/types.ts","../src/shared/channels.ts","../../../common/dist/index.js","../src/shared/paths.ts","../src/shared/fiscalYear.ts","../src/shared/countries.ts","../src/shared/currencies.ts","../src/shared/dates.ts","../src/shared/timeSeriesEnums.ts"],"sourcesContent":["// Single source of truth for the manageAccounting LLM-facing action\n// names. Used by:\n// - definition.ts (the JSON-schema action enum exposed to the LLM)\n// - api.ts (the View's REST helpers — `call(action, args)`)\n// - server/api/routes/accounting.ts (handler-table keys, PREVIEW\n// and MESSAGE_BUILDERS membership)\n// - e2e/fixtures/accounting.ts (mock dispatcher's handler-table)\n//\n// Stays in its own module so server-side callers can import the\n// const without pulling in apiPost / Vue plumbing from `api.ts`.\n//\n// CLAUDE.md \"no magic literals — use existing `as const` objects\"\n// applies here: never reference an action by raw string at any of\n// the call sites above.\n\nexport const ACCOUNTING_ACTIONS = {\n openBook: \"openBook\",\n getBooks: \"getBooks\",\n createBook: \"createBook\",\n updateBook: \"updateBook\",\n deleteBook: \"deleteBook\",\n getAccounts: \"getAccounts\",\n upsertAccount: \"upsertAccount\",\n addEntries: \"addEntries\",\n voidEntry: \"voidEntry\",\n getJournalEntries: \"getJournalEntries\",\n getOpeningBalances: \"getOpeningBalances\",\n setOpeningBalances: \"setOpeningBalances\",\n getReport: \"getReport\",\n getTimeSeries: \"getTimeSeries\",\n rebuildSnapshots: \"rebuildSnapshots\",\n} as const;\n\nexport type AccountingAction = (typeof ACCOUNTING_ACTIONS)[keyof typeof ACCOUNTING_ACTIONS];\n","// Single source of truth for the accounting REST contract — the one\n// dispatch route the plugin owns. Consumed by BOTH the Vue api client\n// (./vue/api.ts) and the server router (./server/router.ts) so the path\n// can't drift between them. Mirrors the host META's\n// `{ apiNamespace: \"accounting\", dispatch: { method: \"POST\", path: \"\" } }`\n// resolved to a full URL.\n//\n// (CLAUDE.md: API routes go through `as const` objects, never hardcoded\n// strings at the call site.)\n\nexport const ACCOUNTING_API = {\n dispatch: {\n path: \"/api/accounting\",\n method: \"POST\",\n },\n} as const;\n","// Single source of truth for the accounting domain + report shapes that\n// cross the server ↔ Vue boundary. Isomorphic (browser-safe): no `node:`\n// or Vue imports reach this graph, so both surfaces `import type` the SAME\n// declaration instead of hand-mirroring it. Adding a field here is seen by\n// server tsc and Vue tsc at once — the drift that lets an API response grow\n// while the frontend type stays stale (#2334) cannot happen.\n//\n// Server-only persistence shapes (AccountingConfig, MonthSnapshot) stay in\n// ./server/types.ts; those never reach the browser.\n\nimport type { SupportedCountryCode } from \"./countries\";\nimport type { FiscalYearEnd } from \"./fiscalYear\";\n\nexport const ACCOUNT_TYPES = [\"asset\", \"liability\", \"equity\", \"income\", \"expense\"] as const;\nexport type AccountType = (typeof ACCOUNT_TYPES)[number];\n\n/** B/S accounts (assets / liabilities / equity). Used by opening\n * balance validation: opening entries reference balance-sheet\n * accounts only. */\nexport const BALANCE_SHEET_ACCOUNT_TYPES: readonly AccountType[] = [\"asset\", \"liability\", \"equity\"];\n\nexport interface Account {\n /** Stable identifier the journal lines reference. Typically a\n * numeric string (\"1000\" / \"2000\" …) but free-form is allowed\n * so the user can adopt their existing numbering. */\n code: string;\n name: string;\n type: AccountType;\n /** Optional free-form note (tax bucket, parent group, …). Not\n * interpreted by the engine — passes through verbatim. */\n note?: string | undefined;\n /** Soft-delete flag. When `false`, the account is hidden from\n * entry/ledger dropdowns but stays visible in Manage Accounts\n * and historical entries — accounting integrity requires that\n * a code referenced by a journal line never disappears. Omitted\n * (treated as active) by default to keep the JSON files clean\n * for books created before this field existed. */\n active?: boolean | undefined;\n}\n\nexport interface BookSummary {\n id: string;\n name: string;\n /** ISO 4217 (e.g. \"USD\" / \"JPY\"). Single-currency per book — no\n * cross-book aggregation. */\n currency: string;\n /** ISO 3166-1 alpha-2 country code (e.g. \"US\" / \"JP\" / \"GB\").\n * Identifies the tax jurisdiction the book is kept under so the\n * Accounting role can give country-aware advice (Japanese T-number\n * under インボイス制度, EU VAT ID, GSTIN, ABN, etc.). Constrained\n * to `SupportedCountryCode` (the curated list shared with the UI\n * dropdown and the LLM tool's JSON-schema enum) so a typo from any\n * ingress path is rejected at the service layer rather than silently\n * persisted. Optional for backward compatibility with books created\n * before the field was introduced; the UI prompts existing books\n * to set it. */\n country?: SupportedCountryCode | undefined;\n /** Calendar month (1-12) on whose LAST DAY the book's fiscal year\n * closes — e.g. 8 = August 31, 12 = December 31 (calendar year).\n * Drives the UI's \"current quarter / current year\" date-range\n * shortcuts. Optional in the persisted shape for backward\n * compatibility with books written before this field existed (and\n * with the earlier \"Q1\"..\"Q4\" token form) — read-side code\n * normalises both via `resolveFiscalYearEnd`, treating an absent\n * value as December. New books require it at the create boundary;\n * the default is 12 (December). */\n fiscalYearEnd?: FiscalYearEnd | undefined;\n createdAt: string;\n}\n\nexport const JOURNAL_ENTRY_KINDS = [\"normal\", \"opening\", \"void\", \"void-marker\"] as const;\nexport type JournalEntryKind = (typeof JOURNAL_ENTRY_KINDS)[number];\n\nexport interface JournalLine {\n accountCode: string;\n /** Use exactly one of debit / credit per line, both as positive\n * numbers. The engine treats them as separate fields rather than\n * a single signed amount so the input matches a standard\n * bookkeeping form. */\n debit?: number | undefined;\n credit?: number | undefined;\n /** Per-line memo (the entry-level memo lives on JournalEntry). */\n memo?: string | undefined;\n /** Counterparty's tax-authority-issued registration ID for this\n * line — Japanese 適格請求書発行事業者登録番号 (T-number), EU\n * VAT identification number, UK VAT registration number, India\n * GSTIN, Australia ABN, etc. Required for input-tax-credit\n * eligibility under the Japanese インボイス制度 (effective\n * 2023-10-01) and equivalent regimes elsewhere. Free-form string;\n * format validation belongs upstream (per-jurisdiction). */\n taxRegistrationId?: string | undefined;\n}\n\nexport interface JournalEntry {\n /** Globally unique within a book — ULID-style; ordering by id\n * reproduces creation order. */\n id: string;\n /** Calendar date the entry is booked for (YYYY-MM-DD). The month\n * part decides which `journal/YYYY-MM.jsonl` file the entry lives\n * in; entries can be for any past / future date. */\n date: string;\n kind: JournalEntryKind;\n lines: JournalLine[];\n /** Entry-level memo. */\n memo?: string | undefined;\n /** When `kind === \"void-marker\"`: id of the entry being voided.\n * When `kind === \"void\"`: the system-generated reverse entry\n * references the original via this field. */\n voidedEntryId?: string | undefined;\n /** Reason supplied by the user when voiding. */\n voidReason?: string | undefined;\n /** When this entry was posted via the \"edit\" flow (void-then-add),\n * this is the id of the entry it replaces. The void + new-entry\n * pair is *not* atomic on the server — the client issues two\n * sequential calls — but recording the link here makes the\n * edit chain queryable later (e.g. \"what corrected entry X?\"). */\n replacesEntryId?: string | undefined;\n /** ISO timestamp the entry was appended to the journal — the\n * authoritative \"when did this hit the books\" clock. Distinct\n * from `date`, which is the user-visible booking date. */\n createdAt: string;\n}\n\n/** Aggregated balance per account at a point in time. The signed\n * number is debit − credit; downstream display logic converts to\n * natural sign per account type (assets debit-positive, liabilities\n * credit-positive). */\nexport interface AccountBalance {\n accountCode: string;\n /** Σ debit − Σ credit across all entries up to and including the\n * snapshot's period end. */\n netDebit: number;\n}\n\n/** Period selector for reports. Either a single closing month or a\n * date range. Always inclusive on both ends. */\nexport type ReportPeriod = { kind: \"month\"; period: string } | { kind: \"range\"; from: string; to: string };\n\n// ── Report result shapes (server computes, Vue renders) ──────────────\n\nexport interface BalanceSheetSection {\n type: AccountType;\n rows: { accountCode: string; accountName: string; balance: number }[];\n total: number;\n}\n\nexport interface BalanceSheet {\n asOf: string; // ISO date; period end\n sections: BalanceSheetSection[];\n /** Σ assets − Σ (liabilities + equity). Should be 0 (the\n * accounting equation); a non-zero here indicates either a\n * rounding artefact or a data problem. */\n imbalance: number;\n}\n\nexport interface ProfitLoss {\n from: string; // inclusive ISO date\n to: string; // inclusive ISO date\n income: { rows: { accountCode: string; accountName: string; amount: number }[]; total: number };\n expense: { rows: { accountCode: string; accountName: string; amount: number }[]; total: number };\n netIncome: number; // income − expense\n}\n\nexport interface LedgerRow {\n entryId: string;\n date: string;\n kind: JournalEntryKind;\n memo?: string | undefined;\n debit: number;\n credit: number;\n /** Running netDebit balance for this account, in entry order. */\n runningBalance: number;\n /** Counterparty tax-registration ID copied from the source\n * journal line (T-number / VAT ID / GSTIN / ABN). Surfaced as a\n * Ledger column when the active account is in the input-tax\n * band (14xx — see `isTaxAccountCode` in\n * src/vue/components/accountNumbering.ts). Carried per row even on\n * non-tax accounts so a future view that wants to show it\n * elsewhere doesn't need a server change. */\n taxRegistrationId?: string | undefined;\n}\n\nexport interface Ledger {\n accountCode: string;\n accountName: string;\n rows: LedgerRow[];\n /** Closing netDebit balance — the sum at the bottom of `rows`. */\n closingBalance: number;\n}\n","// Per-book event-stream contract for the accounting plugin — the\n// reusable channel-name factory + event-kind enum + payload shape.\n// Single source of truth for both publishers (the package's server\n// surface, `eventPublisher`) and subscribers (the Vue View's\n// `useAccountingChannel`), so anyone branching on event kind imports\n// from here and the type system catches drift on either side.\n//\n// Lives in the package's `./shared` (browser-safe) rather than the\n// host META because the backend needs it too — keeping it host-side\n// would force an uphill import. The host-wiring META (toolName /\n// apiNamespace / workspaceDirs / staticChannels) stays in the host's\n// `src/plugins/accounting/meta.ts` so the plugin-barrel codegen\n// discovers it.\n//\n// Browser-safe: no Vue imports, no server-only imports.\n\n/** Channel factory for per-book event streams. Subscribers:\n * `useAccountingChannel(bookId)`. Publisher: the package's server\n * surface `eventPublisher`. */\nexport function bookChannel(bookId: string): string {\n return `accounting:${bookId}`;\n}\n\n/** Book-list-level channel — a book was created / deleted. Subscribers\n * refetch the BookSwitcher dropdown. Mirrors the host META's\n * `staticChannels.accountingBooks` literal (kept in sync by value;\n * the host META stays the codegen-discoverable source for the\n * aggregator merge). */\nexport const ACCOUNTING_BOOKS_CHANNEL = \"accounting:books\";\n\n/** Event kinds that ride `bookChannel(bookId)`. Single source of\n * truth for both publishers (server/accounting) and subscribers\n * (the View) — anyone branching on event kind imports from here\n * and the type system catches drift on either side.\n *\n * - `journal` — addEntry / voidEntry hit the books at `period`.\n * Refetch the journal list and (if the View is\n * showing balances at or after `period`) the\n * relevant report.\n * - `opening` — setOpeningBalances. Affects every period from\n * the opening date forward; refetch everything.\n * - `accounts` — chart-of-accounts mutation that may affect\n * aggregation (account type changed). Refetch\n * accounts and the active report.\n * - `snapshotsRebuilding` / `snapshotsReady` — purely informational;\n * the View can show a \"calculating\" spinner\n * during rebuild, but the lazy-rebuild safety\n * net means a refetch always returns the right\n * answer regardless. */\nexport const BOOK_EVENT_KINDS = {\n journal: \"journal\",\n opening: \"opening\",\n accounts: \"accounts\",\n snapshotsRebuilding: \"snapshots-rebuilding\",\n snapshotsReady: \"snapshots-ready\",\n} as const;\n\nexport type BookEventKind = (typeof BOOK_EVENT_KINDS)[keyof typeof BOOK_EVENT_KINDS];\n\n/** Payload published on `bookChannel(bookId)`. */\nexport interface BookChannelPayload {\n kind: BookEventKind;\n /** YYYY-MM. Present for `journal` (entry month) and the snapshot\n * events (the earliest invalidated month). Absent for `opening`\n * (which invalidates everything) and `accounts`. */\n period?: string;\n}\n","// General-purpose runtime type guards, shared across the MulmoClaude host,\n// bridges, and plugins. This is a leaf package — pure and dependency-free — so\n// any tier can import it without creating an uphill edge.\n//\n// These originated as `server/utils/types.ts` (#504), which centralised 40+\n// hand-written inline `typeof x === \"object\"` checks. They are promoted here so\n// the same guards stop being re-hand-written in every bridge and plugin too.\n/** Narrow `unknown` to a plain object (not null, not array). */\nexport function isRecord(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n/** Narrow `unknown` to any object (not null, arrays allowed).\n * Use `isRecord` when you need to access string keys. */\nexport function isObj(value) {\n return typeof value === \"object\" && value !== null;\n}\n/** Non-empty string after trimming whitespace. */\nexport function isNonEmptyString(value) {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n/** Record whose values are all strings. */\nexport function isStringRecord(value) {\n if (!isRecord(value))\n return false;\n return Object.values(value).every((val) => typeof val === \"string\");\n}\n/** String array (every element is a string). */\nexport function isStringArray(value) {\n return Array.isArray(value) && value.every((val) => typeof val === \"string\");\n}\n/** An array of unknowns. Prefer this over a bare `Array.isArray` in typed code:\n * `Array.isArray(x: unknown)` narrows to `any[]`, silently reintroducing\n * `any`, whereas this keeps the element type `unknown`. */\nexport function isUnknownArray(value) {\n return Array.isArray(value);\n}\n/** Error-like object with a `code` property (e.g. Node.js fs errors). */\nexport function isErrorWithCode(value) {\n return isRecord(value) && typeof value.code === \"string\";\n}\n/** Check that a record has a specific key with a string value. */\nexport function hasStringProp(value, key) {\n return isRecord(value) && typeof value[key] === \"string\";\n}\n/** Check that a record has a specific key with a number value. */\nexport function hasNumberProp(value, key) {\n return isRecord(value) && typeof value[key] === \"number\";\n}\n/** Split a comma-separated env value into trimmed, non-empty entries.\n * `lowercase` folds case for identifiers compared case-insensitively\n * (JIDs, email addresses, hex pubkeys). Absent/empty input → empty list. */\nexport function parseCsvList(raw, opts) {\n return (raw ?? \"\")\n .split(\",\")\n .map((entry) => (opts?.lowercase ? entry.trim().toLowerCase() : entry.trim()))\n .filter(Boolean);\n}\n/** A comma-separated env value as a Set — the canonical allowlist shape,\n * where an empty set is the \"allow all\" sentinel (`set.size === 0`). */\nexport function parseCsvSet(raw, opts) {\n return new Set(parseCsvList(raw, opts));\n}\n/** Normalise an unknown thrown value into a human-readable string. Isomorphic\n * (host, bridges, plugins, Vue) — this is the single home for the helper that\n * #2217 could only consolidate for server code, since `@mulmoclaude/core/utils`\n * is server-only.\n *\n * A non-Error object with a non-empty string `details` (gRPC convention) or\n * `message` field surfaces that field — `details` wins — instead of the\n * `[object Object]` a bare `String(err)` would print; an empty-string field\n * falls through. `fallback` covers the error-boundary idiom where a thrown\n * non-Error should read as a descriptive message rather than `String(err)`\n * noise; omit it in logging contexts where `String(err)` is fine. */\nexport function errorMessage(err, fallback) {\n if (err instanceof Error)\n return err.message;\n if (hasStringProp(err, \"details\") && err.details)\n return err.details;\n if (hasStringProp(err, \"message\") && err.message)\n return err.message;\n if (fallback !== undefined)\n return fallback;\n return String(err);\n}\n/** `Date` → `YYYY-MM-DD` in UTC — for dates that must not shift with the\n * host's local timezone (tool-trace search dirs, API date keys). Isomorphic\n * single source (#2480): the host re-exports it from `server/utils/date.ts`,\n * x-plugin imports it directly. The `@receptron/task-scheduler` copy stays\n * local on purpose — that leaf package is published independently and kept\n * dependency-free. Wall-clock questions use the host's `toLocalIsoDate`. */\nexport function toUtcIsoDate(timestamp) {\n const year = timestamp.getUTCFullYear();\n const month = String(timestamp.getUTCMonth() + 1).padStart(2, \"0\");\n const day = String(timestamp.getUTCDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n}\n// A Map, not an object literal: `{}[char]` reads through the prototype chain,\n// so a future caller widening the regex would silently get `[object Object]`\n// for keys like `constructor`.\nconst HTML_ESCAPES = new Map([\n [\"&\", \"&amp;\"],\n [\"<\", \"&lt;\"],\n [\">\", \"&gt;\"],\n ['\"', \"&quot;\"],\n [\"'\", \"&#39;\"],\n]);\n/** HTML-escape text destined for markup or an attribute value — the fixed\n * five-character map, nothing more. Lives here rather than in\n * `@mulmoclaude/core/wiki` (#2483) because `@mulmoclaude/markdown-utils` is a\n * leaf that core depends on and so cannot import back up; core/wiki\n * re-exports this, keeping its consumers' import path unchanged.\n *\n * Escaping `&` first is what makes a single pass safe — the entities this\n * introduces contain none of the other four characters, so nothing is\n * double-escaped. Not a sanitiser: it neither strips tags nor validates URLs. */\nexport function escapeHtml(value) {\n return value.replace(/[&<>\"']/g, (char) => HTML_ESCAPES.get(char) ?? char);\n}\n/** Split a JWS compact serialization into its three segments, or `null` when the\n * token isn't well-formed. Pure string work, so the Node bridges and the\n * Cloudflare Workers relay — which decode the segments differently (`Buffer` vs\n * `atob`) — can still share this one guard.\n *\n * A JWS compact serialization is EXACTLY three segments. Both a short token and\n * a longer one (a five-segment JWE, or an attacker appending `.junk`) are\n * rejected outright — never parsed from their first three segments, which would\n * let the signed input disagree with the token. */\nexport function splitJwtSegments(token) {\n const [headerSegment, payloadSegment, signatureSegment, ...extraSegments] = token.split(\".\");\n if (headerSegment === undefined || payloadSegment === undefined || signatureSegment === undefined)\n return null;\n if (extraSegments.length > 0)\n return null;\n return { headerSegment, payloadSegment, signatureSegment };\n}\nexport { scanEnvOptions, snakeToLowerCamel } from \"./envScan.js\";\n","// Workspace-relative directories this plugin owns. Single source of\n// truth, consumed by BOTH the server io layer (./server/io.ts) and the\n// host META (src/plugins/accounting/meta.ts → the WORKSPACE_DIRS\n// aggregator), so the on-disk layout can't drift between the backend\n// and the rest of the app.\n//\n// Browser-safe: no node:* imports.\n\nexport const ACCOUNTING_DIRS = {\n /** `data/accounting/config.json` + the books tree below. */\n accounting: \"data/accounting\",\n /** `data/accounting/books/<bookId>/{accounts.json, journal/, snapshots/}`. */\n accountingBooks: \"data/accounting/books\",\n} as const;\n","// Fiscal-year arithmetic for the accounting plugin.\n//\n// Each book stores a `fiscalYearEnd` = the calendar month (1-12) on\n// whose LAST DAY the book's fiscal year closes:\n//\n// 3 → fiscal year ends March 31 (FY runs Apr 1 → Mar 31)\n// 6 → fiscal year ends June 30 (FY runs Jul 1 → Jun 30)\n// 8 → fiscal year ends August 31 (FY runs Sep 1 → Aug 31)\n// 12 → fiscal year ends December 31 (FY runs Jan 1 → Dec 31; default)\n//\n// Any month is allowed — a corporation whose statutory closing date\n// is August 31 stores 8. The quarter / year arithmetic below is fully\n// parametric on the closing month, so a non-calendar-quarter close\n// (e.g. 8) just shifts the fiscal quarters accordingly.\n//\n// \"Current quarter\" / \"current year\" everywhere in the UI refer to\n// the *fiscal* quarter / *fiscal* year that contains today, under the\n// active book's `fiscalYearEnd`. For a December (12) book fiscal\n// quarters and fiscal years coincide with calendar quarters / calendar\n// years; for any other close a shift applies.\n//\n// Legacy books (written when the field was a calendar-quarter token\n// \"Q1\"..\"Q4\") are absorbed by `resolveFiscalYearEnd`, which maps the\n// old tokens to their closing month (Q1→3, Q2→6, Q3→9, Q4→12). The\n// on-disk value is only rewritten the next time the user saves the\n// book — same no-auto-migrate policy the field has always had.\n//\n// All helpers return `YYYY-MM-DD` strings in the user's local\n// timezone — same convention as `dates.ts`.\n\nexport const FISCAL_YEAR_END_MONTHS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as const;\nexport type FiscalYearEnd = (typeof FISCAL_YEAR_END_MONTHS)[number];\n\nexport const DEFAULT_FISCAL_YEAR_END: FiscalYearEnd = 12;\n\n/** Legacy calendar-quarter tokens → closing month, for books written\n * before the field became a month number. */\n// A Map rather than a plain record: the key is caller-supplied, and a\n// record lookup would resolve inherited prototype members (\"constructor\")\n// as if they were stored quarters.\nconst LEGACY_QUARTER_MONTHS = new Map<string, FiscalYearEnd>([\n [\"Q1\", 3],\n [\"Q2\", 6],\n [\"Q3\", 9],\n [\"Q4\", 12],\n]);\n\nexport function isFiscalYearEnd(value: unknown): value is FiscalYearEnd {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= 12;\n}\n\n/** Normalise any stored / inbound value to a concrete closing month.\n * Absent or unrecognised → the default (December); a legacy \"Q1\"..\"Q4\"\n * token → its closing month; a valid 1-12 number → itself. Kept\n * tolerant (unknown input) so a legacy book read from disk — or shared\n * with an older MulmoTerminal — never breaks the UI or a report. */\nexport function resolveFiscalYearEnd(value: unknown): FiscalYearEnd {\n if (isFiscalYearEnd(value)) return value;\n const legacy = typeof value === \"string\" ? LEGACY_QUARTER_MONTHS.get(value) : undefined;\n return legacy ?? DEFAULT_FISCAL_YEAR_END;\n}\n\n/** Last calendar month (1-12) of the fiscal year. The stored token IS\n * the closing month now, so this reads as `resolveFiscalYearEnd` under\n * a name that states intent at the call sites (and still absorbs a\n * stray legacy token defensively). */\nexport function fiscalYearEndMonth(end: FiscalYearEnd): number {\n return resolveFiscalYearEnd(end);\n}\n\n/** Localised label for a fiscal-year-end month, showing that month's\n * last day — e.g. 8 → \"August 31\" / \"8月31日\" / \"31 de agosto\". Uses a\n * fixed non-leap reference year, so February reads as the 28th; this\n * is display only — the engine still computes the real last day\n * (Feb 29 in a leap year) at runtime. */\nexport function fiscalYearEndMonthLabel(month: FiscalYearEnd, locale: string): string {\n // UTC day 0 of the *next* month = last day of `month`, in a fixed\n // non-leap reference year (2001) so the label is stable and\n // timezone-independent.\n const lastDay = new Date(Date.UTC(2001, month, 0));\n try {\n return new Intl.DateTimeFormat(locale, { month: \"long\", day: \"numeric\", timeZone: \"UTC\" }).format(lastDay);\n } catch {\n return String(month);\n }\n}\n\nexport interface DateRange {\n /** Inclusive lower bound (YYYY-MM-DD). Empty string = unbounded. */\n from: string;\n /** Inclusive upper bound (YYYY-MM-DD). Empty string = unbounded. */\n to: string;\n}\n\nfunction pad2(num: number): string {\n return String(num).padStart(2, \"0\");\n}\n\nfunction lastDayOfMonth(year: number, monthZeroBased: number): number {\n // Day 0 of next month = last day of this month, all in local time.\n return new Date(year, monthZeroBased + 1, 0).getDate();\n}\n\nfunction ymd(year: number, monthOneBased: number, day: number): string {\n return `${year}-${pad2(monthOneBased)}-${pad2(day)}`;\n}\n\n/** Fiscal quarter index (0..3) of the given local date under `end`,\n * where 0 is the first quarter of the fiscal year (right after the\n * prior year's close) and 3 is the closing quarter. */\nfunction fiscalQuarterIndex(end: FiscalYearEnd, today: Date): number {\n const closingMonth = fiscalYearEndMonth(end); // 1-based\n const month = today.getMonth() + 1; // 1-based local month\n // Months past the close of the prior fiscal year, mod 12.\n const offset = (month - closingMonth - 1 + 12) % 12;\n return Math.floor(offset / 3);\n}\n\n/** Calendar (year, monthOneBased) of the *first* month of the fiscal\n * quarter at index `index` in the fiscal year that *contains*\n * `today`. Returned both as the first day of that month and as the\n * count of months covered (always 3 — exposed as a constant). */\nfunction fiscalQuarterStart(end: FiscalYearEnd, today: Date, index: number): { year: number; month: number } {\n const closingMonth = fiscalYearEndMonth(end);\n const todayMonth = today.getMonth() + 1;\n const todayYear = today.getFullYear();\n // Month after the close of the prior fiscal year — fiscal-year start month.\n const startMonth = (closingMonth % 12) + 1;\n // The fiscal year that contains `today` started in the calendar\n // year ≤ today's year. Specifically: if today's calendar month is\n // ≥ startMonth (or startMonth is 1, which is the Q4 case), the FY\n // started this calendar year; otherwise it started last year.\n const fyStartYear = todayMonth >= startMonth ? todayYear : todayYear - 1;\n // Month of the requested fiscal quarter's first month, expressed\n // as a 1-based offset from January of fyStartYear.\n const flatMonth = startMonth + index * 3; // 1-based, may exceed 12\n const year = fyStartYear + Math.floor((flatMonth - 1) / 12);\n const month = ((flatMonth - 1) % 12) + 1;\n return { year, month };\n}\n\nfunction quarterRangeAt(end: FiscalYearEnd, today: Date, index: number): DateRange {\n const start = fiscalQuarterStart(end, today, index);\n // Quarter spans 3 calendar months starting at `start`.\n const lastMonthFlat = start.month - 1 + 2; // 0-based offset of the third month\n const lastMonthYear = start.year + Math.floor(lastMonthFlat / 12);\n const lastMonth = (lastMonthFlat % 12) + 1; // 1-based\n const lastDay = lastDayOfMonth(lastMonthYear, lastMonth - 1);\n return {\n from: ymd(start.year, start.month, 1),\n to: ymd(lastMonthYear, lastMonth, lastDay),\n };\n}\n\nexport function currentQuarterRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n return quarterRangeAt(end, today, fiscalQuarterIndex(end, today));\n}\n\nexport function previousQuarterRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n const idx = fiscalQuarterIndex(end, today);\n if (idx > 0) return quarterRangeAt(end, today, idx - 1);\n // Wrap to Q4 of the prior fiscal year. Step `today` back 3 months\n // — that lands inside the prior fiscal year regardless of `end`,\n // and Q4 (closing) is index 3 within whichever FY contains it.\n const stepped = new Date(today.getFullYear(), today.getMonth() - 3, 1);\n return quarterRangeAt(end, stepped, 3);\n}\n\n/** Current fiscal year — Q0 start through Q3 close. */\nexport function currentFiscalYearRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n const first = quarterRangeAt(end, today, 0);\n const last = quarterRangeAt(end, today, 3);\n return { from: first.from, to: last.to };\n}\n\nexport function previousFiscalYearRange(end: FiscalYearEnd, today: Date = new Date()): DateRange {\n // Step a year back so `quarterRangeAt` resolves the prior FY.\n const stepped = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate());\n return currentFiscalYearRange(end, stepped);\n}\n","// Country utilities for the accounting plugin.\n//\n// The book's country (ISO 3166-1 alpha-2) identifies the tax\n// jurisdiction the book is kept under. The Accounting role uses it\n// to give country-aware advice — Japanese T-number under\n// インボイス制度, EU VAT ID, UK VAT, GSTIN, ABN, etc.\n//\n// Curated against the supported currency list and the tax-regime\n// guidance in `src/config/roles.ts` (Accounting role prompt).\n// Intl.DisplayNames provides the localized human name at render\n// time, so this stays a flat list of codes.\n\n/** ISO 3166-1 alpha-2 country codes shown in the book country\n * dropdown. Curated to cover every jurisdiction the Accounting role\n * has explicit tax-registration advice for, plus the major economies\n * represented in `SUPPORTED_CURRENCY_CODES`. */\nexport const SUPPORTED_COUNTRY_CODES = [\n \"US\",\n \"JP\",\n \"GB\",\n \"CA\",\n \"AU\",\n \"NZ\",\n \"DE\",\n \"FR\",\n \"IT\",\n \"ES\",\n \"NL\",\n \"BE\",\n \"AT\",\n \"IE\",\n \"PT\",\n \"FI\",\n \"SE\",\n \"DK\",\n \"PL\",\n \"CH\",\n \"NO\",\n \"CN\",\n \"KR\",\n \"TW\",\n \"HK\",\n \"SG\",\n \"IN\",\n \"BR\",\n \"MX\",\n] as const;\n\nexport type SupportedCountryCode = (typeof SUPPORTED_COUNTRY_CODES)[number];\n\n/** EU member states as of 2026. Used by the role-prompt advice path\n * to recommend a VAT identification number when the book country is\n * in the EU. */\nexport const EU_COUNTRY_CODES: ReadonlySet<string> = new Set([\n \"AT\",\n \"BE\",\n \"BG\",\n \"CY\",\n \"CZ\",\n \"DE\",\n \"DK\",\n \"EE\",\n \"ES\",\n \"FI\",\n \"FR\",\n \"GR\",\n \"HR\",\n \"HU\",\n \"IE\",\n \"IT\",\n \"LT\",\n \"LU\",\n \"LV\",\n \"MT\",\n \"NL\",\n \"PL\",\n \"PT\",\n \"RO\",\n \"SE\",\n \"SI\",\n \"SK\",\n]);\n\n/** Localized human name for a country code. Falls back to the code\n * itself if the runtime can't resolve the name. */\nexport function localizedCountryName(code: string, locale: string): string {\n try {\n return new Intl.DisplayNames([locale], { type: \"region\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/** Runtime guard for `BookSummary.country`. The type is the union\n * `SupportedCountryCode`, but every entry point that takes user /\n * LLM input arrives as raw `string` (form submit, JSON-RPC body),\n * so the service layer narrows here before persisting. */\nexport function isSupportedCountryCode(value: unknown): value is SupportedCountryCode {\n return SUPPORTED_COUNTRY_CODES.some((code) => code === value);\n}\n\n/** Country-gated UI features. Each key is a feature name; the value\n * is the set of country codes for which the feature is enabled.\n * Components ask `countryHasFeature(\"...\", country)` instead of\n * hard-coding country lists at the call site.\n *\n * Add a new country-specific feature by adding a new key here and\n * reading it via `countryHasFeature`. An unknown / undefined\n * country never has any feature — components fall back to neutral\n * default UI rather than guessing.\n *\n * Mirrors the \"Country-aware tax behaviour\" prose in the\n * Accounting role prompt (`src/config/roles.ts`). The two MUST\n * stay in sync — drift means the LLM and the form give the user\n * contradictory advice. The prompt is the source of truth for\n * agent behaviour; this table is structured-data sibling for the\n * form. */\nexport const COUNTRY_FEATURES = {\n /** Show an amber \"missing tax ID\" warning + helper text on a\n * postable 14xx (input-tax) line whose taxRegistrationId is\n * blank. Limited to jurisdictions where the role prompt\n * explicitly requires the counterparty registration number\n * (JP T-number, EU VAT ID, GB VAT, GSTIN, ABN, NZ GST, CA BN).\n * The \"other countries\" bucket and US (no federal sales-tax\n * registration) intentionally stay quiet. 24xx output-tax\n * lines don't trigger the warning — see `isTaxAccountCode`. */\n warnMissingTaxRegistrationId: new Set<SupportedCountryCode>([\n \"JP\",\n \"GB\",\n \"DE\",\n \"FR\",\n \"IT\",\n \"ES\",\n \"NL\",\n \"BE\",\n \"AT\",\n \"IE\",\n \"PT\",\n \"FI\",\n \"SE\",\n \"DK\",\n \"PL\",\n \"IN\",\n \"AU\",\n \"NZ\",\n \"CA\",\n ]),\n} as const;\n\nexport type CountryFeature = keyof typeof COUNTRY_FEATURES;\n\n/** Resolve a country-gated feature flag. Returns `false` when the\n * country is undefined / unsupported — components default to the\n * neutral path (no warning, no extra UI) rather than guessing. */\nexport function countryHasFeature(feature: CountryFeature, country: SupportedCountryCode | undefined): boolean {\n if (!country) return false;\n return COUNTRY_FEATURES[feature].has(country);\n}\n","// Currency utilities for the accounting plugin.\n//\n// We expose a curated list of ISO 4217 codes for the New Book\n// dropdown — covering the major reserve currencies plus the most\n// requested Asian / regional ones — plus per-currency formatting\n// helpers built on Intl.NumberFormat.\n//\n// The book's currency is per-book metadata (BookSummary.currency)\n// and only matters once the user has opened the book; cross-book\n// aggregation isn't supported.\n\n/** ISO 4217 codes shown in the New Book dropdown. Curated for\n * recognisability — Intl.DisplayNames provides the localised\n * human name at render time, so this stays a flat list of codes. */\nexport const SUPPORTED_CURRENCY_CODES = [\"USD\", \"EUR\", \"JPY\", \"GBP\", \"CNY\", \"KRW\", \"TWD\", \"HKD\", \"SGD\", \"AUD\", \"CAD\", \"CHF\", \"INR\", \"BRL\", \"MXN\"] as const;\n\nexport type SupportedCurrencyCode = (typeof SUPPORTED_CURRENCY_CODES)[number];\n\nconst DEFAULT_FALLBACK_DIGITS = 2;\n\n/** Localised human name for a currency code. Falls back to the\n * code itself if the runtime can't resolve the name. */\nexport function localizedCurrencyName(code: string, locale: string): string {\n try {\n return new Intl.DisplayNames([locale], { type: \"currency\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/** Number of fraction digits ISO 4217 specifies for a currency.\n * JPY = 0, USD = 2, KWD = 3. Used both for amount formatting and\n * for the HTML input step on debit/credit fields. */\nexport function fractionDigitsFor(currency: string): number {\n try {\n const opts = new Intl.NumberFormat(\"en\", { style: \"currency\", currency }).resolvedOptions();\n return opts.maximumFractionDigits ?? DEFAULT_FALLBACK_DIGITS;\n } catch {\n return DEFAULT_FALLBACK_DIGITS;\n }\n}\n\n/** \"1\" for JPY, \"0.01\" for USD, \"0.001\" for KWD. Used as the HTML\n * input step on debit/credit fields so a JPY book doesn't let the\n * user type cents that would just round-trip back through the\n * decimal validator. */\nexport function inputStepFor(currency: string): string {\n const digits = fractionDigitsFor(currency);\n if (digits === 0) return \"1\";\n return (1 / 10 ** digits).toFixed(digits);\n}\n\n/** Locale-aware currency formatter — returns \"¥1,130\" / \"$1,130.00\"\n * etc. Falls back to fixed-point formatting if the runtime can't\n * resolve the currency code; the fallback still respects the\n * currency's natural fraction-digit count so JPY shows whole\n * numbers even on the slow path. */\nexport function formatAmount(value: number, currency: string, locale?: string): string {\n try {\n return new Intl.NumberFormat(locale, { style: \"currency\", currency }).format(value);\n } catch {\n return value.toFixed(fractionDigitsFor(currency));\n }\n}\n\n/** Currency-agnostic amount formatter — \"1,130.00\" — for places that\n * don't carry the currency code on the data path (compact preview\n * envelopes etc.). Use `formatAmount(value, currency)` whenever the\n * currency IS available — the currency-aware path picks the right\n * fraction-digit count automatically (JPY = 0, USD = 2).\n *\n * `locale` mirrors `formatAmount`'s signature: pass an explicit BCP-47\n * locale (`\"en-US\"`, `\"ja-JP\"`, …) when the caller knows the desired\n * grouping / digit-shape; omit to fall back to the runtime default. */\nexport function formatAmountNumeric(value: number, decimals = 2, locale?: string): string {\n return value.toLocaleString(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });\n}\n","// Local-calendar date helpers for the accounting forms.\n//\n// Why not `new Date().toISOString().slice(0, 10)`? `toISOString` is\n// UTC. In a negative-offset zone (US Pacific, Eastern, …) the UTC\n// date crosses to \"tomorrow\" several hours before midnight local,\n// so a naively prefilled date input would post entries into the\n// wrong accounting day. Same mistake near month boundaries flips\n// the default Balance Sheet period to the next month.\n//\n// All four helpers below are pure local-calendar formatters built\n// from `getFullYear` / `getMonth` / `getDate`, which the JS engine\n// resolves in the user's local timezone.\n\nfunction pad2(num: number): string {\n return String(num).padStart(2, \"0\");\n}\n\n/** Today as `YYYY-MM-DD` in the user's local timezone. */\nexport function localDateString(now: Date = new Date()): string {\n return `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}`;\n}\n\n/** Current month as `YYYY-MM` in the user's local timezone. */\nexport function localMonthString(now: Date = new Date()): string {\n return `${now.getFullYear()}-${pad2(now.getMonth() + 1)}`;\n}\n\n/** First day of the current calendar year as `YYYY-MM-DD`. */\nexport function localStartOfYearString(now: Date = new Date()): string {\n return `${now.getFullYear()}-01-01`;\n}\n\n/** Previous calendar month as `YYYY-MM` in the user's local timezone. */\nexport function previousMonthString(now: Date = new Date()): string {\n const target = new Date(now.getFullYear(), now.getMonth() - 1, 1);\n return `${target.getFullYear()}-${pad2(target.getMonth() + 1)}`;\n}\n\n/** Last month of the previous calendar quarter as `YYYY-MM`. Calendar\n * quarters: Q1=Jan–Mar, Q2=Apr–Jun, Q3=Jul–Sep, Q4=Oct–Dec. When the\n * current month is in Q1, this rolls back to December of last year. */\nexport function lastMonthOfPreviousQuarterString(now: Date = new Date()): string {\n const firstMonthOfCurrentQuarter = Math.floor(now.getMonth() / 3) * 3;\n const target = new Date(now.getFullYear(), firstMonthOfCurrentQuarter - 1, 1);\n return `${target.getFullYear()}-${pad2(target.getMonth() + 1)}`;\n}\n\n/** December of the previous calendar year as `YYYY-MM`. */\nexport function decemberOfPreviousYearString(now: Date = new Date()): string {\n return `${now.getFullYear() - 1}-12`;\n}\n","// Single source of truth for the `getTimeSeries` action's enum\n// surfaces — kept outside the server module so the frontend tool\n// definition (`definition.ts`) and the server validator\n// (`server/accounting/timeSeries.ts`) can both import without\n// crossing the src ↔ server boundary in the wrong direction.\n//\n// Adding a new metric / granularity: extend the array here, then\n// extend the corresponding switch / aggregation in\n// `server/accounting/timeSeries.ts`. The LLM tool schema picks up\n// the new value automatically via `definition.ts`'s `enum` field.\n\nexport const TIME_SERIES_METRICS = [\"revenue\", \"expense\", \"netIncome\", \"accountBalance\"] as const;\nexport type TimeSeriesMetric = (typeof TIME_SERIES_METRICS)[number];\n\nexport const TIME_SERIES_GRANULARITIES = [\"month\", \"quarter\", \"year\"] as const;\nexport type TimeSeriesGranularity = (typeof TIME_SERIES_GRANULARITIES)[number];\n"],"mappings":";AAeA,IAAa,qBAAqB;CAChC,UAAU;CACV,UAAU;CACV,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,aAAa;CACb,eAAe;CACf,YAAY;CACZ,WAAW;CACX,mBAAmB;CACnB,oBAAoB;CACpB,oBAAoB;CACpB,WAAW;CACX,eAAe;CACf,kBAAkB;AACpB;;;ACrBA,IAAa,iBAAiB,EAC5B,UAAU;CACR,MAAM;CACN,QAAQ;AACV,EACF;;;ACFA,IAAa,gBAAgB;CAAC;CAAS;CAAa;CAAU;CAAU;AAAS;;;;AAMjF,IAAa,8BA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