Skip to content

The core from JavaScript

Gantry’s core is the Go package github.com/c65llc/gantry/core: lint, format, generate, the read model, queries and edits, over files held in memory. It never touches the operating system, so it compiles to WebAssembly as gantry.wasm. @c65llc/gantry-core, in web/core/, runs that module in a module Worker behind a typed, promise-based client. A host (a web app, an editor extension) gives it files and gets back the same findings, tally and outputs gantry lint --json, gantry fmt and gantry generate give for the same files.

The package is private to this repository and not published to npm.

import { createCore } from "@c65llc/gantry-core";
import wasmUrl from "@c65llc/gantry-core/gantry.wasm?url";
const core = createCore({ wasmUrl: new URL(wasmUrl, location.href) });
const result = await core.lint(files, { strict: true });
core.close();

createCore(opts) takes:

Option Value
wasmUrl Where gantry.wasm is served. Go’s wasm_exec.js is loaded from beside it, so serve the two together (web/core/dist/ holds both after make wasm).
workerUrl The worker script. Optional; the default is the package’s worker.js.
timeoutMs How long a worker with calls in flight may stay silent before it is taken for hung. Optional; the default, DEFAULT_TIMEOUT_MS, is ten minutes, and 0 turns the watchdog off. The wait starts only after the worker’s first reply, so loading the module never trips it.

The worker starts on the first call and loads the module once. Each call returns a Promise:

  • It resolves with the result.
  • It rejects with GantryError when core refuses the call, such as for an invalid path. The message is the bridge’s error, "<fn>: <message>", and the worker carries on.
  • It rejects with GantryCrashError when the worker dies, fails to load the module, the module exits, or the watchdog fires. Every call in flight is rejected, and the next call starts a fresh worker.

close() stops the worker and rejects what is in flight; a later call starts a new one. createClient(spawn) builds the same client over any transport, such as Node’s worker_threads, which the package’s tests and the VS Code extension use. The worker side of such a transport is serve(port, instantiate), exported as @c65llc/gantry-core/serve.

Every function takes the project as Files: an object from project-relative path to file contents (UTF-8 text).

  • A key is a slash path relative to the project root: gantry.yaml, docs/design/rulings/safe-area.md. A key that is absolute, has a . or .. element, a leading or trailing slash, a backslash, a colon anywhere (C:x, a/b:stream) or a NUL byte is refused: the call fails with file name must be a project-relative path written with /, naming the key. scope is the exception: it takes the whole folder listing, so it ignores such a key (a name like captures/2026-11-27T10:00:00.png is legal on POSIX). The key is never in read and causes no error. Every other function refuses it, since a host passes them only the scoped files.
  • Files must hold gantry.yaml, or the call fails with no gantry.yaml found.
  • A file outside the project’s scope (a blob no manifest frame names, node_modules/) is ignored. The result is the same as with only the scoped files.

Reading a project: list, scope, read, call

Section titled “Reading a project: list, scope, read, call”

A host does not read a whole folder. It reads only what the project uses:

  1. List the folder: every file path, each with "" as its contents, except gantry.yaml and, when present, starboard.yaml and airframe.yaml, which it reads: scope needs the content directory each names.
  2. Scope: call scope on that listing. Its content is the content directory and its read every file the project uses.
  3. Scope again for evidence: if <content>/evidence/manifest.yaml is in the listing, read its contents into the listing and call scope again. Only then does heads, the evidence blobs the manifest names, list them: a host learns <content> from the first call, so it cannot read the manifest before it.
  4. Read those files, and only those: each of read in full, and the first 1024 bytes of each of heads.
  5. Call lint, model or any other function with the files read.
const listing = Object.fromEntries(paths.map((p) => [p, ""]));
listing["gantry.yaml"] = await readText("gantry.yaml");
let scope = await core.scope(listing);
const manifest = `${scope.content}/evidence/manifest.yaml`;
if (manifest in listing) {
listing[manifest] = await readText(manifest);
scope = await core.scope(listing);
}
const files = Object.fromEntries([
...(await Promise.all(scope.read.map(async (p) => [p, await readText(p)]))),
...(await Promise.all(scope.heads.map(async (p) => [p, await readHead(p, 1024)]))),
]);
const result = await core.lint(files);

