Repository navigation
feat(wasm): expose directive metadata to JS consumers (closes #1168) - #1199
Merged
Merged
Conversation
The WASM bindings' `directive_to_json` dropped every directive's `meta` field and the `Custom` directive's `values` field. JS consumers had no way to read transaction-level metadata, posting notes, open-directive booking annotations, commodity precision markers, or `custom` directive arguments — even though the host parsed and tracked all of it. This PR mirrors the FFI-WASI bindings' metadata shape: - New `MetaValueJson` untagged enum (String | Bool | Amount | Null). Host's strong `MetaValue` newtypes — Account, Currency, Tag, Link, Date, Decimal — flatten to JSON strings to match the FFI-WASI output. JS consumers branch on `typeof v` or shape (`'number' in v` → Amount), no discriminator field. - `meta: HashMap<String, MetaValueJson>` field on every `DirectiveJson` variant and on `PostingJson`. Empty maps serialize as an absent field via `skip_serializing_if`, so existing consumers continue to see the pre-#1168 shape for directives without explicit metadata. - `values: Vec<MetaValueJson>` on the `Custom` variant, restoring positional arguments that were previously dropped. - Updated both `.d.ts` files with the new `MetaValueJson` type and `meta?` annotations across every directive interface. Tests cover: every metadata-bearing directive type (open, commodity, transaction, balance, posting-level), the empty-meta omission shape, custom-directive `values` round-trip, and an exhaustive `MetaValue` → `MetaValueJson` mapping spot-check that breaks compilation if a host variant is added without updating the wire path.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Contributor
There was a problem hiding this comment.
Pull request overview
This PR updates rustledger-wasm’s JSON DTO surface so JavaScript/TypeScript consumers can access directive-level and posting-level metadata (and Custom directive positional values), aligning the WASM wire format with the FFI-WASI binding behavior to close #1168.
Changes:
- Add a WASM wire type (
MetaValueJson) and includemetaon all directive variants and postings (omitted when empty). - Restore
Custom.valuespositional arguments in the JSON output. - Extend TypeScript declaration files and add regression tests validating metadata/value preservation and omission behavior.
Reviewed changes
Copilot reviewed 2 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
crates/rustledger-wasm/src/types.rs |
Introduces MetaValueJson and adds meta fields to directive variants and PostingJson. |
crates/rustledger-wasm/src/convert.rs |
Implements MetaValue/Metadata → wire JSON lowering and adds #1168 regression tests. |
crates/rustledger-wasm/beancount.d.ts |
Updates TS types to include MetaValueJson and meta/values fields (but has mismatches noted in comments). |
crates/rustledger-wasm/beancount_wasm.d.ts |
Updates the alternate TS declarations with MetaValueJson and meta on directives/postings. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
📊 Benchmark Results
vs main branch (2026-05-26)
What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Findings 1, 3, 5, 7, 9 from the deep PR review (others either fit issue #1200's wire-format-drift sweep or are not actually bugs): - Finding 1 (wasm-bindgen-test for JS path): new tests/wasm_meta.rs runs under `wasm-pack test --node` and asserts what JS actually receives — `meta` reflects as native JS string/boolean/object, absent when empty, Custom values array preserves order and per-arg type. The sibling tests/wasm.rs is configured `run_in_browser` only (Issue #261 disabled the browser test job, so those tests silently skip in CI today); the new file is node-targeting so the metadata wire shape — the whole feature value of #1168 — gets actual CI coverage. - Finding 3 (deny_unknown_fields on Amount variant): serde rejects the attribute on untagged-enum struct variants, so document the permissive-by-design deserialize behavior in the rustdoc instead. Output-side consumers are unaffected. - Finding 5 (Decimal scale preservation): add a test for `Decimal::new(10000, 2)` → `"100.00"`, complementing the existing `Decimal::from(100)` → `"100"` case. Pins that trailing zeros survive the wire and that the Display contract for scale is not silently changed. - Finding 7 (`directive_meta` helper was a 12-arm match): hoisted the match into a new `DirectiveJson::meta()` accessor. Future variants fail compilation here, not at every call site. The test helper is gone. - Finding 9 (Custom values Null position): new test for `[String, Null, Number]` round-trip — pins that a `MetaValue::None` in the middle of `Custom.values` keeps its index rather than the position silently collapsing.
Round-2 review findings 1, 3, plus polish on 2/5/7/9:
- Finding 1 (Open.booking Debug format): `format!("{b:?}")` produced
`"\"STRICT\""` on the JS side (Debug-quoted string). Switched to
`open.booking.clone()` — JS now sees the literal source token
`"STRICT"`, matching FFI-WASI. Pre-existing bug also tracked under
#1200's audit; bundling here as a glaring same-crate fix.
- Finding 3 (Amount + Null + Account JS-runtime coverage): four new
tests in `tests/wasm_meta.rs`:
* `amount_metadata_exposes_as_object_in_js_1168` — `cost-basis:
100.00 USD` reaches JS as `{number, currency}`, not as a string.
* `null_metadata_exposes_as_js_null_1168` — value-less meta key
`key:\n` (the parser's `MetaValue::None` production rule) reaches
JS as native `null`, not `undefined` or `"null"`.
* `account_metadata_flattens_to_string_in_js_1168` — pins the
documented Account-to-string flattening so a future tightening
that adds a typed Account variant to MetaValueJson doesn't
silently change JS consumer behavior.
* `open_booking_is_clean_string_in_js` — guards finding 1's fix.
- Finding 2 (meta() accessor): doc updated to note it's a Rust-only
API not exposed via `#[wasm_bindgen]` — JS reads `directive.meta`
off the serialized object directly.
- Finding 7 (tests/wasm.rs vs tests/wasm_meta.rs cross-reference):
added a configure-asymmetry note in tests/wasm.rs pointing at
wasm_meta.rs and explaining why new tests needing CI signal should
go there (Issue #261 disables the browser job).
- Finding 9 (FFI-WASI parity claim): tightened MetaValueJson
docstring — JSON output is byte-equivalent, but the Rust types
are independent (true source-of-truth unification is #1200's
item 2).
- Finding 1: pin the MetaValueJson deserialize rejection for raw
JSON numbers. The wire contract stringifies `MetaValue::Number`
to preserve Decimal precision; raw `42` must NOT match any of
the String/Bool/Amount/Null arms. Without the test, a future
"helpful" numeric arm would silently erode precision.
- Finding 2: one-line note on `MetaValueJson::Null` flagging the
serde unit-variant-in-untagged-enum pattern as intentional.
- Finding 3: extracted `find_directive_by_type` helper in
tests/wasm_meta.rs; replaced index-based directive lookups in the
multi-directive fixture test (and the Amount-metadata test) with
type-filtering. A future parser reordering no longer breaks the
test with confusing index-mismatch messages.
- Finding 7: `Custom.values` now uses
`skip_serializing_if = "Vec::is_empty"` matching the `meta` field
treatment. A Custom directive with no positional args and no
metadata serializes as `{type, date, custom_type}`, matching the
TS shape's `values?` / `meta?` optional declarations.
Two inline findings:
- src/convert.rs: the test-module-gating comment said `serde_json`
AND `rust_decimal_macros` were the reason for the host-only gate,
but `rust_decimal_macros` was dropped in an earlier review round
(the tests use `Decimal::new(value, scale)` directly now). The
Cargo.toml only lists `serde_json` as a host-only dev-dep. Drop
the stale reference.
- src/types.rs: the MetaValueJson docstring claimed the TS union
was `Record<string, string | number | boolean | null | Amount>`,
but the enum has no plain-number arm — `MetaValue::Number`
(Decimal) stringifies to preserve precision, and a raw JSON
number fails to deserialize (pinned by
`meta_value_json_rejects_raw_json_number`). Rewrite the
docstring to reflect the actual union shape
(`string | boolean | {number,currency} | null`), matching what
the `.d.ts` files already declare.
robcohen
added a commit
that referenced
this pull request
May 27, 2026
…g audits (#1200 item 3) Builds on the cross-binding equivalence harness landed earlier in this PR by adding coverage for every directive variant and posting-level audit candidates from issue #1200 item 3. New fixtures (13 passing, 3 #[ignore]-pinned audit findings): - close_directive_equivalence - balance_directive_with_tolerance_equivalence [ignored] - pad_directive_equivalence - commodity_directive_equivalence - price_directive_equivalence - event_directive_equivalence - note_directive_equivalence - document_directive_with_tags_and_links_equivalence - query_directive_equivalence - custom_directive_with_all_value_variants_equivalence [ignored] - open_with_booking_method_equivalence - posting_with_cost_spec_equivalence - posting_with_price_annotation_equivalence - posting_with_flag_equivalence [ignored] Three real WASM-side wire-format bugs surfaced by the audit (each documented inline; each deserves its own focused convergence PR): 1. WASM drops Posting.flag entirely from its DirectiveJson::Transaction posting shape. FFI-WASI emits it. Same failure mode as the pre-#1199 meta drop — silently absent from one binding. 2. WASM drops Balance.tolerance from its DirectiveJson::Balance variant. FFI-WASI emits it. 3. WASM emits Custom.values raw (bare string/number/object) — lossy: JS consumers can't distinguish a Date value from a String value. FFI-WASI uses a tagged-union shape {type, value} that preserves the type info. Each failing test is marked #[ignore] with a reason pointing at #1200. When the WASM-side fix lands, the #[ignore] comes off mechanically and the test starts pinning the convergence going forward. The other 13 fixtures pass — meaning every other directive shape agrees between bindings after the normalization step. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 <[email protected]>
This was referenced May 27, 2026
robcohen
added a commit
that referenced
this pull request
May 27, 2026
… 1) (#1204) * feat(test): cross-binding wire-format equivalence harness (#1200 item 1) Establishes the test scaffold issue #1200 asks for: a new rustledger-wire-format-tests workspace crate that depends on both rustledger-ffi-wasi and rustledger-wasm and asserts they emit structurally-equivalent JSON for the same Directive fixture. This catches the #1168 failure mode (one binding silently drops a field the other emits) at CI time instead of waiting for a user- filed issue. Each audit finding from issue #1200 item 3 lands as an additional fixture row going forward. What's in this PR: - rustledger-ffi-wasi gains a lib target. Modules `convert` and `jsonrpc` are pub for the test + binary; `commands`, `helpers`, and `types` are pub(crate). DTOs that participate in the conversion surface (DirectiveJson, Posting, Amount, etc.) are re-exported at the crate root. - rustledger-wasm: `convert` module promoted from private `mod` to `pub mod` for the test crate. JS consumers still use the `api`/`parsed_ledger` bindings. - crates/rustledger-wire-format-tests/: new test crate with two initial tests: 1. metadata_equivalence_across_all_meta_value_variants — exercises every MetaValue flavor (String, Account, Currency, Tag, Link, Date, Number, Bool, Amount, None). This is the direct #1168 regression: WASM dropped the whole meta field for the crate's lifetime before #1199. The exhaustive fixture means any future drop of a single variant fails CI. 2. open_directive_minimal_equivalence — smoke test on a minimal Open directive (no metadata, no optional fields). Three real divergences the harness caught on first run (documented in the test module's rustdoc, normalized in the assert helper — each deserves a follow-up convergence PR): 1. FFI-WASI's Meta bundles filename/lineno/hash with user metadata; WASM emits user metadata only. 2. FFI-WASI emits `"meta": {}` for empty metadata; WASM uses skip_serializing_if = "HashMap::is_empty". 3. WASM emits `"payee": null`; FFI-WASI uses skip_serializing_if = "Option::is_none". Following the priority adjustment in #1200 (comment) : item 1 (harness) lands first, item 3 (audit findings) lands as fixture rows in this same crate, item 2 (TS generation) gets its own design issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 <[email protected]> * chore: regenerate cargo-vet exemptions * test(wire-format): extend fixtures to all directive variants + posting audits (#1200 item 3) Builds on the cross-binding equivalence harness landed earlier in this PR by adding coverage for every directive variant and posting-level audit candidates from issue #1200 item 3. New fixtures (13 passing, 3 #[ignore]-pinned audit findings): - close_directive_equivalence - balance_directive_with_tolerance_equivalence [ignored] - pad_directive_equivalence - commodity_directive_equivalence - price_directive_equivalence - event_directive_equivalence - note_directive_equivalence - document_directive_with_tags_and_links_equivalence - query_directive_equivalence - custom_directive_with_all_value_variants_equivalence [ignored] - open_with_booking_method_equivalence - posting_with_cost_spec_equivalence - posting_with_price_annotation_equivalence - posting_with_flag_equivalence [ignored] Three real WASM-side wire-format bugs surfaced by the audit (each documented inline; each deserves its own focused convergence PR): 1. WASM drops Posting.flag entirely from its DirectiveJson::Transaction posting shape. FFI-WASI emits it. Same failure mode as the pre-#1199 meta drop — silently absent from one binding. 2. WASM drops Balance.tolerance from its DirectiveJson::Balance variant. FFI-WASI emits it. 3. WASM emits Custom.values raw (bare string/number/object) — lossy: JS consumers can't distinguish a Date value from a String value. FFI-WASI uses a tagged-union shape {type, value} that preserves the type info. Each failing test is marked #[ignore] with a reason pointing at #1200. When the WASM-side fix lands, the #[ignore] comes off mechanically and the test starts pinning the convergence going forward. The other 13 fixtures pass — meaning every other directive shape agrees between bindings after the normalization step. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(wire-format-tests): scope null-stripping to top level (Copilot review) Copilot caught a real bug: the previous `strip_empty_meta_and_nulls` recursed into every nested object and dropped null values everywhere — including inside the `meta` object on directives. That hid the `MetaValue::None` variant from the metadata-equivalence fixture: the test's intentional `none-key: null` entry was being stripped from both sides before comparison, so a future binding-side drop of the `None` variant would have looked like agreement. Fix: rename to `strip_top_level_empty_meta_and_nulls` and limit it to the directive's own keys (plus per-posting keys, since postings also carry optional fields like `flag` per audit finding #1205). Never recurse into `meta` — null inside `meta` is a legitimate value that pins `MetaValue::None`'s wire shape. Test result unchanged (13 passing, 3 #[ignore]) — both bindings happen to agree on the `MetaValue::None` → `null` representation, so the fix doesn't surface a new divergence, but it removes a mask that would have hidden one in the future. Addresses #1204 (comment) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 <[email protected]> * test(wire-format): self-review polish — field-presence, issue refs, scope cleanup Addresses the v2 self-review findings on PR #1204: 1. **`assert_field_present` helper added**. Walks JSON via dot-separated path (e.g. "postings.0.cost"), panics if the field is missing from either binding. Used by audit fixtures that care about the field being present, not just the two bindings agreeing — equivalence alone would pass a lockstep-wrong drop. The module docstring now explicitly distinguishes drift detection (equivalence) from correctness (presence). 2. **`#[ignore]` reasons reference the specific follow-up issues** (#1205, #1206, #1207 — and #1208 just filed for a 4th find). 3. **Cargo.toml cleanup**: drop redundant `path = "src/lib.rs"`; correct the misleading "bare lib required for integration tests" comment to describe the actual rationale (empty lib, tests live under `tests/`). 4. **dev-dependency cleanup**: drop unused `jiff`. Keep `rust_decimal` even though only `rust_decimal_macros::dec!` is used directly — the macro expands to `rust_decimal::Decimal::from_parts(...)` and needs the crate in scope as a direct dep, not transitive. 5. **Metadata fixture applied to non-Transaction directives**: added `metadata_equivalence_on_open_directive` and `metadata_equivalence_on_document_directive` so the exhaustive `MetaValue`-variant check runs against multiple directive variants — a binding that handles meta correctly on Transaction but drops it on Open/Document would now fail. 6. **Module docstring** acknowledges that equivalence catches drift but not lockstep-wrong shapes, and points readers at `assert_field_present` for fixtures that need to verify presence. 7. **Builder consistency**: `Posting::with_flag` already exists in core (my v2 review was wrong on this); the `posting_with_flag` fixture now uses it instead of `let mut`. New audit finding surfaced by the field-presence helper: - **Both bindings drop `Document.tags` and `Document.links`** from their JSON wire shape — lockstep-wrong, so the original equivalence check passed silently. Filed as #1208 with a fix plan for both bindings. Test is now `#[ignore]`d pending convergence. Test result: 14 passing, 4 `#[ignore]`-pinned audit findings (was 13/3 before). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.7 <[email protected]> * chore(loader): satisfy clippy::unnecessary_trailing_comma (rustc 1.95) Drive-by: rustc 1.95.0 surfaced a new clippy lint (`clippy::unnecessary_trailing_comma`) that flagged a trailing comma inside a `format!` macro call. Since workspace path-deps don't get `--cap-lints`, this blocks `cargo clippy -- -D warnings` on every crate in the workspace. Co-Authored-By: Claude Opus 4.7 <[email protected]> * test(wire-format): unify presence + equivalence helpers (v3 review) Addresses v3 self-review findings on PR #1204: 1. **Single `assert_wire_format(label, directive, &[required_fields])` helper** replaces the previous split between `assert_field_present` and `assert_wire_equivalent`. The two checks always ran together in practice (every audit fixture wanted both presence and equivalence), so the unified call site reads more clearly and is harder to misuse. 2. **Catches always-empty regressions, not just missing keys.** `is_trivially_default` rejects `null`, `[]`, and `{}` — so a future bug that emits `"tags": []` regardless of input still fails the audit, even though `tags` is technically "present". Previously this would have slipped past `assert_field_present`. 3. **`json_get_path` rustdoc documents the dot-separator constraint:** paths containing literal `.` characters (e.g. an account name in a JSON key) aren't expressible. None of the current fixtures hit this, but the docstring flags it so a future contributor doesn't waste time debugging a silent miss. 4. **Cargo.toml polish:** - `version = "0.0.0"` with a comment marking the unpublished intent explicitly (the previous `0.15.0` was just inherited from the workspace scaffold and would be confusing to a future reader). - Replace the em-dash in the description with `--` (avoids non-ASCII in package metadata). 5. **Minor:** `fixture_posting`'s `.unwrap()` → `.expect(...)` with a reason — consistent with the rest of the harness. Test result unchanged: 14 passing, 4 `#[ignore]`-pinned audit findings (#1205, #1206, #1207, #1208). Co-Authored-By: Claude Opus 4.7 <[email protected]> * test(wire-format): rename strip helper to match its actual scope `strip_top_level_empty_meta_and_nulls` does recurse — into `postings` — so the "top level" framing in the name reads as inaccurate even though the docstring captures it. Rename to `strip_empty_meta_and_directive_nulls` and reflow the docstring to make the "descends into postings, never into meta" rule the leading sentence. No behavior change. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(wire-format): drop empty [lib] table so cargo-vet workflow passes The `Update Exemptions` workflow checks out the base branch, then fetches only Cargo.toml files from the PR (`pull_request_target` security posture: trusted base + Cargo files only — `src/` is not pulled in). With `[lib]` declared, `cargo metadata` requires `src/lib.rs` to exist even when the table is empty, and errors with: can't find library `rustledger_wire_format_tests`, rename file to `src/lib.rs` or specify lib.path Without the empty `[lib]` table, cargo auto-detects: `src/lib.rs` present → lib target; absent → no lib target, metadata succeeds. The on-branch build behavior is unchanged because `src/lib.rs` is still present in the repo. Reproduced locally: removing `src/lib.rs` and running `cargo metadata` errors with the v2 Cargo.toml (which declared `[lib]`) and succeeds with this fix. Co-Authored-By: Claude Opus 4.7 <[email protected]> * ci(supply-chain): fetch new crates' src/lib.rs in Update Exemptions The Update Exemptions workflow checks out the base branch, then fetches only Cargo.toml files from the PR. When a PR adds a new workspace member, `cargo metadata` then fails -- the new Cargo.toml is present but there is no default target file (src/lib.rs or src/main.rs), and cargo refuses to load such a manifest. Extend the file-filter to also fetch */src/lib.rs and */src/main.rs when present in the PR. Just enough to give cargo a default target so `cargo metadata` can enumerate the dep graph. Security model unchanged: `cargo vet regenerate exemptions` invokes `cargo metadata`, which parses Cargo.toml and resolves the dep graph but does NOT compile or execute the fetched source -- so pulling a source file from an untrusted PR can't run code on the runner. Build scripts (build.rs) are not fetched (cargo metadata doesn't execute them either, but keeping the surface minimal). This PR introduces crates/rustledger-wire-format-tests/ and tripped this bug on its own Update Exemptions run. Note that the fix can't heal this PR's check -- pull_request_target loads the workflow file from the base branch -- but lands on merge so subsequent PRs adding workspace members are clean. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]> Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
robcohen
added a commit
that referenced
this pull request
May 27, 2026
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
added a commit
that referenced
this pull request
May 27, 2026
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
added a commit
that referenced
this pull request
May 27, 2026
* docs(wasm): align beancount_wasm.d.ts with the actual wire shape 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]> * docs(wasm): extend audit to typescript_custom_section + beancount.d.ts 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]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
directive_to_jsonincrates/rustledger-wasm/src/convert.rsdropped every directive'smetafield, plus theCustomdirective's positionalvalues. JS consumers had no way to read transaction-level metadata, posting notes, open-directive annotations, commodity precision markers, orcustomarguments — even though the host parsed and tracked all of it.Implementation
Mirrors the FFI-WASI bindings' metadata shape so portable consumers see the same wire format across both bindings:
MetaValueJsonuntagged enum (String | Bool | Amount | Null). Host's strongMetaValuenewtypes — Account/Currency/Tag/Link/Date/Decimal — flatten to JSON strings to match FFI-WASI output. JS consumers branch ontypeof vor shape ('number' in v→ Amount), no discriminator field.metafield on everyDirectiveJsonvariant and onPostingJson. Empty maps are skipped viaskip_serializing_if, so existing consumers see the pre-[Feature]: WASM: add meta to directives #1168 shape for directives without explicit metadata.valuesfield on theCustomvariant, restoring positional arguments that were previously dropped..d.tsfiles with the newMetaValueJsontype andmeta?annotations across every directive interface, plusvalues?on Custom.Test plan
directive_to_json_preserves_metadata_1168— every meta-bearing directive type (Open, Commodity, Transaction with posting-level meta, Balance with boolean meta) round-trips throughdirective_to_json.directive_to_json_omits_meta_when_empty_1168— pins theskip_serializing_ifbehavior so existing consumers don't see new fields.custom_directive_carries_values_1168—valuespopulated and typed viaMetaValueJson.meta_value_to_json_covers_all_variants— exhaustiveMetaValue→MetaValueJsonmapping. The match inmeta_value_to_jsonis exhaustive, so adding a host variant breaks compilation here too.cargo test -p rustledger-wasm --all-features— 76 tests pass.cargo build -p rustledger-wasm --target=wasm32-unknown-unknown --tests— wasm test target builds clean.cargo clippy --workspace --all-features --all-targets -- -D warningsclean.RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps --all-featuresclean.Closes #1168
🤖 Generated with Claude Code