rete · Guides JavaScript — rete-graph

JavaScript API

rete-graph on npm is the JavaScript client for .rete files: the same WebAssembly engine behind the playground, packaged for browsers and Node with an idiomatic wrapper — parsed Term results, clean IRIs, the same API shape as the Python client.

npm install rete-graph
import { open, build } from "rete-graph";

const g = await open("https://data.graphplaza.com/boe/boe-2026-07-07.rete"); // Node / worker
for (const row of g.query(`
    SELECT ?s ?label WHERE {
        ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label
    } LIMIT 5`)) {
  console.log(row.s.value, "→", row.label.toJS());
}
console.log(g.stats()); // { fileLength, bytes, requests } — lazy, not a download

Or a single <script> tag — no bundler, no install

p5.js-style: one self-contained file (engine embedded), full and minified, served by any npm CDN:

<script src="https://cdn.jsdelivr.net/npm/rete-graph@0.5.1/dist/rete-graph.min.js"></script>
<script>
  (async () => {
    const bytes = new Uint8Array(await (await fetch("mydata.rete")).arrayBuffer());
    const g = await rete.open(bytes);
    console.log(g.query("SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 3"));
  })();
</script>

…/dist/rete-graph.js is the readable twin; pin the version in the URL.

Where remote opens work

Remote graphs are read with synchronous XHR range requests (that's what lets the engine stay simple and synchronous):

Environmentopen(url)open(bytes)
Node ≥ 18✅ built-in sync-fetch bridge✅
Browser web worker✅ native sync XHR✅
Browser main thread❌ (browsers forbid sync binary XHR)✅

On a main thread, either fetch the bytes yourself (small files) or run the graph in a worker — the pattern the playground uses. Hosts must send CORS headers and honor Range (Hosting your .rete).

In Node the bridge also serves the engine's batched reads in parallel: when a query needs a set of ranges at once — the dictionary terms a result decodes, the index tiles a join is about to probe — they are fetched concurrently (16 in flight) instead of one round trip each. A synchronous read is still a round trip, so this matters most over a slow link to a large file: on crossref.rete (60 GB) from a residential connection, listing the 4,758 works that cite one paper took 3.5–4.9 s instead of 23–35 s, and title, venue and year for 100 of them 19–25 s instead of 46–65 s (two runs, cold cache). Results are identical. To keep reads strictly sequential, set globalThis.reteReadMany = null before the first open().

Query results

query() returns {variable: Term} rows for SELECT, a boolean for ASK, and [s, p, o] Term triples for CONSTRUCT/DESCRIBE. A Term has .kind ("iri" | "literal" | "bnode" | "triple"), .value, .datatype, .lang, plus .toJS() (number/boolean/BigInt for the common XSD types) and .n3.

g.query(q, { reason: true });   // OWL 2 QL entailment by query rewriting
g.query(q, { unionDefault: true }); // a pattern outside GRAPH sees every graph, each triple once
g.queryRaw(q);                  // the engine's raw JSON envelope
g.prefixSearch("Berl");         // label autocomplete → [{label, subject}]
g.textSearch("volcano");        // full-text (files built with --text-index)
g.schema();                     // { classes: [[iri, n]], relations: [[s,p,o,n]] }
g.graphNames(); g.info(); g.quads;
g.contentHash();                // remote graphs: blake3-16 cache key
await build(ntText, "nt");      // RDF text → .rete bytes (Uint8Array); also "nq", "ttl", "trig"

Paging a big result: queryRows()

query() decodes every term of every row before it returns, and a dictionary id is a rank, so the terms of a big result are scattered: a page of 25 rows out of 650,000 still reads every chunk the other rows touch (181 MB of the nanopub dump's dictionary for one class). queryRows() runs the SELECT to ids and decodes only the window you ask for:

const rows = g.queryRows(`SELECT ?s ?p ?o WHERE { GRAPH ?g { ?s a <http://example.org/Big> . ?s ?p ?o } }`);
rows.length;             // the exact row count, no term decoded
rows.vars;               // ["s", "p", "o"]
rows.page(0, 25);        // the first page: { s: Term, p: Term, o: Term }[]
rows.page(25, 25);       // the next, one batch of dictionary reads
rows.all();              // every row, as query() would return them
rows.free();

An ORDER BY still decodes the keys it sorts on, for every row; the other columns wait for the page. DISTINCT and GROUP BY work on ids. SELECT only (ASK, CONSTRUCT and DESCRIBE throw); in the browser the same handle is RemoteGraph.query_rows / Graph.query_rows of the wasm engine, with .vars(), .len() and .page(offset, limit) (the page is the JSON envelope of query, plus offset and total).

Why did a FILTER return nothing? lastWarnings()

CONTAINS(?s, "x") on an IRI, STRSTARTS(?year, "15") on an xsd:integer, and CONTAINS(?label, "x"@fr) against an @en label are SPARQL type errors. The spec says a FILTER treats an error as false, so such a query returns no rows and no error. The rows are left exactly as they are, but the graph remembers why (the rule):

const rows = g.query(`SELECT ?s WHERE { ?s rdfs:label ?l FILTER(CONTAINS(?s, "geneva")) }`);
rows.length;                    // 0, as SPARQL requires
g.lastWarnings();
// [{ severity: "type-error", function: "CONTAINS", argument: 1, argKind: "iri",
//    count: 1, sample: "<http://ex.org/map/geneva-1572>",
//    hint: "wrap it in STR() to match the IRI's text", message: "CONTAINS received an IRI …" }]

lastWarnings() describes the most recent query() / queryRaw() on that graph, and is [] when there is nothing to report. It works for every result form, including ASK's boolean, and the row array is the same as before. The raw envelope carries the same list as warnings when it is non-empty. An empty result can also come with a case-sensitivity hint (severity: "hint").

A long query in chunks: partitionPlan()

Per-entity details for thousands of entities on a remote graph can run as many short queries, split by the values of one variable, each retried or resumed on its own (the rule):

const plan = g.partitionPlan(q, "?work");   // throws, saying why, if the split would change the answer
const keys = g.queryRaw(plan.keys_query).rows.map((r) => r[plan.var]);
let rows = [];
for (let i = 0; i < keys.length; i += 200) {
  const part = g.queryRaw(q, { partition: { var: plan.var, keys: keys.slice(i, i + 200) } });
  rows.push(...part.rows);                  // CONSTRUCT: part.triples
}
// dedupe if plan.dedupe, then apply plan.offset / plan.limit — the chunks drop them

Each chunk's rows are term tokens, as in queryRaw. The Claude Desktop extension's partition_by does this with checkpoints on disk.

Jelly

Jelly is a binary RDF format, so it goes in as bytes: build(await readFile("data.jelly"), "jelly"). build takes a Uint8Array or ArrayBuffer for any format (text formats are read as UTF-8).

JSON-LD and YAML-LD

build(text, "jsonld") and build(text, "yamlld") read documents whose contexts are inline. A document that names a remote @context fails with an error naming the IRI; the browser engine fetches nothing. Use the CLI's --context for that.

RDF 1.2 and quoted triples

The CLI's --quoted-triple-syntax vocabulary and defaults, in both directions. build(text, "ttl" | "trig", { quotedTripleSyntax }) reads Turtle/TriG << s p o >> as a quoted triple under "rdf-star" (the default, as before) or as RDF 1.2 under "rdf12" (<<( s p o )>> triple terms, << … >> reifiers, {| … |} annotations). nquads() / writeNQuads() / toNQuads() take { quotedTripleSyntax } too, defaulting to "rdf12": a quoted triple is written as the RDF 1.2 triple term <<( s p o )>>, which Oxigraph 0.5 and Jena 5 load, and a subject-position one (no RDF 1.2 spelling) makes the stream throw; "rdf-star" writes rete's stored <<s p o>>. card().signals.quoted_triples says whether a file holds any, measured from its header on read, so files built before the signal existed answer it too. See Interop.

Comunica (and the RDF/JS ecosystem)

From 0.2.0 the package ships ReteSource, an RDF/JS Source that plugs .rete files into Comunica, LDflex, GraphQL-LD, and the Solid ecosystem:

import { open, ReteSource } from "rete-graph";
const source = new ReteSource(await open(bytesOrUrl));
// → sources: [source] in any Comunica QueryEngine

Comunica also talks to rete with zero code through the gateway's SPARQL endpoints (full query pushdown — prefer it for heavy joins over big remote files). Both levels, the exact semantics, and the which-level-when table live on the dedicated page: Comunica — rete in the RDF/JS ecosystem.

Feature matrix

CapabilityJSNotes
SPARQL SELECT / ASK / CONSTRUCT / DESCRIBE✅query()
Lazy remote open (HTTP Range)✅Node + browser workers
OWL 2 QL reasoned queries✅query(q, {reason: true})
Union default graph✅query(q, {unionDefault: true})
Schema profile, prefix & text search✅clean IRIs everywhere
Build from RDF text✅build() — uncompressed, like the playground
Script-tag single-file build✅dist/rete-graph(.min).js, global rete
TypeScript types✅bundled index.d.ts
RDF/JS Source (Comunica, LDflex, GraphQL-LD)✅ 0.2.0ReteSource — see Comunica
SERVICE federation✅*via the engine; same worker/Node constraint
Dataset Card / embedded examples✅card() (with signals.quoted_triples), examples()
RDF 1.2 Turtle/TriG in, triple terms out✅quotedTripleSyntax on build() and the N-Quads writers
Custom headers / custom readers⏳planned
Builder (card, pyramid options)⏳use build() or the Python/CLI builders

For contributors — how the package builds its engine from the crates, the sync-XHR bridge, and the release procedure: Client development & releases.