The package exports these steps as selectFiles(tree, scope), which the web app’s hosts and the VS Code extension both read through. tree lists the folder (as project-relative slash paths), reads a file and reads a file’s first bytes; selectFiles skips anything under .git or node_modules and returns the files, the content directory and the heads.

A blob may be passed truncated to its first 1024 bytes; core reads only LFS pointers from it. That is enough to tell a Git LFS pointer from the real file, which is all the evidence rules and a frame’s state need. A host that leaves a blob out gets that frame reported as missing. Without the manifest’s contents in the listing, heads is empty: skipping step 3 on a project with frames reports every frame evidence-blob-missing.

The history rules compare the project with an earlier version of it, as gantry lint --base <ref> does from git. Core has no git, so the host passes that version as files:

  • base: the project at the base ref. Without it the history rules do not run, exactly as without --base. Files with no gantry.yaml that loads are an empty base, reported as base-empty.
  • ancestor: the project at the merge-base of the base and HEAD. Without it the base is taken as the fork point: a defect retitled since the base is an edit, never a defect-id-collision.

Of each, only gantry.yaml, the lint baseline and the content directory are read.

Each function’s arguments are the named fields of one JSON object. Every result marshals with lowerCamelCase field names, and its lists and maps are never null: an empty one is [] or {}. web/core/src/types.ts declares every type below, field for field.

Which of a folder’s files the project uses.

  • Arguments: {"files": Files}, the listing (see above).
  • Result: {"content": string, "read": string[], "heads": string[]}. content is the content directory (docs/design when gantry.yaml does not parse). read is sorted: gantry.yaml, the lint baseline, .gitattributes, every file under the content directory but its evidence blobs, every file a test glob matches, starboard.yaml and its screens registry, and airframe.yaml with the <content>/**/*.tokens.json and <content>/components/*.yaml files under its content directory (design-system unless it names one), each when present. It never holds a blob. heads is the blob path of every manifest frame whose blob is in the listing, sorted, each once. A blob may be passed truncated to its first 1024 bytes; core reads only LFS pointers from it.

gantry lint, and with base, gantry lint --base.

  • Arguments: {"files": Files, "strict": boolean, "base"?: Files, "ancestor"?: Files}. The client sends base and ancestor only when given.

  • Result:

    {
    "diagnostics": [Diagnostic],
    "tally": [TallyRow],
    "errors": 0,
    "warnings": 0,
    "infos": 0,
    "passed": true
    }

    passed is the CLI’s exit status: no errors and, when strict, no warnings.

  • A Diagnostic is {"rule", "severity", "file", "path", "line"?, "message", "fix"?, "docs"}: severity is error, warn or info, line is 1-based and absent when unknown, and fix is {"description", "replace"?: {"file", "path", "value"}}. The diagnostics are sorted, and gantry lint --json’s errors, warnings and infos lists are these, by severity.

  • A TallyRow is {"rung", "rule", "examined", "findings", "baselined"?, "skipped"}.

  • A gantry.yaml that does not parse is a finding (yaml-syntax or config-invalid), not an error.

The files gantry fmt would rewrite, in canonical form: gantry.yaml and the record files. Files already canonical are left out.

  • Arguments: {"files": Files}.
  • Result: an object from path to new contents; {} when everything is formatted.

What gantry generate would change.

  • Arguments: {"files": Files}.
  • Result: {"write": {path: contents}, "remove": [path]}: the generated files that are missing or differ, and the orphans under the generated directory. A current project gives {"write": {}, "remove": []}.
  • A project with load errors is refused, as the CLI refuses it.

The read view of the project, as far as it loaded.

  • Arguments: {"files": Files}.

  • Result:

    {
    "config": ModelConfig,
    "rulings": [Ruling],
    "defects": [Defect],
    "passes": [Pass],
    "primers": [Primer],
    "frames": [Frame],
    "citedBy": {"ruling:safe-area": ["defect:D-0001", "primer:ios"]},
    "loadErrors": 0
    }

    citedBy is keyed by the rulings, defects and passes that are cited, as ruling:<id>, defect:<id> or pass:<id>. Each value lists the records citing it, as <kind>:<id>, where the kind may also be primer or frame. loadErrors counts the load findings of error severity, so a UI can say “fix lint first”. A record that does not parse is absent. Each frame has a state: pulled (the blob is the real file), pointer (a Git LFS pointer not yet pulled, which a UI draws as a “not pulled” tile, never a broken image) or missing (no file), read from the blob’s first 1024 bytes. config.classes lists the defect classes in gantry.yaml’s order, and config.classOwes maps each to what closing a defect of that class must carry, as defect-closed-owing checks it: {"anyOf": [], "allOf": [], "assertionKinds": []}, each list never null. config.testGlobs maps each platform, and core when the project has a core platform, to its test-file globs as gantry.yaml writes them (project-relative, doublestar syntax); a platform with no globs maps to [], never null.

gantry query --json.

  • Arguments: {"files": Files, "expr": string}. expr is a kind (rulings, defects, passes or frames) and any field=value terms.
  • Result: the records selected, as their front-matter objects, sorted by ID.

Applies ops in order, through the same scaffolding as gantry new, amend and close. Each op sees the results of the ones before it. If any op fails, the whole batch fails with op <i> (<op>): <message> and nothing comes back.

  • Arguments: {"files": Files, "ops": [EditOp]}. An EditOp is op plus that op’s fields, each a string or a list of strings in the CLI’s grammar:

    op Fields
    new-ruling id, noun
    new-defect title, class, severity, rulings, platforms, apps, frames
    new-pass slug, title, date
    amend ruling, summary, replaces, change, by, pass, date, assertions
    close defect, owes

    Core reads no clock, so the host always passes date, as YYYY-MM-DD: new-pass and amend fail with date is required without one and date must be YYYY-MM-DD for any other form. An op whose file would land outside the project (a content directory of ../out or /abs) fails with the invalid-path error, naming the file.

  • Result: {"files": {path: contents}, "created": [id], "diagnostics": [Diagnostic]}: the full new contents of every changed or new file, the IDs the ops created in op order, and the lint findings in the changed files. The host writes files.

Every lint rule, by rung then ID, as gantry rules --json lists them. The listing includes the two findings the CLI reports while reading --base, base-empty and base-unavailable, so every finding a run can print is listed.

  • Arguments: {}.
  • Result: [{"id", "rung", "kind", "default", "summary", "docs", "cli"?}]. cli is true on base-empty and base-unavailable, which no lint rule runs, and absent otherwise.

refs(text, defectPrefix, markdown) → Ref[]

Section titled “refs(text, defectPrefix, markdown) → Ref[]”

The references in any text, in the order they appear, found as lint finds them in a record: @ruling, @defect, @pass, @evidence, @screen, @component and @token references, and bare defect IDs. An editor uses it to find the references in a record or in a source file’s comments.

  • Arguments: {"text": string, "defectPrefix": string, "markdown": boolean}. defectPrefix is the project’s (config.defectPrefix in the model): a bare defect ID is that prefix, digits and an optional letter b to z. An empty prefix finds no bare IDs. markdown says the text is a record file: its code spans and fenced code blocks are skipped, as lint skips them. Pass false for a source file, whose backticks are not Markdown, so a reference in a comment counts wherever it sits.
  • Result: [{"kind", "id", "fragment", "offset", "length"}]. kind is the record kind (defect for a bare ID), fragment what follows a # or "". offset and length are UTF-16 code units, as a JavaScript string and an editor count them, so the reference is text.slice(offset, offset + length). Nothing found is [].

symbols(path, text, platform) → Symbol[]

Section titled “symbols(path, text, platform) → Symbol[]”

The tests a test file declares, each with its line, so an editor can place what a ruling’s assertion or a defect’s owe names.

  • Arguments: {"path": string, "text": string, "platform": string}. path is the file’s project-relative path: its extension picks the language (.swift, .kt, .ts, .tsx, .js, .cs or .rs), and text is its contents. platform is the platform whose test globs matched path; "", a file no platform’s globs claim, gives [].
  • Result: [{"name", "bare", "line"}] (TestSymbol in types.ts, as Symbol is JavaScript’s own), in the order the language’s patterns find them. name is the symbol fully scoped, as an assertion names it: TabsUITests.testSelected for a test in a Swift class, tabs › shows the selected tab for a test in a describe block. bare is the test’s own name without its scope (testSelected, shows the selected tab), exact where name cannot be split, such as a Kotlin name with a dot in backticks. line is 0-based. The declarations are the ones lint’s symbol index holds for the same file, found with the same patterns, so a name here resolves for an assertion on that platform. An unknown extension, a text over 2 MiB, or one that is not valid UTF-8 gives [], as lint skips such a file.

capture(files, inputs, options, head) → CaptureResult

Section titled “capture(files, inputs, options, head) → CaptureResult”

gantry evidence add as a pure call: each input is recorded as a frame. Its blob is stored once per hash under the content directory, and the evidence manifest is rewritten in its canonical form with the new frames added, its comments kept. For the same inputs and head the manifest text and the blob bytes are the CLI’s, and a Go test runs both and compares them. Everything is checked before anything is returned.

  • Arguments: {"files": Files, "inputs": [CaptureInput], "options": CaptureOptions, "head": Head}. A CaptureInput is {"name", "data"}: name is the file’s name (only its base name and extension are used, to label the frame and to guess a type its bytes do not give away) and data its bytes, base64 (standard alphabet). CaptureOptions are the CLI’s flags, all strings: platform and appearance (required), and pass, device, app, label and note ("" leaves each out). A label names one frame, so it takes one input; without it each frame is labelled <pass>-<platform>-<appearance>-<file stem>. head is {"commit", "dirty"}, what the host read from git; an empty commit says it has none, so the frames carry none and the result warns not a git work tree; frames carry no commit, as the CLI does outside a work tree.
  • Result: {"files", "blobs", "frames", "warnings"} (CaptureResult in types.ts). files maps the evidence manifest’s path to its full new text; blobs maps each new blob’s path to its bytes, base64 (a blob the project already stores is not sent again, so the same screenshot twice is one blob). frames are the new frames in input order, shaped as the model’s, each with state pulled. warnings are the CLI’s (a project whose .gitattributes does not store the blobs through Git LFS). The host writes files and blobs; blobs first, so a manifest never names a blob that was not written.
  • Errors: a refusal is the CLI’s finding text, every problem found joined with ; (*CaptureError in Go, whose Problems lists them): no inputs, a missing platform or appearance, a label given with several files, data that is not base64, an unknown platform, appearance, pass or app, a label that is not kebab-case, repeated or already a frame, or an evidence manifest that does not load. A gantry.yaml that does not load is gantry.yaml does not load; run gantry lint (ErrCaptureNotLoaded); a project without one is ErrNoProject.
  • The media type is sniffed from the first 512 bytes, as the CLI does, from a table of the types a capture is (images, PDF, video, archives, fonts) rather than by net/http, which would add about 2 MB to gantry.wasm; an HTML or XML document is therefore text/plain and audio application/octet-stream (its extension then decides). A file over 64 MiB, or an empty one, is refused.

gantry.wasm (cmd/gantry-wasm) sets globalThis.__gantry to an object holding one function per name: scope, lint, format, generate, model, query, edit, rules, refs, symbols and capture. Each takes one JSON string, the arguments object, and returns one JSON string, the envelope:

{"ok": true, "value": …}
{"ok": false, "error": "<fn>: <message>"}

Unknown argument fields and trailing data are refused, so a misspelt argument fails loudly. A panic inside core comes back as {"ok": false, "error": "<fn>: internal error: …"}, never a crash. The client encodes the arguments on the main thread and unwraps the envelope: ok: true resolves with value, ok: false rejects with GantryError.

Terminal window
make build wasm # bin/gantry, web/core/dist/gantry.wasm and wasm_exec.js
make web-test # lint, build and test web/ (needs Node 24 and corepack)

The tests run the real gantry.wasm in a worker thread and compare it with bin/gantry on the example projects. They also hold the size budget: gantry.wasm is at most 10 MB raw and 2 MB with brotli.