Skip to content

Upload: in-browser BIDS validation with @bids/validator (CLI/CI version lockstep) #161

Closed

Description

@neuromechanist

Problem

The upload page's client-side check (src/lib/bids-precheck.ts) is a hand-rolled structural scan (subjects/sessions/modalities/dataset_description.json). Real BIDS validation only happens after upload, in the dataset repo's CI (centralized Deno run, dispatched from the per-repo bids-validation.yml shim). Users learn about spec violations only after moving potentially hundreds of GB.

Proposal

Run the real schema validator in the browser, before any bytes move - the same @bids/validator that nemar-cli pins (validator-version.json: 2.4.1) and the CI dispatch uses, so all three layers agree.

Upstream support is first-class: the package targets "Deno and Browsers", and the official web validator (bids-standard.github.io/bids-validator) runs it fully client-side. Integration surface is two functions from the web build:

import { fileListToTree, validate } from "@bids/validator/web";  // exact specifier TBD at impl time
const tree = await fileListToTree(files);         // File[] from the dropzone
const result = await validate(tree, { /* schema pin */ });  // -> issues[] + summary

Design

  • Version lockstep: pin the same version as nemar-cli's validator-version.json (2.4.1 today). Add the pin to this repo and a note in AGENTS.md; consider mirroring nemar-cli's weekly bump workflow later.
  • Lazy load: the validator + schema is heavy; dynamically import() it only when the user drops files, keeping /upload's initial payload unchanged.
  • Layered UX: keep the instant structural pre-check as-is (it renders in milliseconds); run full validation next with a progress state; render an issues panel (grouped by code, file paths, severity) once done.
  • Gating: schema errors block the upload button (same severity semantics the publication CI enforces - failing early is strictly better than failing at publication prescreen); warnings are advisory.
  • Privacy note in UI: validation is fully local; no file content leaves the browser.
  • Server stays authoritative: repo CI validation is unchanged; the browser pass is UX, not the trust boundary.

Non-goals

  • No validation in the Pages Worker (no Deno subprocess there; also unnecessary).
  • No replacement of the CI validation path.

References

  • nemar-cli: src/lib/bids-validator.ts (Deno subprocess wrapper), validator-version.json, backend/src/services/github/workflows.ts (CI shim + version pin threading).
  • Upstream web app: web/src/App.tsx in bids-standard/bids-validator (fileListToTree + validate from the web bundle).
  • Current pre-check: src/lib/bids-precheck.ts, src/pages/upload.astro, src/components/UploadDropzone.astro.

