Skip to content

docs(wasm): align beancount_wasm.d.ts with the actual wire shape - #1210

Merged
robcohen merged 2 commits into
mainfrom
docs/wasm-dts-audit
May 27, 2026
Merged

robcohen merged 2 commits into
mainfrom
docs/wasm-dts-audit

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Audit pass over crates/rustledger-wasm/beancount_wasm.d.ts surfaced drift between the hand-maintained TypeScript declarations and the actual Rust DirectiveJson / PostingJson shapes:

  1. Posting was missing price?: Amount — the @/@@ price annotation is emitted by the WASM binding but JS consumers could only access it via the base Directive's [key: string]: unknown index signature.
  2. Posting.flag was in the wrong position — declared between cost and meta, but the Rust struct (and the JSON output) puts it after price. Cosmetic.
  3. 7 of 12 directive variants had no narrowed interface: commodity, pad, event, note, document, query, custom. The DirectiveType union listed them but consumers had no IntelliSense for their fields. Added CommodityDirective, PadDirective, EventDirective, NoteDirective, DocumentDirective, QueryDirective, CustomDirective mirroring the corresponding DirectiveJson variants.

No runtime / wire-shape change — this is type-definitions only.

Why hand-maintained?

The root cause of this whole class of drift is that the .d.ts is hand-written. The proper long-term fix is #1200 item 2 (ts-rs generation from the Rust DTOs), which will make this kind of audit unnecessary. This PR is the tactical close on the current gaps.

Test plan

  • No Rust tests touch the file; no Cargo target needed.
  • No formatter / linter rules apply to the .d.ts (verified treefmt.toml).
  • Eyeball: each new interface mirrors the matching DirectiveJson variant in crates/rustledger-wasm/src/types.rs.

Related: #1200, #1209.

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 27, 2026 20:25
@robcohen
robcohen requested a review from a team as a code owner May 27, 2026 20:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review any files in this pull request.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov

codecov Bot commented May 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

robcohen and others added 2 commits May 27, 2026 22:36
Hand-maintained drift between the .d.ts and the Rust DTOs surfaced
while reviewing #1209. Audit findings:

1. **`Posting` was missing `price?: Amount`** -- the `@`/`@@` price
   annotation is emitted by the Rust side but JS consumers could
   only see it via the `unknown` index signature on `Directive`.

2. **`Posting.flag` was declared in the wrong position** -- the .d.ts
   listed `flag?` between `cost` and `meta`, while
   `rustledger_wasm::types::PostingJson` (and the JSON output)
   puts it after `price`. Cosmetic only; reorder to match.

3. **7 of 12 directive variants had no narrowed interface**:
   commodity, pad, event, note, document, query, custom. The
   `DirectiveType` union listed them but consumers had to inspect
   the raw base `Directive` with its `[key: string]: unknown`
   index signature to read their fields. Add `CommodityDirective`,
   `PadDirective`, `EventDirective`, `NoteDirective`,
   `DocumentDirective`, `QueryDirective`, `CustomDirective`.

Each new interface mirrors the corresponding variant on
`DirectiveJson` (custom_type, source_account, event_type, etc.).

Long term, hand-maintenance of the .d.ts is the root cause -- issue
#1200 item 2 (ts-rs generation from the Rust DTOs) will eliminate
this whole class of drift. This PR is a tactical fix to close the
current gaps; doesn't change the runtime wire shape.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
PR #1209 surfaced via Copilot that the WASM crate ships three
hand-maintained TypeScript surfaces, not one. Extend the audit (begun
in the initial commit on beancount_wasm.d.ts) to the other two:

**`src/lib.rs` typescript_custom_section** (wasm-bindgen embeds this
in the generated .d.ts that ships with the npm package):

- Declare the `MetaValueJson` type so directive/posting `meta?`
  fields are properly typed instead of relying on `unknown`.
- Add `meta?: Record<string, MetaValueJson>` to `BaseDirective`
  (inherited by Transaction/Balance/Open/Close).
- Add `meta?` to each inline directive shape in the `Directive`
  union (commodity, pad, event, note, document, price, query,
  custom), spelled out since these don't extend `BaseDirective`.
