Skip to content

Embedding: the engine, the packages, saving and publishing

Audience: developers who use struktJS as a library, with no editor or with only parts of it · about 8 minutes · Prerequisites: Embedding the editor

Use the engine without the editor (headless core)

npm run build:embed also writes the engine on its own, with no editor, no DOM and no stylesheet, and the languages as separate files you load only when you want them. The files above are for browsers; the same files built for Node 22 are in node/ (node/struktjs-core.js, node/packs/…, node/struktjs-grammar-python.js, node/wasm/), and a plain Node program imports those:

File What it is
struktjs-core.js createCore({ packs, languages }): parse, check, type-check, run and generate. No languages inside.
packs/<plugin>.js One language pack per language plugin in the build (packs/lang-core.js, packs/lang-formula.js, packs/lang-diagram.js, …). Each is a small file; they share the engine with struktjs-core.js.
struktjs-grammar-python.js loadGrammarPython(): the Python/JavaScript/TypeScript grammars that Core and most languages are saved in. Its .wasm files are in wasm/.
import { createCore } from "./struktjs-core.js";
import { loadGrammarPython } from "./struktjs-grammar-python.js";
import core from "./packs/lang-core.js";
import formula from "./packs/lang-formula.js";

await loadGrammarPython();                              // before createCore; skip it for a language that needs no grammar
const c = await createCore({ packs: [core, formula] }); // every language a pack offers is registered, dependencies first
const model = c.parse('x = 1\nprint(x + 2)\n', { language: "core" });
model.check();      // { issues: [{ nodeId, severity, message }], errors, warnings }
model.types();      // the type pass only
await model.run();  // { output: [...lines], value }   the language's own evaluator; rejects if the program throws
model.generate();   // { text, errors, files }
model.print();      // canonical source text

Things to know:

  • A pack needs what its languages import. createCore({ packs: [diagram] }) fails with "diagram" imports "core", which no given pack or language provides: add packs/lang-core.js. Core also takes the standard-library languages (packs/lang-stdlib.js) when you provide them, as the IDE does; a build made for the embedded editor leaves that pack out.
  • The packs in a build are the languages that build was made with. npm run build:embed -- --profile <name> keeps only that profile's languages (see customization); the files in packs/ are exactly those.
  • You can also write your own language against the exports of struktjs-core.js (BaseConcept, ChildSlot, Prop, conceptsFromModule, …; the authoring surface is still provisional) and pass it as languages: [myLanguage].
  • Use node/ under Node, not the browser files (they cannot run under Node). The command-line tool is the other way to run the engine from Node, with the whole product.
  • run() is the language's evaluator, not a host runtime: Core does not execute real Python this way.
  • Size (uncompressed): the engine with the Formula pack is 1.2 MB, with Core, standard library, Formula, Diagram and decision tables 2.2 MB.
  • Every core owns its languages (core.registry): two cores on one page can hold a same-named, different language, and an editor mounted over a core that lacks a language says unknown language. A core can carry persistence grammars of its own (createCore({ grammars: [...] }), or a grammars list on a pack), visible to that core's languages only; a grammar registered by loading its module is the page's and shared by every core.
  • The editor and the core come from the same build and share one copy of the engine; load both from one folder.

Install it as packages (@struktjs/*)

npm run build:package packs the same build as separate npm packages under the @struktjs scope, one tarball each in dist/ (struktjs-<name>-<version>.tgz). They are distributed as those tarballs (private: the licence is UNLICENSED, nothing is published to the public npm registry). Install the ones you need together, in one command: their peer dependencies are pinned to exactly the same version, which no registry serves, and npm resolves them from the tarballs you list.

npm install ./struktjs-core-0.1.0.tgz ./struktjs-grammar-python-0.1.0.tgz ./struktjs-lang-core-0.1.0.tgz
Package What Needs
@struktjs/core the headless engine (createCore), browser and Node 22 or newer nothing
@struktjs/grammar-python the tree-sitter grammars and their wasm: await loadGrammarPython() (@struktjs/grammar-python/wasm/* are the four .wasm files) core
@struktjs/lang-core, lang-formula, lang-diagram, lang-core-decision-table, lang-pattern one language pack each (the packs of the build profile); the default export goes to createCore({ packs }) core and lang-core; formula also needs lang-diagram and lang-core-decision-table
@struktjs/widgets the Problems and Results views, and the stylesheet (@struktjs/widgets/style.css) core
@struktjs/editor mountEditor (browser only); it carries no languages of its own, so it needs a core core, widgets, grammar-python
@struktjs/diagram optional: the ELK layout engine (about 2 MB, loaded only when a layout is asked for). import "@struktjs/diagram" once, anywhere on the page, and the diagram editor's Layout Diagram (ELK) actions use it; without it they say which package to add, and the built-in Layout Diagram still works core
@struktjs/git structural version control over model source texts: diffModels (a tree diff), mergeModelTexts (a three-way merge that reports conflicts and takes your resolutions) and computeGitAnnotate (per-node blame, given functions that fetch the file versions). No git binary, no filesystem, no UI: it works in a page, a Node script or a merge driver. Load the grammar the files are written in first core
@struktjs/collab headless collaboration, no editor and no UI: the AST-to-Yjs mirror (createMirrorContext, reconcileLocalToYjs, hydrateFromYjs, applyYjsToLocal) and the relay session (hostSession, joinSession, resumeSession). A bot, a server-side check or a test can be a peer in Node 22 or newer or a page. It exports Y, the yjs it was built with: create your documents with that one, never a second copy of yjs. Secure by default: a plain-http relay on a local network and the pure-JS crypto fallback are refused until you install a settings reader with setCollabSettingsReader. The presence, cursor and join-dialog manager is part of the IDE, not this package core
@struktjs/python-runtime real Python execution: createPythonRuntime() returns a runtime you give to the core, createCore({ packs, runtime }), and model.run() then runs the languages that run on Python (Core) on CPython instead of the language's own evaluator; every other language, and a core with no runtime, is unchanged. In a page it runs Pyodide in a worker from the package's own pyodide/ folder (about 13 MB, same origin, no download prompt; name another folder or a CDN in pyodideUrl); in Node it uses the machine's python3 when there is one, else Pyodide (python: "host" \| "pyodide" \| "auto"). It depends on the pyodide package. You own the runtime: call dispose() when done core
@struktjs/lionweb the LionWeb repository helper core
@struktjs/stubs-python opt-in, only in a build made with --with-stubs core, grammar-python

npm install of one package pulls in its peers when you list their tarballs too, and a tree never holds two copies of @struktjs/core (they import each other's files). Take all the tarballs from one build: the version number alone does not tell two builds apart, and a mix fails when the page or program loads, not when npm installs. Importing a built entry file by its path is refused.

import { createCore } from "@struktjs/core";
import { loadGrammarPython } from "@struktjs/grammar-python";
import core from "@struktjs/lang-core";

await loadGrammarPython();
const c = await createCore({ packs: [core] });
const model = c.parse("x = 1 + 2\nprint(x)\n", { language: "core" });
console.log(model.check().errors, (await model.run()).output);

A page with no bundler serves the installed packages as they are, and the packages import each other by name, so it needs an import map from each package name to its folder ({ "imports": { "@struktjs/core": "/pkg/core/struktjs-core.js", "@struktjs/core/": "/pkg/core/", … } }; each package's exports["."].default is its entry file). A bundler needs nothing.

In an application built with a bundler (Vite, webpack, …) the library cannot know where the .wasm files ended up, so name the folder yourself: copy node_modules/@struktjs/grammar-python/wasm to a folder your server publishes (for Vite: public/strukts-wasm) and pass loadGrammarPython({ wasmBase: "/strukts-wasm/" }) and mountEditor(el, { wasmBase: "/strukts-wasm/" }). The packaged editor has no languages of its own: mountEditor(el, { core }) edits with the languages of a core you made from packs, and a mount without a core is an error that says so. The Vite development server is not covered (its dependency pre-bundling moves the library's files, so use wasmBase and, if needed, optimizeDeps.exclude: ["@struktjs/core", "@struktjs/editor", "@struktjs/grammar-python"]). The Python standard-library type stubs (about 5,000 files) are not in the default package: packages built with node scripts/build-package.mjs --with-stubs add @struktjs/stubs-python (about 4 MB packed); call loadStubsPython() before mountEditor and the editor offers standard-library modules (import os). The headless core does not load them.

Problems and results without an editor

@struktjs/widgets (struktjs-widgets.js in a build, about 3 KB, plus the shared stylesheet) holds two views that need no editor and no engine, for a page that checks and runs models headlessly with the core and only wants to show the outcome:

import { createCore } from "@struktjs/core";
import { mountProblems, mountResults } from "@struktjs/widgets";
import "@struktjs/widgets/style.css";           // their styles are part of the embed stylesheet, which the widgets package carries

const model = core.parse(text, { language: "core" });
const problems = mountProblems(el, { issues: model.check().issues, onSelect: (issue) => highlight(issue.nodeId) });
const results = mountResults(el2, { result: { lines: [{ kind: "output", text: "3" }], ok: true, durationMs: 1 } });
problems.update(model.check().issues);          // after the next check

mountProblems takes any list of { severity, message, nodeId? }: a core model's check().issues, or the editor's onIssues items. mountResults draws a run's lines (the editor's run() result fits as it is), marks a failure and shows the time. The Inspector needs the editor's selection, so it stays ed.mountInspector(element).

Remember the visitor's edits

The editor itself writes nothing to your page's storage; keeping a visitor's work across a reload is up to your page, and it takes a few lines with onChange and setSource:

const KEY = "my-page.source.v1";
const SEED = 'x = 1\n';
const read = () => { try { return localStorage.getItem(KEY); } catch { return null; } };
const write = (s) => { try { s.trim() === SEED.trim() ? localStorage.removeItem(KEY) : localStorage.setItem(KEY, s); } catch {} };

const remembered = read();
const ed = await mountEditor(el, { source: remembered ?? SEED, onChange: write });
// a stored text the parser had to repair does not read back as it was saved: start over from the seed
if (remembered !== null && ed.getSource().trim() !== remembered.trim()) ed.setSource(SEED);

Keep the storage calls in try/catch (a frame without storage access, or a browser that blocks site data, throws; the editor still starts, it just forgets), store nothing while the text equals the seed, version the key, and compare ignoring blank lines and a trailing newline (the editor prints without them). embed-demo.html (npm run dev) is a working copy that keeps the model as a LionWeb chunk through getChunk() instead of text.

Keep the model in your own LionWeb repository

If you run a LionWeb repository, a second small file, struktjs-embed-lionweb.js, lets a page push the editor's model to it and pull it back. It is not loaded by the editor and the public showcase does not ship it.

import { mountEditor } from "./struktjs-embed.js";
import { connectRepository } from "./struktjs-embed-lionweb.js";

let repo;
const ed = await mountEditor(el, { source, onChange: () => repo?.changed() });
repo = connectRepository(ed, { url: "https://lionweb.example.com", repository: "default", token, onStatus: (s) => show(s.state) });
await repo.pull(partitionId); // load a partition, or: await repo.push() to create one from this model
  • changed() (call it from onChange) pushes once, a second after the last edit. A failure is reported through onStatus and status; the edit is sent with the next push.
  • pull() without an id takes the partition this page is bound to, else the only one the repository has. push() creates the partition the first time and then updates it in place: every node keeps its id, so other tools reading the repository see edits, not replacements.
  • It is last writer wins: there is no live merging, so a page that has not pulled recently overwrites a newer model with its next push.
  • The token is kept in memory only. A token in a static page is visible to every visitor: use a read-only repository, or a proxy that adds the token. The repository has to allow your page's address (CORS).

Try it with the reference server: npm run lionweb:demo -- up (needs Docker).

Publish the showcase on your site

npm run build:showcase writes dist/showcase/: about 9 MB in some 30 static files. Upload the folder as it is, to the site root or any sub-folder (every link is relative); there is no back end and nothing leaves the visitor's browser (edits and theme stay in local storage, per tab). To update, rebuild and replace the whole folder (chunk names change with their content).

What the web server needs

  • .wasm as application/wasm. The parsers are WebAssembly; most servers know the type, some CMS hosts do not.
  • Compression (gzip or brotli). A first visit loads about 4.3 MB of script and parsers uncompressed, about 1.0 MB compressed; the diagram tab adds about 0.7 MB when it is first opened.
  • Caching. Files in embed/chunks/ have content-hashed names: Cache-Control: public, max-age=31536000, immutable. Everything else keeps its name between builds: let it revalidate.
  • Content-Security-Policy (if you set one). This is enough, tested from a sub-path: default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:. 'unsafe-eval' is not needed (the editor tries it once, is refused and carries on, leaving one blocked attempt in the console). style-src 'unsafe-inline' is needed for the diagram's style attributes, each language's own <style> element and the sandboxed equipment report.

The robot-maze simulation runs a script in a frame sandboxed with allow-scripts only (never allow-same-origin: it cannot reach your page, storage or origin). Under the policy above its inline script is refused: the page shows "The simulation could not start" and everything else keeps working. To enable it add 'unsafe-inline' to script-src for that folder (which relaxes the page's own script policy), or leave the maze example out of your build.

In an <iframe>. Do not send X-Frame-Options: DENY for that folder; use Content-Security-Policy: frame-ancestors https://your-site.example. The page's height changes per tab and width, so it posts { type: "strukts-showcase-height", height } to the parent whenever it changes.

<iframe id="demo" src="/demo/" style="width:100%;border:0;height:1200px" title="Live model editor demo"></iframe>
<script>
  addEventListener("message", (e) => {
    if (e.origin === "https://demo.your-site.example" && e.data?.type === "strukts-showcase-height")
      document.getElementById("demo").style.height = e.data.height + "px";
  });
</script>

Browsers and devices. Chromium and WebKit (Safari's engine) are supported, at desktop and phone widths, in light and dark. On a touch screen the page shows a short note on how to confirm an edit.

Accessibility. The page is operable by keyboard (arrow keys move between tabs) and respects reduced motion. It has not been used with a screen reader.