Activity

  1. neuromechanist commented on Jul 29, 2026

    @neuromechanist
    ContributorAuthor

    Spike result: does not work cleanly at the pinned version. No PR.

    Spent the session actually trying to get @bids/validator (JSR) into a browser bundle rather than guessing. Summary: the CLI/CI pin (2.4.1, matching nemar-cli's validator-version.json) has no supported browser entry point, and forcing one open reveals a bundle so CLI-shaped that "lazy load it" undersells the problem. Full evidence below, per spike question.

    1. Does it run in a browser at all?

    Not at the pinned version, no. @bids/[email protected]'s published exports map (confirmed via jsr.io/@bids/validator/2.4.1_meta.json and the npm-compat package.json after bun add @jsr/[email protected] with npm.jsr.io configured as the @jsr scope registry) only exposes:

    ".", "./main", "./output", "./files" (-> src/files/deno.js), "./options", "./issues"
    

    There is no ./files/browser or ./validate export. src/files/browser.ts (the browser File[]-based file tree builder) exists in the package source but is not part of the public exports map — deep-importing it (@jsr/bids__validator/src/files/browser.js) is flatly rejected by both Bun and Node's exports-map resolution ("Could not resolve").

    The only public export that re-exports both fileListToTree and validate together is ./main (src/main.ts). But its own docstring says: "Validation entrypoint intended for command line usage with Deno... Call validate directly for other environments" — and its module-level imports pull in ./files/deno.js (imports node:fs) and the CLI's colored-output stack (ansi-escapes → node:os, supports-hyperlinks → supports-color's browser shim, which is itself broken against how supports-hyperlinks calls it). Bundling ./main for a browser target with esbuild — even reusing upstream's exact esbuild-plugins-node-modules-polyfill config (Buffer/process/crypto polyfilled, matching their own build.ts) — fails outright on unresolvable node:fs / node:os and a broken supports-color export.

    Browser support genuinely exists — but only as of the 3.0.0 rewrite (released 2026-07-13, i.e. ~2 weeks old), which adds an explicit ./files/browser export (src/api/files/browser/mod.ts) alongside ./files/deno and ./files/git. nemar-cli is pinned to 2.4.1 and its bump-validator.yml only tracks 2.x (select(test("^2\\.[0-9]+\\.[0-9]+$"))), so it will never pick up 3.x automatically. Getting browser support and staying in lockstep with the CLI/CI pin are mutually exclusive today.

    Separately: the "official web validator" at bids-standard.github.io/bids-validator does not consume the published JSR/npm package at all. Its web/src/App.tsx imports from ../dist/validator/web.js — a build artifact produced by the repo's own build.ts (Deno + esbuild with jsr:@deno/esbuild-plugin + hand-picked node polyfills), run only inside bids-validator's own .github/workflows/web_build.yml (denoland/setup-deno + deno task build), and deployed straight to GitHub Pages. It is never published anywhere a downstream project could bun add it. There is no versioned, importable "browser build" of this package — "browser support" upstream means "clone our repo and run our Deno build," not "add our package."

    2. Bundle size

    Couldn't get a clean number because there's no clean build (see #1). To get any number, I forcibly stubbed the four blockers (node:fs, node:os, supports-color, supports-hyperlinks → empty modules) on top of ./main with upstream's own polyfill plugin config. That is not something I'd ship — it's diagnostic only.

    Result: 10.3 MB minified / ~1.6 MB gzip (measured with gzip -9). hed-validator alone is 9.0 MB raw (87.4% of the bundle — it bundles the full HED schema/vocabulary). The rest is isomorphic-git (146 KB), the BIDS JSON schema (521 KB + 26 KB citation schema), ajv, marked, pako and fflate both present (duplicate gzip implementations), @jsr/effigies__cliffy-command/cliffy-table (a full CLI arg-parser/table-renderer that's dead code in a browser), and @jsr/bradenmacdonald__s3-lite-client (S3 client, for validating datasets that live in S3 — irrelevant to a browser drop). None of this reflects tree-shaking discipline on upstream's part for browser consumption; it reflects what's left standing after stubbing the parts that don't resolve at all.

    For comparison: this site currently ships route bundles in the tens-to-low-hundreds of KB. A 1.6 MB gzip payload (before you even get to WASM for hash-wasm) on the upload route is not a "lazy import," it's a second app.

    3. How does it take input?

    This part is genuinely good news, for whenever a clean import path exists: fileListToTree(files: File[]) (in src/files/browser.ts, confirmed present even at 2.4.1) takes a plain File[], exactly the shape filesFromInput() and walkDataTransferItems() in src/lib/upload-client.ts already produce. BIDSFileBrowser wraps each File via webkitRelativePath. No adapter would be needed beyond mapping our DroppedFile[] to File[].

    4. Does it need to read file contents?

    Yes, but the read pattern for large binary files is bounded, not "slurp the whole file." BrowserFileOpener.readBytes(size, offset) (src/files/openers.ts) does file.slice(offset, size).arrayBuffer() — a native File.slice() byte-range read, which browsers implement without loading the full file into memory. NIfTI header parsing (schema/context.ts → loadNiftiHeader → files/nifti.ts) uses exactly this for .nii/.nii.gz. TSV/JSON sidecar files get a full .text() read, but those are metadata files (small) by construction, not the multi-GB modality data NEMAR actually stores (EEG/MEG/iEEG/EMG: .set/.fdt, .edf, .bdf, .vhdr/.eeg, etc.) — I did not find content-reading rules targeting those formats in the schema-application code I read, but I did not exhaustively audit every rule. This question is moot pending #1/#2 being resolved, but it's not a structural blocker on its own.

    5. Web Worker

    Not reached — never got a working validate() call (blocked at bundling, #1/#2). In principle nothing in the dependency graph looks Worker-hostile (hash-wasm is WASM and workers support WASM; ajv, isomorphic-git generally run in Workers), but I'm not going to claim Worker-compatibility as verified when the bundle itself isn't buildable in the first place.

    6. Version lockstep

    This is the sharpest problem, independent of bundling mechanics: the version that has a public browser export (3.x) is not the version nemar-cli pins or auto-bumps to (2.x only), and nemar-cli's .github/workflows/bump-validator.yml explicitly filters to ^2\.[0-9]+\.[0-9]+$. Widening that regex to include 3.x is a nemar-cli decision (out of this repo's scope) with its own migration cost — 3.0.0 is ~2 weeks old, went through 5 alpha tags over roughly May–July 2026, and its dependency set is materially different from 2.x. Until nemar-cli moves its pin to a 3.x release and that release's browser export is verified to bundle cleanly (not yet checked — this spike only exercised 2.4.1's internals in detail), there is no version where "runs in the browser" and "matches what CLI/CI will actually enforce" are simultaneously true. Shipping against 3.x in the website while nemar-cli stays on 2.x would recreate exactly the drift bug (issue #586 in nemar-cli) that motivated pinning in the first place — the browser could say "valid" against different schema/rule versions than CI enforces.

    7. Cloudflare Pages build

    Not the primary blocker, but confirms the second-order risk: getting the actual upstream browser artifact requires Deno in CI (denoland/setup-deno + deno task build, per bids-validator's web_build.yml) — our own deploy-test.yml only sets up Bun, and prod deploys through Cloudflare's GitHub App integration, whose build image is outside our control and near-certainly lacks Deno. Since there's no published package to bun add instead (see #1), this would mean either (a) adding a Deno toolchain to our build pipeline and vendoring/replicating a fork of bids-validator's build.ts, which is exactly the kind of fragile, high-maintenance path the spike brief told me not to force, or (b) reaching into unexported internals as a bundler input, which is what I actually tried and which breaks on unrelated CLI dependencies (#1/#2). Neither is "the build step needs Deno available" in a simple sense — it needs us to own a shadow build of someone else's private tooling.

    Decision

    Not implementing. bids-precheck.ts stays as the only client-side check for now; no code changes in this repo. Branch spike/issue-161-bids-validator has no commits (all experimentation happened in a scratch dir, not this repo) — nothing to open a PR against.

    Alternative approaches, roughly in order of how much I'd trust them

    1. Server-side pre-flight validation via a nemar-cli endpoint, using the real validator on a version nemar-cli already trusts. Doesn't satisfy "before any bytes move" literally, but could run immediately after the file manifest is known (before or interleaved with the S3 PUTs) rather than only after finalize, using the exact 2.x pin CI already enforces — zero version-skew risk, because it's the same code path CI uses today (nemar-cli/src/lib/bids-validator.ts, Deno subprocess). Needs new nemar-cli-side infra (an endpoint or queued job that can spawn Deno) — cross-repo, but low technical risk since it reuses code that already works and is already trusted.
    2. File an upstream issue against bids-standard/bids-validator asking for a genuinely tree-shakeable "core" export — no ansi-escapes/cliffy/s3-lite-client/isomorphic-git in the browser-reachable graph, and hed-validator loaded lazily/on-demand rather than unconditionally (it's 87% of the forced bundle and only matters for datasets that actually use HED). This is the "right" long-term fix and would benefit every downstream consumer, not just us, but it's not actionable on our timeline and depends on upstream prioritization. Worth doing regardless of what else we pick.
    3. Close the loop on the existing post-upload CI validation instead of duplicating it client-side. Keep bids-precheck.ts as-is, and invest instead in making the real validation result (already run in CI after finalize, per the epic's description) show up fast and prominently on the dataset's draft/status page — poll for it, surface errors/warnings with the same grouping the issue wanted, and make re-upload/fix-and-retry cheap. This accepts that true pre-upload validation isn't available today rather than shipping a 1.6+ MB gzip payload or an unsupported internal-API integration to approximate it.

    Happy to prototype option 1 if there's appetite — that's the one that doesn't ask this repo to own someone else's unpublished build pipeline.

  2. neuromechanist commented on Jul 29, 2026

    @neuromechanist
    ContributorAuthor

    Follow-up to the spike findings above, after verifying the registry data directly. The conclusion sharpens: the blocker is not that browser support is missing, it is that we are pinned below the major that has it.

    Two corrections/additions to the analysis:

    1. 3.x is stable, not a fresh alpha. 3.0.1 is a stable release on JSR. Its exports map is exactly the shape this feature needs:

    { ".": "./src/api/app.ts", "./validate": "./src/api/validate/mod.ts",
      "./files": "./src/api/files/mod.ts", "./filetree": "./src/api/filetree/mod.ts",
      "./files/deno": "...", "./files/browser": "./src/api/files/browser/mod.ts",
      "./files/git": "...", "./issues": "...", "./output": "...", "./cli": "...",
      "./main": "...", "./options": "..." }

    Deno / browser / git file access are separate entry points, and ./validate + ./filetree are exposed independently of the CLI. Compare 2.4.1, which offers only a Deno ./files and a ./main documented for command-line use:

    { ".": "./src/bids-validator.ts", "./main": "./src/main.ts", "./output": "...",
      "./files": "./src/files/deno.ts", "./options": "...", "./issues": "..." }

    So the 10.3 MB force-bundle measured above is not evidence that this package is unbundleable — it is evidence that 2.x is unbundleable. 3.x was restructured for precisely this.

    2. The lockstep problem has a specific, fixable cause. nemar-cli's .github/workflows/bump-validator.yml resolves versions with select(test("^2\\.[0-9]+\\.[0-9]+$")). That regex is hard-locked to the 2 major, so the weekly auto-bump will never surface 3.x. The pin is frozen at 2.4.1 until someone deliberately moves it — it is not that 3.x was evaluated and rejected.

    Revised recommendation

    Filed nemarOrg/nemar-cli#1036 to evaluate moving the pin to 3.x. That is the highest-value unblock: it fixes the version-skew problem at the root rather than routing around it, and once CI enforces 3.x the website can consume ./files/browser + ./validate directly, in lockstep by construction.

    The server-side pre-flight endpoint (option 1 above) remains the fallback if 3.x turns out not to be adoptable soon. It is a strictly larger backend ask, so it is worth waiting on #1036's answer before committing to it.

    This issue stays blocked on nemar-cli#1036. Keeping the hand-rolled src/lib/bids-precheck.ts structural scan as-is in the meantime; no code changed.

  3. neuromechanist commented on Oct 21, 2026

    @neuromechanist
    ContributorAuthor

    Implemented in #473, merged to staging as 9c73a77 (squash). Verified on test.nemar.org after the staging deploy: the validator worker is served at /vendor/bids-validator/3.0.2/bids-validator-worker.js with 200, application/javascript, the worker's own content-security-policy and no-referrer policy, and bytes that match SHA256SUMS. The plain URL kept an edge-cached 404 from before the deploy for up to four hours, tracked in the follow-up linked above. Known limits, stated in the PR: Safari was not run, there is no browser end-to-end test in CI (#435), the npm.jsr.io route is tracked in #474, and the public uploading page is tracked in nemarOrg/docs#81.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions