Embedding the projectional editor in a plain web page¶
npm run build:embed builds a small library (dist/embed/: struktjs-embed.js, struktjs-embed.css, chunks/, wasm/, demo.html) that mounts a struktJS editor into any element — with checks, type errors, completion, intentions and constraints — and none of the IDE (no Theia, no panes, no git, no project/model layer, no menus).
import { mountEditor } from "./struktjs-embed.js";
const ed = await mountEditor(el, {
source: 'x = 1\ny = "a" + 1\n', // Python surface (Core); `language: "formula" | "diagram" | …` for a built-in language
theme: "auto", // "light" | "dark" | "auto" (follows prefers-color-scheme)
rememberCompletions: false, // true = rank frequently picked completions across sessions via the page origin's localStorage
notations: ["math"], // notation names a node opens in when the editor mounts (and after setSource), if its concept offers one; a view, never written to the source
rootHeader: false, // leave out the file root's header line (`kernelf`, `formula`, `device name:`): the program starts on the first line; Core has no header and is unaffected
language: "core", imports: ["coreDecisionTable"], // languages composed into `language` (a model.json `imports` entry): Core with decision tables
modelName: "main", models: [{ name: "lib", source: "…" }], // sibling models the edited one can import from / refer to; ed.setModels([...]) later
onChange: (src) => {}, onIssues: (issues) => {}, // issues: {nodeId, severity, message, explain?: {reason, hint?}}[]
onSelect: (nodeId) => {}, // the selected node changed (null = nothing); a literal cell reports the node that holds it
onOpenInfoPanel: (nodeId) => {}, // "More info" in a node's tooltip (double-click); the button exists only with this or a mounted Inspector
});
ed.getSource(); ed.setSource(text); ed.getAst(); ed.dispose();
await ed.getChunk(); await ed.setChunk(chunk); // LionWeb chunk, lazy-loaded
ed.getIssues(); ed.focusNode(issue.nodeId); // build your own Problems list: onIssues/getIssues + jump to the node
ed.mountProblems(el, { onSelect }); // ...or use the ready-made list: severity dot + message, click jumps to the node
ed.workbench.types.describe(nodeId); // -> { text, named?, plain: "a number", type, of?, via?, within?, problems: [{severity, message, explain?}] } | null: a node in plain words (pair with onSelect)
await ed.mountInspector(el); // the Inspector for the selected node, following the editor's selection
await ed.generate(); // -> { text, errors } via the language's generator
await ed.run({ input: (prompt) => "…", timeoutMs: 5000, signal }); // -> { lines: [{kind:"output"|"info"|"warn"|"error"|"result"|"html", …}], ok, error?, result?, durationMs, cancelled? } (timeout/abort stop it at the evaluator's next step; lines hold what it printed)
How it works (src/embed/mount.tsx)¶
The recipe is the Model Console's embedded editor (routes/console-panel.tsx) with a private DocumentState per mount: a Solid store seeded with mirrorToPlain(ast); new Editor(container, {preserveIds: true, setAst: state.syncStoreFromEditor, getDocumentState, onGetCheckIssues}); <NodeRenderer> inside DocumentStateContext + LangContext; a debounced runChecks feeding state.setCheckResults. Two mounts on one page are independent (own document state, own language instance via a per-mount owner id).
preserveIds: trueis mandatory when the store is seeded before theEditorexists. Without it the constructor re-stamps ids, DOM ids stop matchingeditor.root, and literal commits silently miss (typing "works", the source never changes).- Literal cells buffer typing and commit on blur/Enter — read the source after the commit.
- Core has no undefined-name check;
"a" + 1is the easy type error to demonstrate.
run()/generate() load the generator on first call (a separate chunk); the evaluator is a small (14 KB) chunk that the Workbench API's synchronous createEvaluator() imports statically, so it is not lazy any more (tests/test-embed-build.spec.js guards its size instead). run() of mountEditor runs a language with supportsHostExecution (Core) on Pyodide: it generates Python, adds the language's prelude and runs it through a per-mount PyodideRuntime (src/embed/run-python.ts, a Web Worker; the runtime option names where Pyodide's files come from and whether they may be downloaded — nothing is fetched unless autoDownload/confirmDownload agrees, and dev serves the package same-origin at /__pyodide/). Every other language interprets the AST with Evaluator, the in-browser evaluator every language ships. A program throwing comes back as {ok: false, error}, never as a rejection. Cancellation: timeoutMs is the runtime's own clock (it starts when the program does, not when the worker starts loading) and an AbortSignal stops the run even while it waits on the host's input callback; the evaluator's runs use the EvalCancellation token (the same one the IDE's test runs use), so even while True: pass stops. The headless core entry (createCore, model.run()) is still the evaluator for every language, Core included.
Out of scope, deliberately: the debugger and Live Model Session collaboration. Don't add them to the embed. That includes breakpoints: mount.tsx passes no getBreakpoints/onToggleBreakpoint, which switches off the gutter dot, the context-menu entry and Alt+Shift+G, and breakpoints stored by the IDE for the same origin are ignored (tested).
Sibling models¶
models: [{name, source}] (+ modelName for the edited one, default "main", and ed.setModels(list) to change them later) gives the edited model the project context the IDE has: the editor, checker and evaluator read a live list of project-model objects ({name, filename, roots:[{filename, ast}], meta} — workbench/project.ts's ProjectModel; the edited model's root is a getter on the editor, a sibling's AST is parsed once from its source), through Editor#setProjectModels, DocumentState#setActiveModel and the evaluator's resolveModel. Siblings are in the edited model's language and persistence grammar; file names are <name>.model.<grammar extension>, so a model's identity is its name (modelQualifiedName). What this buys is whatever a language does with sibling models: a reference slot offers declarations from them (Entities' entityPropertyRef), KernelF's import "lib" evaluates the sibling's blocks in run(), byId link targets resolve across them. Core's own from util import double is checked but not evaluated across models by the evaluator — in the IDE Core runs through generated Python, and there is no host executor in the embed. Found while building this: the Entities plugin's referenceScopes read m.ast from each model although a ProjectModel has roots[].ast, so with ANY project open (the IDE included) the reference had no candidates; fixed, with a unit test using real project-model shapes.
Several editors, lifetime, shared state¶
Audit result (2026-10-18). Per mount: document state (AST store, check results, active language), the language instance (an owner id per mount for built-in languages), overlays, and now teardown. ed.dispose() calls Editor#dispose() (editor/public-api.ts), which removes the editor's document-level listeners (_listenDocument in dom-events.ts registers each with a removal callback — add new document listeners through it, never document.addEventListener directly), disconnects the gutter ResizeObserver, closes any open popup/menu/tooltip and removes its overlay elements; the embed then removes its wrapper and overlay root. Mount/dispose cycles leave no document listeners (tested in a real browser).
Still shared by design: the page's grammar registry (read-only after boot; a core can hold grammars of its own since P1 landing 2, see "The editor over a core"), the page's default language registry (what an embed WITHOUT a core boots its built-in languages into; a core owns its own since P1, see "The editor over a core"), the global preference/keybinding stores (the renderer reads preferences such as notation toggles; an embed never writes them), app-state signals (coverage/test marks, focus-dim — empty in an embed), and defaultDocumentState, which is only the default of the renderer contexts and is never used when the host supplies its own (the embed always does). Persistence: the editor's only own write to localStorage is completion-pick counts (struktjs.completion-usage.v1); the embed turns that off (persistCompletionUsage: false) unless rememberCompletions: true.
Cross-browser¶
npm run test:embed (playwright.embed.config.js) runs every tests/test-ui-embed*.spec.js on Chromium, Firefox and WebKit (npx playwright install firefox webkit once), plus tests/test-embed-build.spec.js (Chromium): it snapshots the working tree into a temp dir, runs the real pruned build:embed there (never stages in the shared checkout) and drives the built output from a static server on a styled host page — a full-language build would hide pruning bugs (other eagerly loaded plugins register the Python grammar by accident), and removing the grammar-pack import from embed/index.ts makes this spec fail. 36 tests incl. MathML (mfrac/msqrt sized), the lazy Sprotty chunk and four languages on one page. It found a real bug in the first run: Enter right after typing into a literal cell lost the typed value in Firefox and WebKit (the structural edit removes the focused cell; only Chromium still fires its blur, which was the commit) — tryCellEditKey now commits the pending text itself before inserting the line. Rule of thumb: never rely on blur/focusout firing for an element a re-render removes. WebKit reports the benign "ResizeObserver loop" notification as a window error during diagram layout; no embed can hide it from a host listener registered earlier (Chromium delivers in registration order), it is harmless and the spec tolerates it.
Style isolation¶
The app stylesheet is global (html, body { height: 100%; background }, * { box-sizing }, :root variables, scrollbars). The embed build runs it through scripts/postcss-embed-scope.mjs, which confines it to .strukts-embed: html/body/:root selectors become the root class (theme variables, font and colour now live there), * becomes root, root *, everything else is prefixed, the page-level rule loses height/margin/padding and gains all: initial; display: block (so the host's inherited font/colour stop leaking in; it is attached to that one rule, in source order — the plugin runs per CSS file, a prepended reset would re-reset the colour). Verified on a styled host page: the host's body, headings, buttons and :root variables are identical before and after mounting.
Overlays (completion/intentions popups, tooltip, context menu, hint, live region, drag ghost, the gutter's measuring shadow) used to be appended to document.body, outside any scope. Editor now takes overlayRoot and mounts them through overlayParent(editor) (editor/shared.ts; default document.body, so the IDE is unchanged). mountEditor creates a per-mount .strukts-embed.strukts-embed-overlays root on <body> for it — position: fixed overlays escape the host's overflow clipping — and removes it on dispose(). A new overlay in src/editor/ must use overlayParent, never document.body.
Host tag-selector rules (button { … }, p { margin }, a CSS framework's reboot) are held out by a second rule the scoping plugin emits next to the page-level one: :where(.strukts-embed) :not(svg, svg *, math, math *):not(svg):not(svg) { all: revert }. Its specificity is (0,0,3): above a host's plain element rules, below every embed rule (all ≥ (0,1,0) once prefixed), so the embed's own styling is untouched and only what the embed never styled comes back to browser defaults. SVG and MathML are excluded — revert also discards presentation attributes (<svg width>, fill=) — so a host rule targeting those elements still applies. Because WebKit leaves -webkit-user-modify: read-only on contenteditable elements after a revert (editability is not a UA-stylesheet declaration there; every cell became uneditable), the plugin re-asserts read-write for them in a class-level rule after the reset. Host !important rules, and host class/id rules that happen to match, cannot be stopped from here. Verified by comparing the computed style of every element in the editor, problems list, Inspector and an open popup between a neutral and a hostile host page (identical), by showing the hostile sheet does restyle them without the reset, and by showing the reset changes nothing on a neutral host (tests/test-ui-embed-scope.spec.js, 3 engines).
Why not Shadow DOM: the editor reads document.activeElement in 30 places across 15 files and getSelection() in 9 across 5, and both are retargeted across a shadow boundary (activeElement returns the host; selection ranges are not reliably retargeted in Firefox/Safari), which is what caret placement, cell commit and focus restore are built on. Rewriting that is far larger than the problem it solves. Kobalte portals (the Inspector's Select/Tooltip/Popover/Dialog widget wrappers, src/ui/inspector-kobalte-*.tsx) mount into the nearest .strukts-embed root through portalMountFor(trigger) — evaluated when the portal opens, and createPortalReady holds each Portal back until the trigger is attached (next microtask; at most ~20 frames if it never is), so a widget that is already open at mount time also lands in the embed root; the IDE has no such ancestor and keeps Kobalte's default. Not covered: host CSS that targets elements by tag (button { … } still applies inside the embed — only Shadow DOM would stop that, at the price of re-plumbing the overlay root and every document-level listener).
The customer-facing showcase (embed/showcase/, npm run build:showcase)¶
Its Core scenario (Discounts) runs on the in-page evaluator:
mountEditor({ runtime: { engine: "evaluator" } }). Sincerun()became Python-backed the page's default would be a Pyodide download from a CDN, which its strict policy (default-src 'none') forbids, so the Discounts card stayed empty ("Not run: downloading the built-in Python runtime was declined.").tests/test-embed-showcase.spec.js"discounts: a decision table is drawn…" is the check.
Showing the selection's type (onSelect, types.describe, issue.explain). onSelect(nodeId | null) fires when the selected node changes (not again for the same node; a literal cell reports the node that holds it, the id the Inspector uses). ed.workbench.types.describe(nodeId) answers what a reader wants to know about that node from ONE type pass: its source text, its type in plain words (plain: "a number", "text", "true or false", from src/type-plain.ts, so a host never words types itself), and the type problems on it. A node with no type of its own (a parameter's name, an invisible wrapper) or an unknown one answers with the nearest enclosing node that has one (via names it); a statement (type void) and a node nothing is known about answer null, so a host hides its strip. A failed expression has type: null and its problem instead (a failed + is any). A node with no problem of its own that sits inside a failing expression (the discount of "Discount: " + discount, or the text beside it) has within: the nearest enclosing expression with its text and problems (the search stops at a statement), so a strip can say what the node is and what is wrong around it; a caret put on a problem's node by focusNode lands in its first cell, which is why that matters. Core's list carries no element type, so plain says "a list", never "a list of numbers". A language words its own type constructor with registerPlainTypeWord(con, {noun, phrase}) (src/type-plain.ts, called at plugin load): KernelF says "an amount in USD" for money<USD>, in describe, the Inspector and the type-error explanations alike, so a host never patches the words. The public website no longer draws its own strip: its "Selected" block is ed.mountInspector (the Inspector's header: a path, one sentence, what it refers to), shown after a selection and with the concept-name band hidden by the page's CSS. The pass is repeated per call (the engine keeps no cache over an edited tree): a host that selects a lot debounces, or calls types.analyze() once per check run. issue.explain is { reason, hint? } in plain words, present on an issue only when its concept's overload table declares .explain(reason, hint?) (typing.overloads(...).explain("...", "..."), or explain/hint keys of the object form; placeholders in src/type-contract.ts, OverloadDescriptor.explain, filled by src/type-explain.ts). v1 covers Core's +, -, * and / only (Core's comparisons are not type-checked at all, and call-argument warnings come from a generic path with no table to carry words); the engine's own message is unchanged, so every existing consumer reads what it read before. The Language Editor's hook card reads and writes both spellings (src/concept-hook-literal.ts). The website's home demo uses all three (assets/demo.js in the site repository: the "Selected" strip under the result card and the plain reason under each type problem).
scripts/build-showcase.mjs builds the embed library with the customers/embed-showcase profile (core, formula, diagram, coreDecisionTable; default language formula) into dist/showcase/embed/ and puts index.html + showcase.css + showcase.js beside it: one deployable static folder, every URL relative. The page imports only the public library, no IDE code. Three tabs (loan formula, discount decision table, approval flow), each seeded with ONE mistake the visitor fixes with the editor's own interactions; tests/test-embed-showcase.spec.js (built from a snapshot, 3 engines in npm run test:embed) drives exactly those fixes with real clicks and typing. The page builds its own Problems list from onIssues (plain-language messages, one entry per mistake, a different shape for error and warning) instead of mountProblems; the theme toggle remounts (the embed's theme is fixed per mount) and keeps the source; edits per tab survive tab switches and reloads (see "Remembering a visitor's edits" below). Brand it through the --sc-* variables at the top of showcase.css; the editor's size is set from the host with --editor-font-size on the editor's parent (it survives the embed's all: initial reset) and .host .editor.projectional { min-height: 0 } (the app stylesheet gives .editor a 400px minimum).
Found while building it (all fixed or recorded here):
- Fixed — every Table concept crashed in a real built embed. Vite's lib mode leaves process.env.NODE_ENV in the output; TanStack Table reads it on first use, so a decision table threw "process is not defined" on a plain page (the dev server defines it, which is why no earlier test saw it). vite.embed.config.js now defines it as "production".
- Added imports (EmbedOptions): Core's decision-table concepts live in the separate coreDecisionTable language that a model composes with Language#withExtraImports (the IDE does it from model.json); without it decisionTable(...) was drawn as plain call text.
- What the checker flags decides the seeded mistakes. A text threshold in a decision row (quantity >= "100") is NOT flagged; a blank cell is ("result slot is required"). Formula has no variables or assignment (principal = 1 is "no assign concept"), so inputs are literals. Type-replacing a string cell by typing is a dead end for a newcomer (type-over keeps it a string; Delete removes characters, not the node), so mistakes that need a new value are blanks, not wrong types.
- Fixed afterwards — operand parentheses were not drawn. Core drew (100 - discount) / 100 as 100 − discount / 100 and formula drew (1 + r)^-n as 1 + r^-n (the tree and the saved text were right; only the display read as a different expression, for every nested operator). Now drawn by the editor itself: see docs/architecture/projection.md "Operand parentheses". The showcase uses the natural expressions again.
- Not verified: Firefox (cannot launch under the sandbox the page was built in: "Could not find profile folder"); run npm run test:embed, which includes it, before publishing. Chromium and WebKit pass.
Phase 3/4 (usability and production), what was measured and decided¶
- Size. The folder was 5,228 files / 23 MB because
plugins/lang-python/stub-registry.tsglobs ~5,200 Python stdlib stubs into lazy chunks that nothing on the page loads.STRUKTJS_EMBED_NO_TYPESHED=1(set bybuild-showcase.mjs; pluginstrukts-embed-no-typeshedinvite.embed.config.js, which throws if the glob changes shape) rewrites that glob to{}: 23 chunks, 9.3 MB. A page whose modelsimport osneeds the stubs: build it without the variable. First load (loan tab): 18 files, 4.3 MB raw / ~1.0 MB gzip; the diagram tab adds one chunk (Sprotty). The spec asserts < 60 files, < 12 MB, first load < 30 requests / 5.5 MB / 1.4 MB gzip. - Hosting. Served from
/company/demo/underdefault-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; …: works, no failed requests. (style-src 'self'alone is NOT enough once the diagram tab opens, its inline style attributes are blocked (style-src-attr inline; found when the test asserted onblockedURI); andstyle-src 'self'; style-src-attr 'unsafe-inline'stopped being enough when the equipment tab arrived: the embed adds each language's concept CSS as a<style>element and the generated report document has its own<style>, both inline style ELEMENTS.) The only violation isscript-src eval(the engine compiles rule bodies withnew Functionand falls back when refused; checks, results and diagrams were compared with and without'unsafe-eval'and are identical). Failure path (asserted): a CSP without'wasm-unsafe-eval', a missingtree-sitter.wasmand a missing editor chunk each replace the spinner with the failure message within milliseconds on both engines, with a "details for the site owner" naming the likely causes; no static-screenshot fallback was built. In an iframe the page posts{type: "strukts-showcase-height", height}to its parent (ResizeObserver, +2 px so sub-pixel rounding leaves no inner scrollbar; the editor box's70vhcap is lifted in a frame becausevhis then the frame's own height). All asserted intests/test-embed-showcase.spec.js. - Touch. With emulated touch (Chromium, WebKit) a tap focuses a blank cell, typing works and tapping elsewhere commits it (a phone keyboard has no Tab): the instructions say "Tab or click elsewhere", and a coarse pointer shows a note. Real devices with a soft keyboard are untested (viewport resizing, scroll-into-view).
- Four things every embed got wrong until the public site's Pricing demo showed them (all pinned by
tests/test-embed-build.spec.js, "a function body is indented and folds ..."): (1) Folding did nothing.mountEditorpassed nofoldstore, so the editor folded into a private in-memory set while the renderer readsDocumentState.foldedNodes;foldStoreFor(state)(src/state/fold-store.ts) is the store of both the embed and the private editor. (2) The file's root was foldable: a chevron on line 1 (formula,robot file :,device :) hid the whole program;_isFoldableleaveslang.isFileRoot()out. (3) No indentation at all. A CSS Module (NodeRenderer.module.css,.suite) is hashed after PostCSS, so the scope plugin's.strukts-embedprefix was renamed with it (._strukts-embed_<hash> ._suite_<hash>) and matched nothing; the plugin writes:global(.strukts-embed)for*.module.css. A new CSS Module is safe; a rule outside both (neither module nor prefixed) is not. (4) Hidden line numbers could not come back. The embed keeps the toggle on its own.strukts-embedroot (not the host's<html>), and the gutter's menu is the only place that offered it, on a gutter that was gone: the editor's own context menu (and Shift+F10) offers "Show Line Numbers" while they are hidden. Not fixed, by design: the wholeif/elsechain is one foldable node, so folding either branch folds both. - Accessibility. axe (WCAG 2.2 AA + label-in-name) on all tabs, both themes: zero violations, in the page and in the editor inside it, asserted by the spec. The page's own findings were the theme button's accessible name (it must contain its visible text) and a real
tabpanel. The editor's own findings, first recorded and then fixed at their source: line numbers blended byopacity: .8to 3.7:1 / 4.41:1 (now full-strength--fg-dim), the light theme's--punct(#6b7280, 4.47:1 under the diagram title; now #656d7b), the Sprotty zoom-reset button's name not containing its visible percentage (now"67% - Reset pan/zoom (fit to screen)"), and a nested formula<math>with editable cells and no role (nested-interactive; now an unnamedgrouplike the outer one). A screen reader has not been used on it. - Not done, on purpose: hiding the
formula/printkeyword lines on the loan tab (they are the language's own projection; hiding them from CSS would misalign the line-number gutter); fixing the two parenthesis display bugs (above).
The equipment-selection tab (vibro): a rich language, and a generated HTML report on the page¶
The fourth tab embeds plugins/lang-vibro (a pile, a soil profile, a target depth and an equipment catalogue, ranked RECOMMENDED / SUITABLE / MARGINAL / NOT_SUITABLE by the ported engine) with four scenarios behind a list (the demo's own sample models, minus their narration comments), opening on a working result.
- The report. The language's default transformation has the extension
html(previewFormatis derived from it):ed.generate()returns a complete, script-free HTML document (the IDE's "Open Preview" shows the same text in a sandboxed iframe). The page writes it into<iframe sandbox="allow-same-origin">: noallow-scripts, so nothing in it can run, yet the page can write the document and measure its height (capped at 900 px; taller reports scroll inside the frame). It regenerates after every check run, so it follows the editor as the visitor types; while the model has an ERROR the last good report stays and the status chip says "Paused: fix the problem". - Neutral branding. The generated report carries the original tool's name and palette. The page substitutes its exact tokens (
NEUTRAL_BRANDinshowcase.js);tests/test-embed-showcase.spec.jsfails if any original name or hex survives in the frame. The one remaining brand word was in the engine's own text (engine.js, "Powered by a shared multi-functional IQIP powerpack…"), also shown in the editor's results panel, so it was removed at the source. - The embed now injects a language's concept CSS. A concept's
css(the soil drawing, status badges and cards of this language) reaches the IDE through the shell's global<style id="concept-scoped-styles">; the embed never called it, so the soil drawing was plain text lines.mount.tsxnow addsbuildConceptRules(lang)as a<style>inside each mount's own root: only the per-concept rules, each scoped to its own[data-head]nodes (they cannot reach the host page), removed ondispose(), no clobbering between mounts. It applies to every language, not only this one. - A latent bug found by it, fixed in the scoper. A
/* comment */inside a concept'scsswas glued onto the next rule's selector byscopeConceptCss(it splits on{), giving[data-head="x"] & .card.primary, which the browser drops. This language's primary-card styling (navy card, light labels) had been silently lost that way, in the IDE too.scopeConceptCssnow strips comments first (tests/test-concept-css-scope-comments.mjs). - Accessibility of this language's editor view (it failed axe with 89 findings; now zero in both themes on all four scenarios):
<Meter>names itself from a string label (aria-label,aria-valuetext), the empty-list placeholder textbox has an accessible name,--numin the light theme is #a8480a (4.32:1 on a tinted card before), status labels use--accent-text/--ok-text/--warn-text/--err-textinstead of the brand colours (2.47:1 on dark), the unit/margin labels are full-strength--fg-dim(an opacity blended them to 3.3:1), and the depth pill and target-line label have their own accessible colours. - Layout. The equipment table needs the full width (at the normal column width the editor's container clipped its right-hand columns), so this tab widens the page (
.page-wide:min(1760px, 97vw); the other tabs keep the 1180 px reading column) and puts the explanation and result in a row above a full-width editor (.wide-editor). - No duplicate results. The language's editor draws its own ranked-results panel ("selection results:" and the cards). With the generated report right below it, the page hides that panel by CSS (
.no-editor-results,:has(> .style-vibro-results-view)), a host rule on the language's own wrapper, leaving the pile, soil drawing, catalogue and orders. The panel is still computed (it feeds nothing else), only not displayed. - Open: the in-editor accent blue is a generic blue now; the editor's own wording still says "VibroSelect" where the language names its tool in tooltips and the Language pane.
"Under the hood" (loan and discounts): how it was calculated, generated Python, tests¶
A panel under the demo with up to three sub-tabs, rendered lazily (only the open one, after every check run; a model with an error says "Fix the highlighted problem" instead).
ed.runTests({ tests?, timeoutMs? })(new,EmbeddedEditor): the edited model's own statements are the shared setup,tests(source text of a test file in the same language, e.g. aTestSuite) is a second root, and the result is flattened into{ ok, passed, failed, cases: [{ suite, case, assertion, ok, message?, expected?, actual?, nodeId }], setupErrors }. It needs a test language in the build (testlangis in the showcase profile). A test can only call what the model DEFINES: the discount rules are therefore a function (def discount_for(quantity)), which is why that example shows adefagain after being flattened for the "no code shown" audience; the tests (discount_for(100) == 15, …) catch a rate the visitor changes ("Expected 15, got 12.").- Why there is no
ed.explain(). The engine has a "why this result" trace (src/trace-explain.ts), but it runs on the SYNCHRONOUS core, and only KernelF has synchronous rules (evalSync); Core, formula and decision tables report "no synchronous evaluation rule". Tracing the async evaluator is not sound (operands run concurrently underPromise.all, so enter/exit frames interleave). I added and then removedexplain()rather than ship a method that says "unsupported" on the samples being shown. The page instead builds the explanations from the public workbench API:workbench.generator.text({ root: subNode })for any sub-expression's text andworkbench.run.createEvaluator(...).evaluate(subNode, vars)for its value. "How it was calculated" (loan,stepsWhyin the site'sassets/demo.js) is built from the model's own named values, not from a fixed formula shape: everyformulaDefineis an input (a plain number, or a blank) or a step (a formula over the names above it), shown with its calculation once by name and once with the numbers filled in, plus which case eachpiecewisetook; printing a step's name marks it the result, any other printed formula is a step of its own. Each step is evaluated on its own with the names above it (evaluate(node, vars)), so one that cannot be worked out says what it waits for and the rest still show; a large formula with nothing named inside lists its main operands with their values. A change to a formula, a new define or a new variable shows up without touching the page. The sample names its intermediate results (owed_after_fee,to_pay_off,monthly_payment) for exactly that; a label is the name read aloud, so no engine change is involved; "Which rule applied" (discounts) re-evaluates the table's row conditions in order, in the model's final variable scope, marking the one that decides, the ones not met and the ones not checked. It is faithful for pure conditions; it is not an execution trace (a rule with side effects would be re-run). - Generated Python is
ed.generate()with Copy and Download (volume-discounts.py). The text was run under a real Python: 15% / $4,080.0 and 1432.49, the page's own numbers. - The Flow and equipment examples have no panel (the flow's generated text is a plain step list; the equipment report IS its under-the-hood).
tests/test-embed-showcase.spec.jscovers all three views, the failing-test message, the download, and audits each state with axe. - Lesson (again): a dimmed state ("Not checked") must be a colour, not
opacity, or it blends under 4.5:1.
The robot-maze tab (interactive generated page)¶
- Sixth language in the profile (
robot,customers/embed-showcase/customer.json). The result card parses the program's own output line (<name> ends at (x, y) …); the Live simulation section putsed.generate()(the language'spreviewFormat = "html"output) into#sim-frameviasrcdoc, sandboxallow-scriptsonly. It restarts on every clean edit (errors pause it) and only when the generated text changed. - CSP handshake. The frame inherits the page's CSP, so a strict
script-srcsilently blocks the generated inline script. The page appends a one-linepostMessage({strukts: "sim-ready", id})script to the document; no message within 2.5 s shows#sim-blockedand a "Blocked" chip.idties the message to the latest load, so a stale frame cannot flip the state. Asserted for both outcomes intests/test-embed-showcase.spec.js(the CSP test uses the strict policy from the hosting notes). - The editor also draws a static copy of the maze (
.style-maze-visual); the page hides it (.demo.no-editor-maze …, with the editor's own selector chain as a prefix: a shorter selector loses to the language CSS the embed injects, found live). - The tab grid is
auto-fit, not four fixed columns. Firefox could not be launched on the machine that wrote this (a browser-profile error, not a test failure): chromium and webkit were run, firefox was not.
Trying it¶
- Fast loop:
npm run dev, open/tests/fixtures/embed-demo.html(and/embed/dev/embed-host-demo.htmlfor the styled-host/isolation case).tests/test-ui-embed.spec.jsdrives these. - Built library:
npm run build:embed(→dist/embed/, or--out <dir>), serve it over HTTP (notfile://: wasm and lazy chunks), opendemo.html. - No-Core profile:
node scripts/build-embed.mjs --profile embed-nocore— same default output dir, so it overwrites the default build unless--outis given. - Automated:
npm run test:embed(Playwright,playwright.embed.config.js).
Build pieces¶
| File | Role |
|---|---|
embed/index.ts |
Library entry. Sets the tree-sitter wasm URLs (next to the bundle, or wasmBase / the __STRUKTJS_TREE_SITTER_*_WASM_URL__ globals) before dynamically importing the grammar pack and host — tree-sitter starts initialising when the pack is evaluated. |
embed/pack-python.ts |
The Python/JS/TS grammar registration. A pack lives outside src/ because general code must not import language plugins (language-agnostic-core.md); in the full IDE this registration is an accident of an eagerly globbed plugin, a pruned build has no such accident. |
vite.embed.config.js |
Reuses vite.config.js; lib build, no IDE public/, the scoping PostCSS plugin. Three entries: the editor, the headless core (embed/core.ts), the optional LionWeb helper. |
scripts/build-embed.mjs |
(--no-stage builds with the already staged full set and touches nothing shared.) Stages customers/<profile>/customer.json (default embed-minimal: core, formula, diagram, coreDecisionTable) into plugins-active/, builds, copies the wasm files, and always restores the full staging in finally. Run it in a throwaway git worktree (needs node_modules symlinked, src/generated/ and public/*.wasm copied — both gitignored) when other sessions share the checkout. |
Grammars: the Python pack (embed/pack-python.ts) registers python/javascript/typescript; the JS/TS tree-sitter grammars load their wasm lazily, so mountEditor awaits ensureGrammarLoadedIfRegistered(lang.persistenceGrammar) before the first (synchronous) parse, and getSource() prints through withSurfaceLang(lang, grammar, …) — the grammar's own printer, as serializeSourceFile does (a JSON language prints JSON, not Python-style calls). A language persisted as JS/TS/JSON only needs its plugin in the profile (jsgrammar, typescript, json); a plugin that registers its own grammar (sexpr, kernelf) needs nothing more. A profile may carry "embed": {"defaultLanguage": "<name>"}: the language mountEditor uses when the page names none (checked against the profile's kept languages at build time, injected as __STRUKTJS_EMBED_DEFAULT_LANGUAGE__). customers/embed-nocore is a build with no Core (simplest, sexpr plus the languages the engine itself still requires; default sexpr) — about a third smaller than the default profile and tested end to end (tests/test-embed-build.spec.js: default language applies, other Core-free languages mount by name, core is an "unknown language"). customers/embed-jsgrammar (core, jsgrammar, typescript, json; default jsgrammar) is the built-library proof for JS/TS/JSON persistence (tested in test-embed-build.spec.js). Without embed.defaultLanguage a no-Core build falls back to the workbench's own default, which is merely the first boot-tier language. A different language set = another customers/<name>/customer.json and --profile <name> (rules and validator: customization.md). npm run dev + embed-demo.html is the fast loop; tests/test-ui-embed.spec.js drives it (render, type error, typed edit, intentions, completion, two mounts, MathML, diagram lazy chunk, a plugin language's intention and reference completion); tests/test-ui-embed-scope.spec.js runs the real stylesheet through the scoping plugin on a styled host page (embed-host-demo.html); tests/test-embed-css-scope.mjs asserts no selector of the real stylesheet escapes .strukts-embed.
Measured (2026-10-18)¶
Full language set, dev-entry build: 3.56 MB static JS (2.56 MB = the language library). embed-minimal library build: entry 1.2 MB + NodeRenderer 0.66 + base-concept 0.54 for a first mount, 149 kB CSS; Sprotty (0.68 MB) and ELK load only when a diagram mounts (verified: no request before, request after).
Remembering a visitor's edits (2026-11-12; plan: embed-persistence-plan.md)¶
The library stores nothing (onChange / getSource / setSource are the whole contract); remembering an edit is the host page's job. Two pages do it, and the recipe is the same:
tests/fixtures/embed-demo.html(the library's worked example): since 2026-11-13 (plan 2 phase 2)localStorage["embed-demo.chunk.v1"]={ v: 1, chunk }, the model as a LionWeb chunk, written synchronously fromonChange(no debounce, so an edit followed at once by a reload is kept: a chunk throughgetChunkSync(), or the text under the old key while the LionWeb code is still loading, which the first change starts loading and then re-saves as a chunk), removed while the source equals the seed; Reset button; a "restored" line; a status line with the node count and stored size. On load: a stored chunk is mounted through thechunkoption and dropped for the seed when it is not a chunk, throws on import, or imports with a non-emptychunkReport(an unknown concept, i.e. another build's language); a value an earlier page version wrote as text (embed-demo.source.v1) is restored if it reads back as saved and becomes a chunk on the first save. Before 2026-11-13 the key held the source text.- The showcase (
embed/showcase/showcase.js):showcase-edit.v1:<tab>[:<scenario>]={ v: 2, seed, chunk }(since 2026-11-13: the model as a LionWeb chunk, node ids kept) or, as before,{ v: 1, seed, source }(text), whereseedis a 32-bit FNV-1a hash of the seeded example + language + imports, andshowcase-variant.v1:<tab>= the chosen scenario of a tab that has several. Written fromonChange(400 ms debounce) and flushed on tab switch, theme remount,visibilitychange(hidden) andpagehide. Read inselect(): in-memory edit first ({ source, chunk }, so ids survive a tab switch), then the stored one. Writes are synchronous (pagehidecannot wait for a promise):writeEditstores a v2 chunk throughgetChunkSync()and falls back to the v1 text entry when the LionWeb code is not loaded yet;warmChunkloads that code on the editor's first change, so a visitor who never edits never fetches it (tested) and one who does has it long before the debounce fires. A v1 entry (what plan 1 wrote) is read as before and becomes a v2 entry on its next save. A v2 entry that is not a chunk, has an unknown version, a stale seed, or imports with a non-emptychunkReport(another build's concept) is dropped for the seed; a variant change applies a stored chunk withsetChunkand treats a lossy report the same way. A restored tab shows "Your edits from last time are restored. Reset starts over."; Reset and a scenario change clear/replace the entry; each scenario keeps its own.
Rules that were found the hard way (each is pinned by a test):
- The printout is not the authored text. The editor prints without a trailing newline and drops blank lines, so "equal to the seed" must compare without whitespace-only differences, and the showcase also learns the editor's own printout of each seed (
printedSeed) because a seed's layout may differ. Without this, Reset (which reports a change throughsetSource) stored the seed as an "edit". - The parser repairs, it does not throw. A stored text it cannot read comes back as a different tree, not as an exception, so the page checks that the mounted source equals what was stored (ignoring blank lines and trailing whitespace; an exact comparison discarded a valid edit that contained an empty statement). If not, or if the mount throws, the entry is removed and the seed is mounted.
- A stale seed drops the edit (the showcase is a guided walkthrough of one seeded mistake; an edit against a changed example teaches nothing).
- Storage can be unavailable (a sandboxed
<iframe>withoutallow-same-origin, blocked site data): every call is in try/catch and the page keeps edits for the visit only. The library itself used to fail at load in that case (src/state/app-state.tscalledmakePersistedonwindow.localStorageat import time, which throws); its persisted signals now go throughsrc/state/safe-storage.ts(aStoragethat falls back to memory), so the embed starts in a blocked frame.localStorageis still the only thing touched; nothing is sent anywhere. - A test that edits and then navigates again must clear the entries (the axe test's dark pass starts from the seeded mistakes through an init script).
- Uncommitted cell text (a literal buffers typing until blur/Enter) is not saved.
Tests: tests/test-ui-embed.spec.js (embed-demo: reload keeps the edit and its node ids, Reset forgets it, a damaged text entry, an old text entry upgraded to a chunk, a corrupt chunk, a chunk with an unknown concept, blocked storage) and tests/test-embed-showcase.spec.js ("remembered edits": reload, Reset, per-tab, per-scenario, stale/damaged/unreadable entries, blocked storage), Chromium and WebKit run here (Firefox could not launch on the machine that wrote this). A LionWeb chunk instead of source text is plan 2, not built.
LionWeb chunks (2026-11-13; plan: embed-lionweb-plan.md)¶
getChunk()/setChunk(chunk) and the chunk mount option move the model as a LionWeb serialization chunk (tools/lionweb, lionweb.md) instead
of source text. Only model-export.ts and model-import.ts are imported, lazily (a separate chunk of the bundle, ~22 KB minified; the first getChunk is
asynchronous), so a page that never asks for a chunk loads nothing extra. The embed keeps the path -> id/fingerprint sidecar of the last export or import, so
a node keeps its LionWeb id across edits, setSource and a reload through chunk. A chunk the language cannot fully read is imported without the
offending nodes and report / chunkReport lists them; a non-chunk or a chunk of other than one root rejects. getChunkSync() returns the chunk without waiting when the code is already loaded (else null), for a handler that must write synchronously. embed-demo.html and the showcase store their remembered edits this way (see "Remembering a visitor's edits"); the repository transport is the optional second entry below.
A LionWeb repository as a second store (2026-11-14; plan phase 5)¶
For a customer who runs their own LionWeb repository. Not part of the default bundle and not shipped by the public showcase (build-showcase.mjs deletes it; the showcase spec asserts that, and that no showcase file contains the bulk client). embed/lionweb.ts is a second library entry (vite.embed.config.js: lib.entry is an object; dist/embed/struktjs-embed-lionweb.js, ~6 KB, sharing only a tiny runtime/types chunk with the editor, so a page that never imports it never loads it).
connectRepository(ed, { url, repository?, token?, clientId?, debounceMs?, onStatus?, fetch? }) returns { partition, status, partitions(), pull(id?), push(), changed(), flush(), dispose() }. It uses only the public chunk API plus LionWebServerClient (tools/lionweb/src/server-client.ts):
- Ids.
getChunk({ version, newId })(ChunkOptions): the helper asks the repository's own serialization version (repositoryVersion(): a chunk must equal it) and passesnewId = () => "e" + crypto.randomUUID(), so two models never share an id (path-derived ids collide across models of one name, the reasonpushModelmints ids from the server). A node keeps the id it has, so a re-push isstore, which the server diffs; nothing is deleted and recreated. The embed's own path/fingerprint sidecar (see "LionWeb chunks") carries ids across edits and across apull. - Flow.
pull(id?):retrievethe partition,setChunk; the id defaults to the bound one, else the repository's only partition (several: the error lists them; none: "push first").push(): export,listPartitions,createPartitionswhen the root is new, thenstore. Pulls and pushes are serialised; an edit made during a push goes out in the next one.changed()(call it fromonChange) debounces a push (default 1 s) and never throws: failures are instatus/onStatus, the edit stays pending (dirty) for the next push. A pull's own change is not sent back (applyingflag, plus the pending push is cancelled aftersetChunk; either alone suffices, the test only fails with both removed). - Not built, on purpose. The live-sync (delta) protocol and the project-side
model.jsonsidecar (the embed has no project). It is pull on demand, push after an edit, last writer wins: a stale page overwrites a newer model on its next push. Edits made between apullrequest and its answer are replaced by the pull. - Token. Kept in the closure only, sent as the raw
Authorizationheader (the server's convention), never stored (a test checkslocalStorageand the connection object). A token in a static page is public: use a read-only repository or a proxy that adds it. The repository must allow the page's origin (CORS): the reference server does. - Demo and tests.
embed/dev/embed-lionweb-demo.html(dev server;npm run lionweb:demo -- upstarts the repository).tests/test-embed-lionweb-repository.mjsruns every flow against an in-memory stand-in that follows the real server's rules, and against a real repository whenSTRUKTJS_LIONWEB_SERVER_URLis set (it empties the repository first and last: run it alone).tests/test-ui-embed-lionweb.spec.js(opt-in, same variable) drives the page in a real browser across origins (push, list, pull into a second window, push after an edit, an unreachable address, the token not stored).tests/test-embed-build.spec.jschecks that the built helper is its own small file, in no editor bundle or chunk and never requested by an editor page, and (opt-in) pushes and pulls with the BUILT files.
The headless core entry (2026-11-14; plan: component-split-plan.md, P0-P2)¶
struktjs-core.js (embed/core.ts -> src/core/index.ts) is built by the same vite.embed.config.js run as the editor, as a third lib.entry, so both share ONE copy of the engine and of the language/grammar registries (one chunk defines Language; tests/test-embed-build.spec.js asserts it). createCore({ languages, defaultLanguage? }) registers the languages it is given (it does not import boot-languages.ts/lang-library.ts: those discover a language set at build time through a glob, which would bake a profile in and, built, find no plugins/ on Node), resolves their imports, loads each registered persistence grammar, and returns { workbench, language(name), languageNames(), parse(source, {language?}), model(root, {language?}) }; a model has check(), types(), run(), generate(), print(), syntaxError. It is a thin facade over the headless workbench (workbench.surface/checks/types/run/generator), not a second implementation. It also re-exports the language-authoring surface (BaseConcept, ChildSlot, Prop, Ref, conceptsFromModule, check/infer/evaluate, the JSX factory, node/empty, toKdl/parseKdl, registerGrammar), provisional until P3.
Measured on the shipped (pruned) build: static chunk graph of the entry = 11 files, ~1.09 MB raw (the engine, 967 KB of it one chunk), no Solid runtime, no lang-library, no ELK/Sprotty; the test budgets < 25 files and < 1.4 MB. It runs in a real browser (Chromium, loaded from the served build, no editor mounted; test-embed-build.spec.js) and in plain Node with no DOM global, with a language written like an outside consumer would (tests/fixtures/core-consumer/, run by run-built-core.mjs): check, run() (13), generate(), an unbound name reported and run() rejecting.
The public showcase (scripts/build-showcase.mjs) deletes struktjs-core.js like it deletes the LionWeb helper (its page imports only the editor, and distribution of the core is private); tests/test-embed-showcase.spec.js asserts it is gone.
Layering is a ratchet (tests/test-core-layering.mjs, helper test-support/import-closure.mjs: TypeScript's own import scanner, type-only and dynamic imports skipped): the closure of ast, kdl, scope, surface, Language, checker, type system, evaluator, generator, the workbench API, the LionWeb exporter and the core entry may not reach solid-js*/kobalte/sprotty/elk/yjs, src/state/, components/ui/routes/collab, the Editor or its mixin, or read a browser global at module top level. It is by reachability, not folder name (editor/slot-helpers.ts is pure and fine). Two imports in workbench/project.ts were the whole problem and are cut: Editor#setChild's body is now src/set-child.ts (setNamedChild, used by the Editor and by the loader's headless stand-in for @migration code steps), and "is this project still open in a document?" asks a registered source (setDocumentProjectsSource in workbench/document-projects-source.ts, a module of its own with no imports, installed by state/instance-registry.ts; with none registered nothing is live, which is what a headless host has). It is its own module because nine tests mock workbench/project.js with partial factories: a registration that lived in project.ts was lost with the mock and instance-registry failed to load. vscode-bridge.ts stays in core: it imports nothing and is a no-op outside a host. The project loader (workbench/project.ts, model-language.ts, project-rules.ts, project-generator-overlay.ts) is out of the core's source closure too (P2b): the pure name/slug/language-of-root helpers the engine uses are workbench/project-names.ts, which project.ts re-exports; the layering test forbids those four files. (The built core never contained the loader: the bundler dropped the unused functions. The rule guards the source closure.)
Found, not fixed: workbench.surface.parse(text, { checked: true }) cannot work: parseSurfaceChecked returns a { ast, hasError, diagnostics, positions } result, parseSurfaceNode then rejects it as "did not parse to a node". The core uses parseSurfaceFlagged ({ ast, hasError }, every grammar) instead.
Language packs and the grammar entry (2026-11-14; plan: component-split-plan.md, P3-P4)¶
createCore({ packs, languages }) takes languages as packs: { name, modules: [{ sourceFile, mod }], devkits }, exactly what lang-library.ts's build-time discovery sees for one plugin. The discovery logic that turns modules into ordered descriptors (tier, hidden, dependsOn, load(), devkit merging, topological order) moved out of lang-library.ts into the pure src/language-catalog.ts (descriptorsOfPlugin, finishCatalog, buildCatalog); lang-library.ts keeps only its discovery (the glob in a bundle, readdirSync on Node) and calls it, so the IDE and a pack consumer get the same descriptors in the same order. That refactor is behaviour-identical (checked against the HEAD module: same name lists, same default language, same _sourceFile on every concept of all built-in languages). createCore registers every non-hidden language of the packs (and the hidden ones a model may import) in dependency order, resolves imports, seeds the default language's imports from the lang-stdlib languages when it has none (what boot-languages.ts does for the IDE), and throws "diagram" imports "core", which no given pack or language provides when a dependency is missing.
scripts/build-embed.mjs generates one entry per staged plugin that has languages (import.meta.glob over that plugin's languages/*.js and *.devkit.json, in filename order) into a temp directory and passes it to vite.embed.config.js (STRUKTJS_EMBED_PACKS_DIR), so the build writes packs/<plugin>.js beside the editor and the core, sharing one engine chunk; --no-packs skips them (the public showcase, whose chunking and first-load request count changed when 70 extra entries existed, and which deletes packs/ anyway). embed/grammar-python.ts is the grammar entry (loadGrammarPython({ wasmBase? }): URL globals in a browser, __STRUKTS_WASM_DIR__ in Node, then pack-python.ts).
Measured on the full set (2026-11-14, static chunk graphs): engine alone 1.09 MB raw; engine + Formula 1.18 MB; Core pack 2.0 MB; core + Core/stdlib/Formula/Diagram/decision-table packs 2.19 MB; none carries Solid; each pack file is 0.7-3.5 KB. tests/test-embed-build.spec.js asserts the shape, the budgets and, in real Chromium from the served shipped build, that real Core, Formula and Diagram source parses, checks and runs and a missing dependency is the clear error. tests/test-core-packs.mjs does the same from source with the real plugins.
Found while doing it:
- core-editor-ops.js made every Core consumer load the Editor and Solid (it did Object.assign(Editor.prototype, ops) on load: the Core pack was 3.1 MB with a Solid runtime in it). It registers through src/editor-ops-registry.ts now, and editor.ts binds its prototype at the end of its module, so the ops are installed exactly as before whichever module loads first. A headless host never loads the Editor and leaves them pending. tests/test-core-layering.mjs now also checks every language module of the first-release plugins (lang-core, lang-stdlib, lang-formula, lang-diagram, lang-core-decision-table); lang-testlang is excluded on purpose (its runner drives a real detached Editor). src/components/slot-utils.ts (15 pure lines under a UI folder) is the one listed exception.
- plugins/lang-python/stub-registry.ts crashed at import under Node when no typeshed/ folder sits beside the module (its Node branch walks one): a built bundle has none. No stubs is a valid state now (no completion or types for import os); the stubs are the opt-in extra the plan decided on.
- The browser files cannot run under Node. The bundler stubs node:module for the browser target, so web-tree-sitter's Node glue fails (createRequire is not a function); languages that need no tree-sitter (the calc fixture) run from them, Core and Formula do not. That is why the build also writes <out>/node/ (P3b, below).
The Node build (<out>/node/, 2026-11-14; plan P3b)¶
scripts/build-embed.mjs runs a second build, vite.embed-node.config.js, over the same non-DOM entries (core, grammar-python, one pack per staged plugin): ssr with noExternal, target: node22, classic h() JSX for concept editors, code splitting on (so the core and every pack share one engine chunk; build-strukts-cli.mjs is the single-file variant of the same idea), its own copy of the four wasm files beside the grammar entry (./wasm/). It is a separate config on purpose: vite.config.js, which the browser embed config extends, stubs fs/path for web-tree-sitter and swaps yjs for a window global. --no-node skips it (also skipped by --no-packs; the public showcase uses both). The Python stdlib stubs are left out of both builds by the shared scripts/vite-no-typeshed-plugin.mjs (without it the Node build had 5,348 chunks / 31 MB: the stub glob still emits one chunk per .pyi even when the stub-registry's Node branch would read them from disk). Result: real Core, Formula and Diagram source parses, checks and runs in a plain Node process with no DOM from the shipped (embed-minimal) build (tests/test-embed-build.spec.js, tests/fixtures/core-consumer/run-node-packs.mjs); the pruned build's Node folder has under 200 chunks. On the full 71-plugin set the folder is 15 MB, mostly the lazy ELK/Sprotty/editor chunks a headless consumer never loads.
The npm packages @struktjs/* (2026-11-18; plan: workbench-modularization-plan.md, P4; the single @struktjs/* package of 2026-11-14 is gone)¶
scripts/build-package.mjs (npm run build:package; --profile, --out dist/package, --skip-build, --no-pack, --with-stubs) builds the embed ONCE (profile embed-minimal, STRUKTJS_EMBED_NO_TYPESHED=1, STRUKTJS_EMBED_NO_BUILTIN_LANGS=1, Node build and packs included) into dist/package/, emits the pruned declaration tree types/, and scripts/assemble-packages.mjs then PARTITIONS that one build into dist/packages/<id>/ (core, grammar-python, editor, widgets, lionweb, diagram, lang---with-stubs) and npm packs each to dist/struktjs-<id>-<version>.tgz. Nothing is published; the tarballs are the distribution, installed TOGETHER (the peers are pinned to the exact version, because a package imports its dependencies' hashed chunk files and so belongs to exactly one build of them).
- The partition (
scripts/package-layout.mjs, pure and tested bytests/test-package-layout.mjs): every file reachable from an entry (found with TypeScript's parser over static and dynamic imports, never a scan of bundle text) goes to one package: a file reached by one package is its own, a file shared by several goes to the one package all the others depend on, else tocore; the ELK layout engine is thediagrampackage by an explicit hint. The dependency table (DEPENDENCIES) is the only thing that says which edges are allowed, and an edge it does not allow fails the build (browser, Node and declarations). Every import of a file another package owns is rewritten to@struktjs/<owner>/<path>(chunks/*andnode/chunks/*are exported for that and are not API); assets loaded withnew URL(.., import.meta.url)travel with the module that loads them (the Pyodide worker is the editor's); the wasm folders aregrammar-python's; the stylesheet iswidgets' (@struktjs/widgets/style.css: the widgets are styled by it and a widgets-only install has no editor). A chunk no entry reaches is dropped and reported (todayproject-concepts). - The editor carries no languages.
src/lang-library.tsglobs every staged plugin's language modules, which made the editor entry reach every pack's code; the package build empties those globs (scripts/vite-no-builtin-languages-plugin.mjs, which throws if the glob changes shape) andmountEditorwithout acoreis the errorthis build has no languages of its own; pass { core }. The single-bundle embed (build:embed, the showcase) keeps its built-in languages. exportsper package (generated, never hand-kept):.(types, thennode->node/…, thendefault-> the browser file;lionweb,widgets,editorhave nonode),./chunks/*,./node/chunks/*,./types/*({ types: "./types/*.d.ts" }), plus./wasm/*(grammar-python),./style.css(widgets) and whatever file another package imports that is not underchunks/. NosideEffectsfield: the grammar entry registers its grammars from a chunk nothing imports by name, and a bundler that believed it side-effect free dropped it (found by the Vite consumer).diagramhas no.entry: it is an internal package.peerDependenciesare the table's, at the exact version;dependenciesare only what a package's declarations name (zod, from core'slang-schema.d.ts); the script FAILS when a built file of a package imports a bare specifier that is not a Node builtin or a@struktjspackage.- Declarations come from
tsc --emitDeclarationOnlytwice (tsconfig.package-core.json,tsconfig.package-editor.json; Solid JSX for the editor),.tsspecifiers become.js(includingdeclare module "./x.ts"augmentations, which the Workbench type needs), the files reachable from the entries are kept, and then the SAME partition is applied to them: a relative specifier naming another package's declaration becomes@struktjs/<owner>/types/<path>. A language package'stypes/pack.d.tsis generated (aLanguagePackof core's types). - Found by building it: the
editorstatically imports the diagram layout module (only ELK behind it is lazy), sodiagramis a hard dependency of the editor until P6 loads the renderer through a port; a consumer install of the editor without it failed with an unresolved@struktjs/diagram/chunks/….OPTIONAL_DEPENDENCIESis empty today. - Consumers (
tests/consumers/,npm run test:consumers,playwright.consumers.config.js):global-setup.mjsinstalls the PACKED tarballs into fresh directories under the OS temp dir, a SUBSET each (never the working tree: inside the repository Node would climb into itsnode_modulesand pass vacuously): Node with core + grammar-python + lang-core only (no editor), Node with formula and diagram, the smallest editor install, widgets with no editor, a plain HTML page (an import map from each package name to its folder), the Vite app (the repository's vite; wasm copied intopublic/,wasmBase), and a TypeScript program (tsc --noEmit,skipLibCheck: false, bundler and nodenext). The spec asserts each install is exactly its dependency closure and holds ONE physical copy of@struktjs/core, that peers are pinned to the version, and that a mount without acoreis the clear error.STRUKTS_PACKAGES_DIRpoints at another folder of tarballs;STRUKTS_KEEP_CONSUMERS=1keeps the temp directories. CI (.github/workflows/ci.yml) builds with--with-stubsand runs all three browser engines. - The editor over a core (P5).
EmbedOptions.core(acreateCoreresult;Core#defaultLanguageis new for it):bootLanguagesthen returns the core's default language and never runsbootCoreLanguagesHeadless(the build's glob discovery),language/importsresolve through the registry (this mount's own instance, else the page-global registry, where a core registers its languages) and the on-demand demo-tier activation is off. A name nobody registered isunknown language "x" (the core given to mountEditor has: …). Since P1 (instance-owned registries) every core owns aLanguageRegistry(core.registry): two cores in one page, or one process, can hold a same-named, different language, a language only another core registered is invisible through this core (the clear unknown-language error above), and the page's default registry (getLanguage/registerLanguageof the core entry, the IDE's) is touched by no core. Editors over one core share itsLanguageinstances (no per-mount copy as with the build's own demo languages). Isolation holds for definitions and packs; aLanguageOBJECT handed to two cores is one object in both. Grammars:createCore({ grammars })(and a pack'sgrammars) register persistence grammars on the core's own composition, ahead of the page's, so two cores can hold a same-named, different grammar; the reads of the parse, print and file-format stack resolve through theLanguagein hand (GrammarScope: the language's registry's composition, then the page's default). A grammar a language module registers by being imported is the page's and is shared. Still global: the grammar reads of the editor and the IDE (no language in hand or not yet scoped, they see the page's grammars only: an editor mounted over a core whose own grammar the page does not have parses with the page's) andctx.workbenchinside a language's own hooks (the page's workbench, resolving names in the page's registry). Withoutcorenothing changed (BUILD_DEFAULT_LANGUAGEstill applies only then). Tests:test-embed-build.spec.js("built editor over a core": unknown language, default language, two editors, headless run beside them) and both page consumers. - Widgets (P6).
embed/widgets.ts->src/embed/widgets.tsis the./widgetsentry (struktjs-widgets.js, a re-export of a 2.8 KB chunk):mountProblems(el, { issues, onSelect, theme })->{ update, dispose },mountResults(el, { result }),renderProblems(list, issues, onSelect); plain DOM, no Solid, no engine imports (its own structuralProblemItem/ResultDatatypes instead of the editor's, so its declaration closure stays small), listed intest-core-layering.mjs. The editor handle'smountProblemsdraws throughrenderProblems(one drawing routine; the editor-bound one still focuses the node). The styles are the existing.strukts-embed-problem*rules plus new.strukts-embed-results*ones inembed/embed.css, so a widgets page loads the wholeeditor.css(212 KB): a separate small stylesheet would need a second CSS output of the scoped build (not done). The Inspector stays on the editor handle (it needs the selection and aDocumentState); the run panel the plan names did not exist inmount.tsx(run()only returns lines), somountResultsis new. Check:tests/consumers\"core + widgets page\" (a headless model's problem drawn, clicked, updated, run output drawn, and no request for the editor entry or the renderer). The public showcase deletesstruktjs-widgets.jslike the core. - Known limits. The Vite dev server is not covered (pre-bundling moves the files;
wasmBaseandoptimizeDeps.exclude). The stdlib stubs are an opt-in build:build-package.mjs --with-stubssetsSTRUKTJS_EMBED_STUBS=1, which adds theembed/stubs-python.tsentry to both configs (its ownimport.meta.globovertypeshed/**/*.pyi, ~5,200 lazy chunks per build, browser and Node: 7.3 MB packed, 10.6k files) and the./stubs-pythonexport;loadStubsPython()calls the newregisterStubLoadersofplugins/lang-python/stub-registry.ts, which merges the loaders and drops the module index. The embedded editor now callseditor.setStubs(getImportCompletionSourceForLanguage(language), [])when it mounts (it never did, so even a build with stubs had no import completion): with no stubs registered that is an empty index, as before. The editor reads the registered stubs AT MOUNT, so load them first. The headless core never callsensureStubs, so stubs do not changemodel.check(). Tested by the consumers' "stubs-python" case (skipped unless the package has the entry; CI builds with stubs).api-surface.mjsnow coverssrc/core/index.tsandembed/grammar-python.ts; adding them reordered a few union members in other surfaces' signatures (same types, new print order), accepted in the same snapshot write.
The public site's JavaScript size (2026-11-19; npm run build:site)¶
The public website (scripts/build-site.mjs) is assembled so that the visitor downloads as little as possible, and a test keeps it that way. Measured on the home page (40 requests, a Brotli client, headless Chromium): 813 KB of JavaScript before, 767 KB after minification and precompression, 690 KB after the lazy translation tables, 561 KB after the language split; the whole page went from 1.13 MB to 873 KB on the wire.
- Full minification of the embed, for the site only. Vite's ES library mode leaves the whitespace in (it assumes the consumer's bundler minifies), so the package build and the showcase ship readable files on purpose.
STRUKTJS_EMBED_MINIFY=1, which onlybuild-site.mjssets, turns onrolldownOptions.output.minify, lightningcss for the CSS andcomments.legalinvite.embed.config.js.keepNames(fromvite.config.js) stays on becausebase-concept.tsreadsCls.nameat runtime; checked in Chromium (classNameof the concepts of a minified build readsBinomial,Block, ...). Measured on the five biggest chunks: raw size -25%, Brotli size only -8%, because the output was already mangled and Brotli swallows whitespace: the gain is mostly parse time. There is no obfuscation step on purpose (control-flow flattening and string arrays make the code 2-4x bigger and slower; property mangling would break the concept heads, AST names and the rule bodies compiled withnew Function). - Legal comments. Rolldown 1.2's bundler output has no "linked" or "external" mode for them (
comments.legalkeeps or drops; those two modes exist in its standaloneminify()only), so the site's embed keeps them inline:comments: { legal: true }. The deprecatedlegalComments: "inline"option silently DROPPED every header once the output was minified (the first measurement said "0 left"); the current option keeps the five dependency headers the bundle carries (noble-ciphers, micro-rsa-dsa-dh, decimal.js, regenerator-runtime, the Microsoft tslib header: about 1.3 KB). The generated notices page still lists every licence.build-siteprints how many legal comments remain in the embed JS. - The site's own files.
scripts/site-finalize.mjsminifies the site'sassets/*.js(Rolldown'sminify) and*.css(lightningcss) in the output folder; the sources in the F1RE repository stay readable. - Precompressed siblings. The same script writes a
.br(Brotli 11) and a.gz(gzip 9) next to every text or wasm file of at least 1 KB, kept only when 5% smaller. GitLab Pages cannot set headers or compress on the fly, but serves a precompressed sibling to a client that accepts it.embed/anddocs/are git-ignored in the F1RE repository, so their siblings travel with the folders (build-site --install); the site's own pages get theirs from a step in that repository's.gitlab-ci.ymlafterjekyll build(gzip, and Brotli whenapt-getcan install it; it never fails the deploy).scripts/site-serve.mjsis the same behaviour for local runs, andplaywright.site.config.jsstarts it, so the site specs run against the compressed files.--no-minifyand--no-precompressskip the steps. - Lazy UI translations.
theia-extension/src/shared/i18n.tsimports the German and Dutch tables statically (382 KB raw, 78 KB Brotli: the whole IDE's strings, almost none of which the embed renders). In a build withSTRUKTJS_EMBED_LAZY_I18N=1(build-site.mjsonly)scripts/vite-embed-lazy-i18n-plugin.mjsturns the two JSON imports into empty tables (it throws ifi18n.tschanges shape; theDICTSkeys stay, soTRANSLATED_LOCALESis the same), andmountEditor(src/embed/mount.tsx) loads the table of a translated locale as a lazy chunk (import.meta.globoveri18n-*.json, no locale hardcoded) and hands it toregisterDictionarybefore it renders;t()stays synchronous. English visitors fetch nothing, ade/nlvisitor one 190 / 184 KB chunk (tests/test-embed-lazy-i18n.mjs, and the last test oftests/site/size-budget.spec.jsin the browser). The default build is unchanged (no extra chunks), which was checked by listing the chunks. - Languages as packs (the language split). The editor of the site carries no languages (
STRUKTJS_EMBED_NO_BUILTIN_LANGS=1: the entry chunks hold the engine and the renderer), every language is a pack (embed/packs/<plugin>.js, the component-split packs below), and the first editor of a page loads only the packs its language needs. Measured: Core on first paint is 650 KB Brotli before the other pieces, against 813 KB with every language inside (languages compress well: the KernelF pack is 89 KB, JS 28, TS 47, Formula 18, so the saving is 20%, not the 50% the raw sizes suggest); switching to the Formula tab afterwards costs 15 KB and 4 requests. - The manifest is generated, not written by hand.
scripts/build-embed.mjsalso builds the Node packs (STRUKTJS_EMBED_PACK_MANIFEST=1adds the build-only entryembed/pack-manifest.ts, which describes a pack withbuildCatalog, the functioncreateCorereads packs with), andscripts/site-pack-manifest.mjswritesembed/packs.jsfrom them: which language lives in which pack, what it imports (dependsOn), the default language and the standard-library languages, plus the file lists of the next paragraph; it fails the build when a language imports one no pack provides, then deletes the Node build. The site'sassets/core-loader.js(F1RE repository) works the pack set of a tab out from it (the language, what it imports transitively, and for the default language the standard library, whichcreateCoreseeds the builtinsprint,len, ... from), keeps one core per language-and-imports set, and mounts the editor over it;createStagechecks its sequence number again after the packs load, so a later pick still wins. - Preloading, because the split alone was slower. Many small packs and chunks put the editor on screen later than the monolith (4G, 40 ms / 12 Mbit/s: 1358 -> 1849 ms; slow, 150 ms / 1.6 Mbit/s: 6.5 -> 7.0 s; the same +500 ms on both, over HTTP/1.1 and HTTP/2) although it sent 130 KB less: manifest, then packs, then their chunks, then the grammar's wasm, then the editor chunk, one after the other.
scripts/site-preload.mjsworks the module graph of the core, of the editor (struktjs-embed.jsplus the two files it imports on mount) and of every pack out of the BUILT files (hashed names),embed/packs.jscarries the lists, the loader preloads them (modulepreload, and the wasm aspreload as=fetch) the moment it first runs, and a page whose first editor is on screen at once says so in its head,<!--strukts:preload core coreDecisionTable testlang-->:build-siteturns the comment into the links, so the downloads start before any script has run (the home page: 39 links). Result, same emulation: 1348 ms on 4G (the monolith: 1349) and 6.0 s on the slow profile (6.5): never slower, 130 KB lighter. The request count is higher on purpose (40 -> 67 on the home page); it is cheap over HTTP/2, which GitLab Pages speaks. - Parity. The 53 specs of
tests/site/(every home tab, every gallery card, the Workbench stages, a remembered edit restored from a LionWeb chunk) pass on the split build, and a differential run captured the visible text of the five home tabs, the seven gallery cards and the Workbench page from the monolithic and the split build: all 13 identical, no page errors in either.--embed-fromnow needs a build of this shape (it haspacks.js). - Documentation. A docs page cost 860 KB on the wire, 639 KB of it the search index (2.7 MB raw) that Material fetches on EVERY page load, before anybody searches.
website/site-overrides/assets/javascripts/site-lazy-search.js(site docs only, included bysite-overrides/main.html) runs before Material's bundle and holds that one request back (it is anXMLHttpRequestof RxJSajax, not afetch; both are held) until the search box gets focus (thes/f//shortcuts focus it) or the narrow-screen search toggle changes; the first search then waits for the index. Measured: a docs page 860 KB -> 222 KB with Brotli siblings (526 KB without them), search works on desktop and phone (tests/site/docs-budget.spec.js).scripts/build-site-docs.mjsalso removes the source maps (1.2 MB; and theirsourceMappingURLcomments) and re-encodes the PNG screenshots losslessly with sharp in the OUTPUT only (9.2 -> 4.1 MB; the sources of the in-app docs are untouched). HTML minification (mkdocs-minify-plugin, a new pip dependency of the in-app docs build too) was measured and left out: it saves 7% of the docs' Brotli HTML. - The budget.
tests/site/size-budget.spec.jsscrolls each page like a visitor and fails when the bytes on the wire (request.sizes().responseBodySize), the JavaScript alone or the request count exceed a budget (the measured size plus ~10%), or when a large file arrives uncompressed. A change that makes a page lighter should lower the numbers there. 2026-11-22: the home page's budget went from 620 KB of JavaScript / 960 KB in all to 700 KB / 1010 KB (measured 645 KB / 939 KB: the editors the home page gained since 2026-11-19 and a licence notice on every file); the Toolkit and Workbench budgets are unchanged.
Publishing the site (npm run publish_website, scripts/publish-website.mjs)¶
The F1RE website repository (../www.f1re.io, GitLab) tracks the built struktjs/embed/ and struktjs/docs/ (committed; the Pages job does not build them, it only writes the .gz/.br siblings), and CI deploys from master only. publish_website is the whole route from this checkout to a branch the owner can open a merge request from: it refuses when this checkout has uncommitted changes to tracked files (--allow-dirty overrides; the build is of the working tree and the commit names the sha), runs build-site.mjs with the documentation and --install, creates struktjs-update-<date>-<sha> (or --branch) from the site repository's current HEAD, commits only struktjs/embed and struktjs/docs on it (uncommitted edits to the site's own pages are listed and left out: commit them first), pushes it with git push -u origin (HTTPS credentials from the keychain / glab auth login), switches the site repository back to its branch and prints the merge-request link. It never opens the merge request. --no-push stops after the commit, --no-build installs what dist/site already holds. If embed/ and docs/ did not change, no branch is made.
Not done / known gaps¶
MathML across engines (screenshots, 2026-10-19). tests/test-ui-embed-screenshots.spec.js (opt-in: EMBED_SHOTS_DIR=<dir>) writes real-browser PNGs of the formula language, KernelF's math notation and a diagram in Chromium, Firefox and WebKit; the numeric mfrac/msqrt assertions cannot see layout bugs, the pictures did. Found and fixed: Firefox dropped the text of a statement a whole line below an inline <math> (the fraction/power sat above val ratio =; formula's print sat above its fraction) — the math box is measured as the text's own height and the line breaks around it. styles/editor.css keeps the math's container and the two levels above it on one line (span:has(> math), span:has(> span > math), span:has(> span > span > math) { white-space: nowrap }); the formula spec now asserts that print and the fraction overlap vertically (fails on Firefox without the rule). Chromium and WebKit were already right; the diagram looked the same in all three. The math font stack also lists STIXGeneral, Asana Math, Noto Sans Math, DejaVu Math TeX Gyre and the CSS math generic before plain serif. The cells notation (lang-cells) shows a <math> element as a nested CellBox tree: covered by an embed spec (edit the tag, source follows).
Diagram (Sprotty) in a host page (2026-10-19). Checked rather than assumed: (1) the diagram's HTML chrome (toolbar, wrappers) keeps its computed styles on the hostile host page in Chromium, Firefox and WebKit (tests/test-ui-embed-scope.spec.js, embed-host-demo.html?diagram=1; the SVG itself is outside the reset as documented above); (2) its wheel/pinch handling cannot touch the host — the wheel listener (non-passive) and the WebKit gesture* listeners sit on the diagram's own wrapper, and the wheel handler returns early unless Ctrl/Meta is held, so plain scrolling over a diagram still scrolls the host page. Not built, on purpose: preloading the Sprotty chunk at mount() — the renderer is lazy() in node-renderer-tokens.tsx and loads on the first diagram render, a language has no flag that says it uses diagrams (it would mean scanning concept editors), and the saving would be one chunk round trip.
Style isolation covers host tag-selector rules but not !important or class/id rules, nor SVG/MathML elements (see above). Project files, folders and persistence are not part of the embed (sibling models are passed in as text); the debugger and collaboration are out of scope by decision. Remaining singletons: defaultDocumentState fallbacks inside renderers, activeDocumentState() users, the preferences store, and the grammar registry (the language registry is per core, P1). *.lang.js project languages need the code-trust policy before the embed could load them.
The workbench API of an embed¶
EmbeddedEditor#workbench (src/embed/mount.tsx) is created on first use over embedAdapter(...) (src/workbench-api/context.ts): host kind "embed",
context = this mount's editor, language and live root. The debugger, collaboration, project, files, Git and the IDE's windows are out of scope by
decision (above) and report why through the capability map; tests/test-workbench-api-embed.mjs and the host contract test
(tests/test-workbench-api-contract.mjs) pin that. The handle's dispose() disposes the workbench.