- Add `values?: MetaValueJson[]` to the `custom` inline shape (the
  positional arguments after the type keyword -- wire shape since
  #1199, but the TS surface had been silently dropping them from
  the type system).
- Add `meta?` to the `Posting` interface (posting-level metadata
  from #1168; wire-shape `meta?` was present but the type elided it).

**`beancount.d.ts`**:

- Add `price?: Amount` to `Posting` -- the `@`/`@@` annotation is
  emitted on the wire (and has been for ages) but the type didn't
  expose it.

Note: `Posting.flag?` is added to both surfaces by the companion
commit on #1209; this PR's edits stay clear of that line to avoid a
merge conflict.

Long term, hand-maintaining three TS surfaces is the structural
problem -- issue #1200 item 2 (ts-rs generation) is the cure.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@robcohen
robcohen force-pushed the docs/wasm-dts-audit branch from f2f6648 to 1c6162b Compare May 27, 2026 20:37
@robcohen
robcohen enabled auto-merge (squash) May 27, 2026 20:37
@github-actions

github-actions Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 39.3ms ± 4.7ms 25.1 MB
beancount 762.1ms ± 7.6ms 50.7 MB
Comparison 19.4x faster 2.0x less

vs main branch (2026-05-27)

Metric main this PR Change
Time 36.1ms 39.3ms +8.9% 🟡
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@robcohen
robcohen merged commit 3a33f1b into main May 27, 2026
34 checks passed
@robcohen
robcohen deleted the docs/wasm-dts-audit branch May 27, 2026 20:41
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 791
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen added a commit that referenced this pull request May 28, 2026
…WASI (closes #1221)

BREAKING CHANGE: the WASM binding's wire shape for `Transaction.payee`
and `Transaction.narration` now matches FFI-WASI. Pre-fix WASM emitted
`"payee": null` when None and `"narration": ""` when empty; post-fix
both fields are absent on the wire via `skip_serializing_if`. JS
consumers using `"payee" in t` (now `false` instead of `true`) or
`t.narration === ""` (now `undefined` instead of `""`) must update.
See `crates/rustledger-wasm/CHANGELOG.md` for details.

Surfaced by the ts-rs spike in #1220. FFI-WASI already used
`skip_serializing_if = "Option::is_none"` on both fields, but the
WASM binding diverged:

- `payee`: WASM emitted `"payee": null` when None; FFI-WASI omitted.
- `narration`: WASM wrapped `txn.narration` unconditionally in
  `Some(...)`, so an empty narration always emitted as `""` on the
  wire; FFI-WASI's converter normalized empty-string to None and
  thus elided the field via `skip_serializing_if`.

This divergence was masked in the wire-format equivalence harness by
the `strip_empty_meta_and_directive_nulls` normalization helper --
the harness was documented as a known divergence (item 3 in its
module docstring) with the recommended convergence being exactly
what this PR does.

## Changes

- `src/types.rs`: add `#[serde(skip_serializing_if = "Option::is_none")]`
  to both `Transaction.payee` and `Transaction.narration`.
- `src/convert.rs`: change `narration: Some(txn.narration.to_string())`
  to elide on empty string -- matches FFI-WASI's converter pattern at
  `crates/rustledger-ffi-wasi/src/convert.rs:133-137`.
- Three TS surfaces aligned:
  - `beancount.d.ts`: `payee: string | null` → `payee?: string`;
    `narration: string` → `narration?: string`.
  - `beancount_wasm.d.ts`: `narration: string` → `narration?: string`
    (payee was already correct).
  - `typescript_custom_section` in `src/lib.rs`: already had
    `payee?: string` and `narration?: string`; no change needed.
- `CHANGELOG.md`: BREAKING CHANGES entry under [Unreleased].
- Wire-format harness docstring updated -- divergence item 3 marked
  as ~~converged~~ with a pointer to this fix.

## Tests

Two new regressions in `src/convert.rs`:

- `transaction_omits_payee_and_empty_narration_1221` -- no-payee +
  empty narration transaction must have neither field on the wire.
- `transaction_emits_payee_and_nonempty_narration_1221` -- present
  payee + non-empty narration must both appear on the wire.
  Counterpoint so a future regression that elides unconditionally
  also fails CI.

The existing wire-format-tests harness already covered Transaction
equivalence (`metadata_equivalence_on_transaction_directive`) and
continues to pass; the null-stripping in
`strip_empty_meta_and_directive_nulls` is no longer load-bearing for
the payee/narration case but stays as a defensive guard against
future regression.

## Notes

The `.d.ts` audit that fixed Posting.price and 7 missing variants
(#1210) didn't catch this because it looked for missing/extra fields,
not type-mismatches on existing fields. The ts-rs spike (#1220)
surfaced it as a side-effect of comparing generated TS against the
hand-written shape -- evidence for ADR-0004's CI gate proposal.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
robcohen added a commit that referenced this pull request May 28, 2026
…ASI (closes #1221) (#1222)

* fix(wasm)!: converge Transaction.payee/narration wire shape with FFI-WASI (closes #1221)

BREAKING CHANGE: the WASM binding's wire shape for `Transaction.payee`
and `Transaction.narration` now matches FFI-WASI. Pre-fix WASM emitted
`"payee": null` when None and `"narration": ""` when empty; post-fix
both fields are absent on the wire via `skip_serializing_if`. JS
consumers using `"payee" in t` (now `false` instead of `true`) or
`t.narration === ""` (now `undefined` instead of `""`) must update.
See `crates/rustledger-wasm/CHANGELOG.md` for details.

Surfaced by the ts-rs spike in #1220. FFI-WASI already used
`skip_serializing_if = "Option::is_none"` on both fields, but the
WASM binding diverged:

- `payee`: WASM emitted `"payee": null` when None; FFI-WASI omitted.
- `narration`: WASM wrapped `txn.narration` unconditionally in
  `Some(...)`, so an empty narration always emitted as `""` on the
  wire; FFI-WASI's converter normalized empty-string to None and
  thus elided the field via `skip_serializing_if`.

This divergence was masked in the wire-format equivalence harness by
the `strip_empty_meta_and_directive_nulls` normalization helper --
the harness was documented as a known divergence (item 3 in its
module docstring) with the recommended convergence being exactly
what this PR does.

## Changes

- `src/types.rs`: add `#[serde(skip_serializing_if = "Option::is_none")]`
  to both `Transaction.payee` and `Transaction.narration`.
- `src/convert.rs`: change `narration: Some(txn.narration.to_string())`
  to elide on empty string -- matches FFI-WASI's converter pattern at
  `crates/rustledger-ffi-wasi/src/convert.rs:133-137`.
- Three TS surfaces aligned:
  - `beancount.d.ts`: `payee: string | null` → `payee?: string`;
    `narration: string` → `narration?: string`.
  - `beancount_wasm.d.ts`: `narration: string` → `narration?: string`
    (payee was already correct).
  - `typescript_custom_section` in `src/lib.rs`: already had
    `payee?: string` and `narration?: string`; no change needed.
- `CHANGELOG.md`: BREAKING CHANGES entry under [Unreleased].
- Wire-format harness docstring updated -- divergence item 3 marked
  as ~~converged~~ with a pointer to this fix.

## Tests

Two new regressions in `src/convert.rs`:

- `transaction_omits_payee_and_empty_narration_1221` -- no-payee +
  empty narration transaction must have neither field on the wire.
- `transaction_emits_payee_and_nonempty_narration_1221` -- present
  payee + non-empty narration must both appear on the wire.
  Counterpoint so a future regression that elides unconditionally
  also fails CI.

The existing wire-format-tests harness already covered Transaction
equivalence (`metadata_equivalence_on_transaction_directive`) and
continues to pass; the null-stripping in
`strip_empty_meta_and_directive_nulls` is no longer load-bearing for
the payee/narration case but stays as a defensive guard against
future regression.

## Notes

The `.d.ts` audit that fixed Posting.price and 7 missing variants
(#1210) didn't catch this because it looked for missing/extra fields,
not type-mismatches on existing fields. The ts-rs spike (#1220)
surfaced it as a side-effect of comparing generated TS against the
hand-written shape -- evidence for ADR-0004's CI gate proposal.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* ci: retrigger after sccache outage

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants