npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@rasamjs/core

v0.3.2

Published

A typed SVG drawing library with shapes, templates, transforms and pointer interaction.

Readme

@rasamjs/core

A TypeScript SVG drawing library with typed geometry, per-drawing ownership, coalesced native writes and optional modules. There are no runtime dependencies. It is an ESM library, with deliberate differences from SVG.js 3.2.8.

Start with the generated public entry points and the action matrix of SVG.js equivalents. The release procedure describes reproducible acceptance checks; publishing remains separately authorized.

For class-defined SVG nodes with saved props, live state and undoable actions, see the opt-in @rasamjs/core/components guide.

Start

Install dependencies at the repository root, then run the remaining commands in this README from packages/rasam:

bun install --frozen-lockfile
cd packages/rasam
bun run build
bun run dev

Open http://127.0.0.1:5173/playground/ for the LED demonstration. It includes template updates, nested transforms, pointer capture, gradients, a marker, and a clip path. After building, you can also open playground/index.html directly in a browser. That route loads the standalone script in preview/playground.js; rebuild after changing the source. The Vite route loads TypeScript directly for live development. For the standalone rectangle example, run bun run build and open http://127.0.0.1:5173/examples/rect.html while the development server is running.

import { SVG } from '@rasamjs/core';

const drawing = SVG('#drawing', { width: 400, height: 240 });
const group = drawing.group().position(40, 30).rotate(10);
const rect = drawing.rect({ x: 10, y: 20, rx: 8 }).width(120).height(60);

rect.fill('#2563eb').stroke('#173e45', 2).opacity(0.9);
group.circle({ cx: 40, cy: 40, r: 20, fill: '#209889' });

rect.width(160);
rect.attr('height', 80);
drawing.flush();

SVG(container, options?) mounts a drawing into an HTML element or a selector matching an HTML container, and registers the built-in catalog for that drawing. Dimensions default to 300 × 150; numeric dimensions supply a matching viewBox unless you provide one. Pass an element to use a different document. A missing selector throws a descriptive error.

Dimensions can also be set through chainable methods:

const drawing = SVG('#drawing').width(1000).height(600);

String selectors default to the Svg return type for drawing chains. Specify a wrapper type for other elements, such as SVG<Rect>('#box'); passing a typed native SVG element infers its wrapper automatically. Native text and span elements infer SvgText | Tspan because their DOM interfaces are structurally identical; narrow with instanceof. Text factories stay concrete.

Passing an existing SVG element, or a selector matching one, wraps that element in place. Repeated calls reuse the same wrapper. Supported ancestors and descendants are adopted together so parent searches, events, and lifecycle methods share the owning drawing. Adoption preserves native element identity, sibling order, and existing attributes; it does not insert another <svg> or apply drawing defaults.

const native = document.querySelector<SVGRectElement>('#existing-box')!;
const box = SVG(native); // Inferred as Rect
box.fill('red');
SVG('#existing-box').attr('fill', 'blue');
const sameBox = SVG<Rect>('#existing-box'); // Explicit selector result type

Import Rect from @rasamjs/core for the typed selector example. Drawing options apply to HTML containers and <svg> references; passing them to a shape throws. For an existing <svg>, explicitly supplied dimensions change while an existing viewBox is preserved. If the viewBox is absent and both supplied dimensions are numeric, the same matching viewBox is generated as for an HTML container. Undefined options leave existing attributes untouched. Adoption without options preserves the original markup. Supported imports are described below.

Roots, groups, clip paths, markers, and other containers expose the same typed creation methods. Shape methods accept their options object and return the concrete wrapper, so geometry properties, chaining, and native element types stay precise.

| Method | Creates | | ---------------------------------------------------------------------- | ----------------------------------------- | | group(options?), defs(options?) | Containers with the same creation methods | | rect(options?), circle(options), ellipse(options) | Basic shapes | | line(options), polyline(options), polygon(options) | Lines and polygons | | path(options), text(options?), use(options?) | Paths, labels, and local references | | linearGradient(options?, stops?), radialGradient(options?, stops?) | Root-owned paint resources | | clipPath(options?), createMarker(options?) | Root-owned clipping and marker resources |

Use createMarker() to create a resource and shape.marker('end', resource) to attach it. Resource creation from a nested group still uses the owning root's defs.

The Svg constructor and create(Constructor, options) remain available for custom elements and selective registration. new Svg(container, options) includes the root rectangle helper; register additional constructors before using their factory methods. Each wrapper exposes its native SVG element as .el. Direct changes to managed native attributes or children are unsupported.

The main entry point exports drawing elements, templates, math, and the attr decorator. Low-level services, registries, DOM adapters, emitters, and mixins live under @rasamjs/core/advanced. Public base/text wrappers are named SvgNode and SvgText so they do not shadow browser globals. Use .el, destroy(), isDestroyed, bounds('root'), position(), and text(); the older aliases have been removed before publication.

import { SVG, SvgNode, SvgText } from '@rasamjs/core';
import { DomFactory, Registry } from '@rasamjs/core/advanced';

Find managed elements by ID, class, or any CSS selector:

const box = drawing.rect({ id: 'box', class: 'shape', width: 100, height: 60 });
SVG.find('#box'); // [box]
SVG.find('.shape'); // All matching Rasam wrappers in the current document
SVG.findFirst('#box')?.attr('fill', 'red');
drawing.findFirst('.shape'); // First matching descendant of this drawing
group.find('.shape'); // All matching descendants of this group

findFirst() returns undefined when nothing matches; find() returns an empty array. Document searches include managed SVG roots and ignore unmanaged elements. Pass a document as the second argument to SVG.find() or SVG.findFirst() to search another document. Container searches exclude the container itself, work while detached, and also accept a predicate: group.findFirst(node => node === box). CSS searches commit pending attribute updates before matching.

To adopt an unmanaged native child already inside a managed container, use group.adopt(nativeChild). This preserves its position among siblings; use group.add(wrapper) to append an already managed node.

All drawable shapes and containers expose chainable width() and height() methods, alongside fill() and stroke(). A new empty rectangle can be configured entirely through methods:

const box = drawing.rect().width(120).height(60).fill('teal').stroke('black', 2);
console.log(box.width(), box.height(), box.fill(), box.stroke());
drawing.width(800).height(480); // Changes the viewport; preserves the viewBox
drawing.circle({ r: 10 }).width(80).height(40).fill('teal');
drawing.polyline({ points: '10,5 30,5 30,15' }).width(80).height(40).stroke('black', 2);

Rectangles and SVG roots use native width/height attributes; markers use markerWidth/markerHeight. These accept numeric or contextual SVG lengths. Other shapes, groups, and clip paths use numeric user-unit dimensions, scaling each axis independently around the current local bounds' top-left corner. Resizing preserves the separate position, origin, rotation, component scale, and matrix-mode skew.

Dimension getters return the size after this sizing transform and before the user's placement transform. They return 0 for empty geometry and null when bounds are unavailable, such as unmeasurable text or unresolved references. Setters reject negative/nonfinite dimensions, unavailable bounds, and expanding a zero-extent axis. A nonempty shape collapsed through resizing to zero can be sized again later. Text sizing uses browser measurements and can vary by subpixel rounding.

For bounds-based sizing, underlying geometry (r, points, path data, and text) stays intact: bounds('local') describes that geometry; bounds('root') includes sizing and placement. resetTransform() resets both sizing and placement; assigning a new explicit matrix replaces them. Paint resources and gradient stops have no drawable extent to scale.

fill() and stroke() read the managed paint attribute on shapes and groups. Getters return a string or undefined; typed paint handles read back as url(#id). Pass a color, paint handle, or null to set or remove paint. stroke(paint, width?) also accepts a numeric width or SVG length string. These getters read logical attributes, including pending writes, and do not resolve inherited or computed CSS.

Runnable examples

Run bun run build and bun run dev, then open an example on the development server. Each phase example exercises its supported editing and lifecycle behavior.

| Topic | Page | Optional module | | ----------------------------------------------------------------- | ------------------------------ | -------------------------------------------------- | | Basic shapes and geometry edits | /examples/editing.html | Main catalog | | Tree movement and ordering | /examples/tree.html | @rasamjs/core/tree | | Keyboard, pointer and custom events | /examples/events.html | @rasamjs/core/events | | Nested viewports and zoom | /examples/viewport.html | @rasamjs/core/viewport | | Gradient, clip and marker editing | /examples/resources.html | @rasamjs/core/resources | | Images, symbols and links | /examples/media.html | @rasamjs/core/media | | Rich text and text paths | /examples/text.html | @rasamjs/core/text | | Masks and pattern paint | /examples/masks.html | @rasamjs/core/masks, @rasamjs/core/patterns | | Metadata, CSS, native islands and fragments | /examples/catalog.html | @rasamjs/core/catalog | | Clone and passive SVG round trips | /examples/interchange.html | @rasamjs/core/query, @rasamjs/core/interchange | | Timeline controls and morphs | /examples/animation.html | @rasamjs/core/animation | | Combined resources, text, interactions, animation and interchange | /examples/release-scene.html | Combined opt-in modules |

Architecture

src/
├── index.ts               public exports
├── math/                  Vec2, Matrix, BBox; no DOM
├── dom/                   namespace, creation, attributes, browser operations
├── services/              scheduler, registry, bounds, defs manager, context
├── core/                  Node, abstract Shape, mix helper
├── mixins/                Styleable, Transformable, Parent, Textual, guards
├── decorators/            @attr field decorator
├── elements/              SVG classes and explicit Elements registration
├── path/                  PathBuilder, parser, curve and arc geometry
├── geometry/              validated point lists and shape edits
├── events/                typed Emitter, pointer routing and native/custom events
├── tree/                  traversal and structural operations
├── resources/             reference classification and consumer operations
├── media/, text/, catalog/ optional wrapper integration and policy
├── interchange/           managed snapshots, clone, passive import/export
├── animation/             timelines, runners, interpolation and clocks
├── template/              SVG tag, binding parts, Renderer
└── types/                 shared contracts

Shape combines Node, Transformable, and Styleable through mix(). Group also includes Parent and Creatable; SvgText uses a managed mixed-text parent capability. The plain Textual mixin remains available for advanced extensions. Guards such as isParent, isTransformable, and isTextual narrow capabilities.

The root creates one DrawingContext. Every descendant receives that same context and its Scheduler, Registry, BoundsService, and DefsManager. DOM operations are confined to dom/. Importing the library never accesses a global document.

Decorate regular instance fields with @attr(); no accessor keyword is needed:

import { attr, Circle } from '@rasamjs/core';
import type { Length } from '@rasamjs/core';

class StyledCircle extends Circle {
  @attr('stroke-width') lineWidth: Length = 1;
}

const circle = new StyledCircle(drawing.context, { r: 10 });
circle.lineWidth = 2; // Updates the managed stroke-width attribute

Built-in shape fields and the attribute API use that same state:

rect.x = 20; // Updates logical state and invalidates bounds
rect.width(200); // Uses the same managed attribute state
rect.attr('width', 220); // Uses the same path

@attr() also works with an accessor declaration, as in @attr() accessor cx: Length = 0, which keeps the getter and setter on the prototype. Built-in shapes go one step further with an internal class decorator, @attrs({ cx: 0, cy: 0, r: 0 }) plus declare cx: Length fields, so creating an instance runs no per-field storage or initializers. @attr() infers the SVG attribute name from the field or accessor, normalizing camel case; @attr('name') supplies an explicit alias. Defaults apply to new elements without replacing constructor options or adding missing attributes to adopted elements. Attribute changes invalidate bounds automatically. Custom classes list their supported attribute names in static attributeNames so adoption and templates can validate before mounting. Custom @attr() fields are non-configurable: redeclaring one as a subclass field throws instead of silently breaking its binding. Built-in shape fields use prototype accessors to keep shape construction cheap. Assign to the inherited field in a subclass constructor after super() to customize its value; do not redeclare a built-in field as a JavaScript class field.

Scheduling

Attribute and text state changes immediately. Native writes are coalesced until the next animation frame. The scheduler compares serialized values with the last committed values, so unchanged attributes are skipped. Camel case attribute names are normalized to kebab case; SVG names such as viewBox remain case sensitive.

drawing.batch(() => {
  rect.fill('red');
  rect.fill('blue');
  rect.width(300);
  console.log(rect.width()); // 300, even before the DOM commit
});
drawing.flush(); // Commits blue and width=300 immediately

Nested batches schedule at the outermost boundary. A thrown callback leaves its applied changes scheduled; batches are not transactions. Browser measurements, screen coordinate conversions, and CSS-selector find() calls flush first. Destroying a node cancels its queued writes. Batches accept synchronous callbacks. A failing commit does not prevent other queued writes from committing. The failed write remains pending. Explicit flush() rethrows the original error after the pass. Animation-frame failures are reported through console.error and retried once on the next frame without needing another edit. A second failure remains pending for explicit retry or a later update; persistent failures never spin in an automatic retry loop.

Shapes and coordinates

The catalog includes Svg, Group, Defs, Rect, Circle, Ellipse, Line, Polyline, Polygon, Path, SvgText, and Use. LinearGradient, RadialGradient, Stop, Marker, and ClipPath provide local resources.

import { Matrix, PathBuilder, Vec2 } from '@rasamjs/core';

group.position(100, 50).origin(20, 20).rotate(30).scale(2);
const worldPoint = rect.toRoot(new Vec2(10, 10));
const localPoint = rect.fromClient({ x: 120, y: 80 }); // Vec2 | null

rect.matrix(new Matrix(1, 0.2, 0, 1, 0, 0));
rect.resetTransform().position(20, 30); // Explicit reset before component setters

drawing.path({
  d: new PathBuilder().moveTo(0, 0).cubicTo(20, 60, 80, 60, 100, 0),
  fill: 'none',
  stroke: '#209889',
});

Matrices use column vectors and parent × local composition. Component transforms are T(position) × T(origin) × R(rotation) × S(scale) × T(-origin). Geometry x/y is separate from transform position. position(x, y) sets it; translate adds to it. Until origin(x, y) is called, rotate() and scale() set the origin to the center of the current geometry bounds, so a shape turns in place whether it was placed by x/y, translate, move or a parent group. The center is measured at each rotate() or scale() call. When geometry was edited since the last call, for example by size(), position absorbs the pivot move, so the shape stays where it is drawn and only the new rotation or scale applies; position() then reports the adjusted value. Empty or unavailable bounds keep the previous origin, initially (0, 0). resetTransform() restores the automatic center. Angles are in degrees. Matrix mode preserves general affine transforms without silently dropping skew. Singular or detached screen conversions return null. position() remains readable in matrix mode and reports the matrix translation; component setters still require an explicit reset.

rotation() reads the exact stored angle, including turns beyond 360 degrees. scale() reads an immutable Vec2, retaining negative and zero scales. origin() reads the explicitly set origin, or null while the center is automatic. These getters do not write attributes, recenter the pivot or emit events; they throw in matrix mode. geometryMatrix() publicly reads the immutable sizing matrix, separately from the user transform, including in matrix mode.

matrix.decompose() returns immutable { x, y, rotation, shear, scaleX, scaleY }. Recompose with T(x,y) × R(rotation) × [scaleX shear; 0 scaleY]. Rotation is in degrees, scaleX is nonnegative, and reflection is retained in scaleY. shear is the upper-right matrix coefficient, not a skew angle. Singular matrices are supported, including a collapsed first axis.

Save and restore an edit with a JSON-compatible TransformState:

const before = shape.transformState();
shape.size(80, 40).rotate(30).bakeSizing();
shape.transformState(before);

The immutable snapshot contains component or matrix mode, position, rotation, scale, the cached pivot and automatic-origin flag, sizing, original transform syntax, and typed editable geometry attributes, including viewport settings and marker dimensions/reference points. Restoration validates the state before writing and restores absent attributes too. It preserves component mode for later rotate() calls, and matrix mode for imported transforms. Restore on the same SVG element kind in the same parent coordinate system. Paint, application attributes, text content, children and parent relationships are not part of this snapshot.

bakeSizing() writes supported sizing into ellipse cx/cy/rx/ry, uniformly sized circle cx/cy/r, line endpoints, polygon/polyline points, or path commands, then clears the sizing matrix. Geometric root bounds stay in place. Native width/height sizing is already geometry. Non-uniform circles, text, groups and unsupported ellipse mappings keep their sizing transform. Identity sizing is a no-op. Baking removes sizing's effect on stroke width; use vector-effect: non-scaling-stroke during editing when a constant stroke width is required.

PathArray.transform(matrixOrTuple) creates an immutable transformed path, mapping line and Bézier points and preserving elliptical arcs under affine maps. Reflections reverse the arc sweep; degenerate arcs become lines. Outside geometry edits, including snapshot restoration, need an explicit transformer update() while the optional geometrychange event remains deferred.

Shapes with native width/height attributes resize those attributes. Circles, paths, text, groups, and other geometry without native dimensions resize through a transform that preserves the local bounding-box anchor. These transforms also scale strokes; non-uniform dimensions can distort them. Set shape.attr('vector-effect', 'non-scaling-stroke') to keep the stroke width constant under transforms. For groups, set this on each stroked descendant; vector-effect is not inherited. Geometric bounds still exclude stroke.

bounds() returns local geometric bounds; bounds('root') returns root user-space bounds. Results distinguish exact, conservative, empty, and unavailable. Basic numeric geometry and supported path extrema are exact to floating point precision. Transformed boxes and unions are conservative. Bounds exclude stroke, markers, filters, and clipping. Percentages and contextual lengths have unavailable headless bounds. External CSS overriding geometry is unsupported.

contains(point) tests local geometry; hitTest(point) converts a root user-space point first. Rounded rectangles, circles, ellipses, and polygon fills have geometric tests. Lines have no fill interior and return false for resolved geometry. Text uses its measured box. Path fill tests use the native browser adapter and may be unavailable headlessly. These are not painted-stroke tests.

Paths support absolute and relative M L H V C S Q T A Z, repeated commands, scientific notation, Bézier extrema, and rotated elliptical arcs. Invalid data returns unavailable bounds. The parser deliberately supports this path grammar, not arbitrary SVG documents.

SVG() supplies browser text measurement automatically. Detached or unmeasurable text returns unavailable bounds. You can supply measureText in its options for a custom provider; the lower-level Svg constructor requires an explicit provider.

import { SVG } from '@rasamjs/core';

const drawing = SVG(document.body, {
  width: 400,
  height: 240,
});
drawing.text({ x: 20, y: 40, text: 'Hello' }).anchor('middle');

Templates and registration

import { Renderer, svg } from '@rasamjs/core';

const led = (on: boolean) => svg`
  <g>
    <circle cx="20" cy="20" r="10" fill="${on ? 'lime' : 'gray'}"/>
    <text x="40" y="25">${on ? 'On' : 'Off'}</text>
  </g>`;

const renderer = new Renderer(group);
const instance = renderer.render(led(false));
renderer.render(led(true)); // Keeps wrappers, element nodes, and text node identity
instance.destroy();

Renderer.render(parent, template) is also available. Each instance owns a host group and its mounted nodes. A different template literal identity replaces the prior instance. Compilation is cached by literal identity.

A hole between elements, or at the top level, renders nested templates. It takes a template, an array or other iterable of templates (nested arrays flatten), or null, undefined, a boolean or '' for nothing, so it can draw lists and conditions:

const chip = (pins: number[], on: boolean) => svg`
  <g>
    <rect width="40" height="60"/>
    ${pins.map((y) => svg`<line x1="0" y1="${y}" x2="-10" y2="${y}"/>`)}
    ${on ? svg`<circle cx="20" cy="30" r="6" fill="lime"/>` : null}
  </g>`;

On update, an item whose template literal matches the one at the same index updates in place; other items are rebuilt. An update validates every binding and builds new items off the drawing first, so a failed update changes nothing. Nested items follow their container's child rules, such as only stop inside a gradient. Removed items and replaced templates are disposed so that undo restores them without clearing history.

Static markup is trusted application code. Dynamic primitives become text or attribute values, never markup. Whole quoted attribute holes remove the attribute for null/undefined; mixed attributes and text use empty segments. Tag names and attribute names are static. Text holes belong inside text elements and take only primitives. Dynamic on* bindings, dynamic CSS strings, and external URL references are rejected. Dynamic URLs are restricted to local #id and url(#id) references.

Templates initialize shapes from their bindings and keep declared resources inside their template-owned containers. Resource IDs may be declared in markup and remain immutable after initialization.

A custom class can share a tag with a built-in class. A Group subclass with static variant = { attribute: 'data-type', value: 'led' } registers for <g data-type="led"> only. Creation writes that attribute, it can't change, and other classes can't use its value. Once the class is registered in a drawing, adoption, import, clone and undo/redo rebuild it instead of a plain group; registry.resolve(element) returns the class an element would get. static ownsChildren = true reserves a container's children for its class: outside builders, add(), moves, reordering, removal and templates throw before changing anything. The class edits them inside this.withOwnChildren(callback), and adoption, clone, undo/redo and destroying the owner keep working.

Registration is local to each drawing. SVG() registers the full built-in catalog; create(Constructor, options) registers a custom constructor as it creates the node. With the lower-level Svg constructor, Elements.register(registry) can register the full catalog explicitly. registry.adopt(nativeElement, parent?) snapshots supported state, preserves wrapper identity, and accepts SVG transform lists: matrix, translate, scale, rotate (including a center), skewX, and skewY. Lists compose into matrices for bounds and coordinates while the original DOM attribute is preserved. Children are linked in one pass in their native order. Namespace declarations, version, and unknown attributes stay in the DOM as unmanaged pass-through; they are not available through the managed attribute API. New attribute writes and templates still use the declared schema. Descriptive title, desc, and metadata subtrees stay untouched and receive no wrappers. Unsupported tags, including style and filter, cause adoption of the entire tree to fail before claiming wrappers; they are not skipped. Cross-root adoption also throws. Nested SVG roots share the outer drawing context. Adoption does not synchronize later external edits and is not a general SVG importer. For explicit catalog setup with the lower-level constructor, import Elements from @rasamjs/core/advanced. Root and nested factories resolve the same registered class.

Resources and lifecycle

const paint = drawing.linearGradient().stop(0, 'red').stop(1, 'blue');
rect.fill(paint).stroke(paint, 2);
console.log(drawing.context.defs.referenceCount(paint)); // 2

const copy = drawing.use({ x: 150 }).href(rect);
rect.remove(); // Reusable; ownership and handlers remain
group.add(rect); // Reparent within the same drawing
copy.destroy();
rect.fill('black').stroke(null);
paint.destroy();
drawing.destroy(); // Also destroys detached owned nodes and resources

Resource constructors mount under root-owned defs. IDs avoid document collisions and reservations made by other drawings. Typed references are counted per consumer attribute, updated on reassignment, and released during destruction. Destruction is rejected while consumers outside the destroyed subtree still reference a node. Zero references do not remove a resource automatically. Raw reference strings are untracked. Cross-root moves are unsupported. Gradients are stop-only containers; they do not expose drawing, styling, or placement methods. Clips and markers keep their drawing-container capabilities. Destroying a wrapper releases its element's identity reservation, so the native element can be adopted by a new wrapper.

Pointer events

const off = rect.on('pointerdown', (event) => {
  rect.capturePointer(event.pointerId);
  console.log(event.target, event.currentTarget);
});
rect.on('pointerup', (event) => rect.releasePointer(event.pointerId));
off();

Pointer events are delegated through one native root listener per subscribed type. The managed ancestry is captured at dispatch start. The event exposes stopPropagation, stopImmediatePropagation, preventDefault, and originalEvent. Supported types are down/move/up/over/out/cancel and got/lost pointer capture. Subscriptions survive remove() and are cleared by destroy(). Set style({ touchAction: 'none' }) deliberately for gesture tools; it is not a global default. Listener installation follows per-type subscription counts and indexed captures. Adding nodes and routing pointer moves do not scan the drawing's node registry.

Support and limitations

Validation records exact versions in reports/svgjs-parity-current.json: current Chromium, Firefox and WebKit engines, Node 24.21.0 and TypeScript 7.0.2 on the recorded Windows machine. These are tested versions, not inferred minimum-version promises. Output targets ES2022 and standard decorators are compiled before packing. Module import works without a document; creation and native measurements need the appropriate owner document/browser APIs.

  • Bounds describe fill geometry, excluding strokes, markers, filters, clipping, masks and alpha. Transformed boxes are conservative. Unsupported contextual lengths, unknown generic elements and unmeasurable text report unavailable bounds. Raw Use href strings do not acquire owned geometry references.
  • Trusted native adoption preserves supported markup and identity; it is not a sanitizer or an external-DOM synchronizer. Register optional catalogs first. ForeignObject descendants remain native DOM islands; SVG(inner) can manage an inline SVG inside their HTML as an independent drawing. Managed import is a separate bounded passive-SVG language; CSS stylesheets, HTML/foreign content and active markup are outside that import contract. Export does not sanitize trusted markup.
  • Templates have static structure and primitive bindings. Dynamic tag names, arbitrary markup/child-list injection, hydration and reactive state are outside that contract. URL bindings follow the element-specific rules in the guide.
  • Same-drawing managed cloning is supported with fresh IDs and explicit shared or copied resources. Cross-drawing moves/cloning are rejected; passive export/import is the reconstruction boundary. Listeners, capture and runners are not copied.
  • Typed references must be released before destroying a referenced target; unused resources remain until explicitly destroyed. Raw reference strings are untracked.
  • Animation is opt-in, respects reduced motion by default and supports only its documented interpolation units/colors/topologies. It is not a general SVG.js plugin morphing or painted-frame guarantee.
  • Editor tools, automatic resource garbage collection, painted-stroke hit tests, filters and application-specific data models are outside this release.
  • WebKit ignores transforms on nested SVG in the documented P5 case; that one conformance test is explicitly skipped. ForeignObject native getBBox origins also differ, while managed/client coordinate checks pass in all three engines.

Verification

bun run release:check runs the complete acceptance pipeline and records source consistency, individual results and candidate readiness. release:assess does not run validation. Review public API changes with api:check before api:update.

bun run typecheck
bun run test
bun run build
npx playwright install chromium firefox webkit
bun run test:browser
bun run check:consumer
bun run check:size
bun run bench
bun run bench:changes
bun run bench:create
bun run bench:adopt
bun run bench:svgjs
bun run bench:svgjs -- --browser=all
bun run bench:svgjs -- --browser=chromium --gc --output=reports/svgjs-comparison-gc
node scripts/profile-svgjs-creation.mjs
bun run format:check

The packed consumer fixture verifies declarations, public runtime exports, typed usage, and importing without a DOM. The selective Svg rectangle bundle must remain below 20 KiB gzip (raised from 15 KiB in P5 for nested viewport mappings and to 20 KiB on 2026-10-26 after the final review fixes) and exclude templates and unrelated shapes. SVG() intentionally includes the full element catalog for its ready-to-use factories. The benchmark measures 1,000 existing circles over 100 warmed batches, including synchronous flush() commits and excluding paint. Machine, browser, median, p95, and samples are recorded in reports/benchmark.json; bundle composition is in reports/size.json. bench:changes compares grouped edits and history replay against commit c21aee1 in alternating before/after order in Chromium, using minified bundles, three warm-ups and 30 samples at 100, 500 and 1,000 targets. It validates cancellation, undo and redo outside each timer and writes samples and source/bundle fingerprints to reports/change-groups-benchmark.json. Set RASAM_CHANGES_BASELINE to compare against a different commit. Setup, teardown and paint are excluded. The pre-parity release-preparation run measured 13,257 bytes gzip (12.95 KiB) against the 15 KiB budget. P0–P2 measurements are retained in the current reports; the pre-change snapshot is in reports/svgjs-parity-baseline.json. Fill updates retain the 16 ms median target. These timings exclude paint and describe the recorded Windows / Intel Core i7-10610U / Chromium environment, not full-frame time. The creation benchmark records 2,000/8,000-node creation and 1,000 pointer moves, using five happy-dom samples per size. It rejects growth above 8× for 4× as many nodes; results and environment are saved in reports/creation.json. The adoption benchmark wraps 1,000/2,000/4,000 existing rects in a group, excluding DOM construction and destruction. Five samples per size and the 4× growth check are recorded in reports/adoption.json. Unit coverage also bounds tree visits directly so an accidental sibling scan fails independently of timing noise.

bench:svgjs compares Rasam with the development-only, pinned SVG.js dependency in headless Chromium. Pass --browser=all to include Firefox and WebKit. Both libraries run identical committed circle geometry, single/repeated fill updates, and synthetic pointer events. Rasam's final flush is included in timed work; validation, setup, teardown, and paint are excluded. Each workload uses a fresh page, and warmed samples alternate library order. Pass --gc for a Chromium diagnostic run that collects garbage before each sample, and --output=path to keep its report separate. The creation profiler prints Chromium CPU samples for 8,000 circles. Medians, p95, raw samples, exact versions, and methodology are saved in reports/svgjs-comparison.json and reports/svgjs-comparison.md. These are operation benchmarks on the recorded machine, not end-to-end rendering or animation FPS. Short workloads are timed in blocks and normalized per operation to reduce timer quantization. The report flags non-monotonic creation results rather than treating them as reliable scaling evidence. Repeated runs are required before drawing conclusions from small timing differences.

Paint-only attribute updates preserve geometric bounds caches. Geometry edits invalidate the affected node, ancestors, and typed use-reference consumers; structural edits reset the drawing's caches. Text and use-dependent ancestors stay uncached because measurements and references can change outside numeric geometry.

The Vite config lowers standard decorators with the existing esbuild development dependency. Published output is compiled by TypeScript and requires no decorator transform or runtime dependencies in consumer applications.

Model changes and automatic history

@rasamjs/history records edits to a drawing, including attributes, complete transform state, content, typed resources, and tree placement. Compound setters form one operation. Transformer gestures use neutral core groups and temporary preview metadata. Core has no undo stack or merge policy.

import { observeChanges, withChanges } from '@rasamjs/core/changes';

const unsubscribe = observeChanges(drawing, (event) => {
  if (event.type === 'change') console.log(event.changes);
});
withChanges(drawing, { source: 'application' }, () => rectangle.size(100, 50));

Node-local attributechange reports normalized { node, attribute, previous, value } at logical mutation time; removal uses undefined. Drawing-wide observation also covers future nodes and semantic state changes that leave SVG attributes unchanged. Scheduled DOM flushes do not create additional model edits. Replay batches carry source: 'replay' and replacement mappings for recreated disposed wrappers. Replay restores placements without firing node remove events; use the settled replay batch for structural notifications. A sole rejected-write conflict is thrown as ChangeConflictError. Multiple observer failures use ChangeObserverError.errors, which can also contain that conflict. ChangeRollbackError means restoration and its recovery both failed, so the current drawing needs a new history baseline.

Custom private model state can implement the exported captureModelState, validateModelState, and restoreModelState symbol hooks. Return immutable data under custom, delegate other domains to super, and use withChanges(this, {}, callback) around its setters so capture occurs before private writes. Validation must be pure. Captured values must describe model data rather than callbacks or external objects. Registration and constructor identity are required for reconstruction.

Explicit destroy() on an observed shape is permanent disposal and clears the entire attached history. Use remove() for deletable shapes and reversible deletion. Semantic replacement can reconstruct disposed model objects with new wrapper identities; external subscriptions and application state are not revived. See the history package for transactions, limits, conflict handling, and the precise supported-state contract.

Neutral groups can carry an undo label without importing history:

import { beginChangeGroup } from '@rasamjs/core/changes';

const edit = beginChangeGroup(drawing, { label: 'Add text' });
edit.run(() => drawing.text({ text: 'Draft' }));
edit.cancel(); // Restores only this group's edits, then ends it.

cancel() records and restores the group's non-temporary changes even when no history is attached. Observers receive the restoration, followed by groupend with cancelled and restored set to true. Finish the synchronous run() callback before cancelling. Repeated end() or cancel() calls after completion do nothing. A conflicting external edit leaves the group open and the model unchanged by the rejected cancellation, so the application can resolve the conflict and retry. Permanent destroy() invalidates active groups; further run() and cancel() calls throw ChangeConflictError. Close an invalidated group with end(). Use remove() for reversible work. Notification failures are reported after a successful restore and completion; multiple failures are retained in an AggregateError. end(true) alone still performs no rollback.

Derived model changes

deriveChanges(drawing, callback) from @rasamjs/core/changes registers a synchronous dependent edit before an operation's final snapshot. Its event contains changed nodes and current source/group/label/temporary metadata. Callback writes join the same operation and group, so one undo step can contain a shape and attached connectors. Getter-only calls, no-op writes and restoration do not invoke derivations. Callbacks run once in registration order and must not start another attribution scope/group. The returned unsubscribe removes the callback; context destruction clears it. Caller transactions own failure rollback.

Core reserves data-rasam-connector-start and data-rasam-connector-end as typed local href references so endpoints follow ID remapping through cloning and SVG import/export.

Document framing and import

import { exportSvg, importSvg } from '@rasamjs/core/interchange';

const svg = exportSvg(drawing, { frame: 'content', padding: 16 });
const nodes = importSvg(drawing, svg, { document: true });

Content framing sets the exported document's viewBox, width and height from geometric bounds in root coordinates. Padding defaults to zero and must be finite and nonnegative. It excludes stroke and marker extents, and throws when content bounds are unavailable. An empty drawing uses its numeric document dimensions, with 800 by 600 as the fallback for unresolved dimensions. Export does not change the live drawing or camera. Framing requires document output; the default export continues to preserve existing dimensions. Framing a nested shape carries its omitted ancestors' transforms into the export; framing a nested SVG preserves its own viewport inside the exported document. Nested viewport percentages retain their original bases when the outer frame changes. Use BBox.union(nodes.map(node => node.bounds('root'))) to union several root-space bounds.

document: true imports the children of a single outer SVG, preserving the destination's camera and dimensions and discarding root presentation. Use document: 'presentation' to retain root paint, text styles, opacity, transforms and references in a scoped <g>. This mode omits the root viewport attributes (x, y, width, height, viewBox, preserveAspectRatio) and does not add a group for an envelope with no remaining attributes. Existing destination content keeps its presentation; repeated exports and imports do not add redundant groups. Both document modes validate the complete passive envelope before discarding attributes. They also accept fragments and a full document's prolog: an XML declaration, comments and a DOCTYPE without an internal subset, such as the public SVG 1.1 DOCTYPE that drawing applications write. Internal subsets, entities and later processing instructions are still rejected. Malformed XML throws SyntaxError containing the parser's first error line. Existing passive-content, namespace, resource and URL validation still applies. Without the option, importing an SVG creates a nested viewport as before.

document: 'replace' requires an empty owning drawing. For a full SVG document it also clears configured root presentation (retaining root ID/class and viewport settings), so the incoming document owns its paint, styles and compositing. This prevents configured root opacity from applying again to restored content. Fragments retain root defaults.

Embedded PNG, JPEG, GIF, WebP, AVIF and SVG data URLs are accepted by importSvg() on <image> elements, allowing exported images to be restored. Other data-URL positions and MIME types remain unsupported. Absolute HTTP(S) images, links and Use URLs still require externalUrls: 'http'. Register the media catalog before importing images.

Release status and license

@rasamjs/[email protected] is published, licensed under MIT. The name is not reserved by these checks. Recheck the intended registry at the time of a separately authorized publication. The package remains private: true until publication is separately authorized.

See CHANGELOG.md and the public API review. release:check verifies CI wiring for the configured GitHub remote, hdevlop/rasam. The CI workflow runs the full gate on pushes to main and pull requests once committed and pushed. See RELEASING.md.

Raster image export

The optional @rasamjs/core/raster entry exports exportImage(root, options): Promise<Blob> and RasterOptions. Importing needs no DOM; rendering needs a browser.

import { exportImage } from '@rasamjs/core/raster';
const png = await exportImage(drawing, {
  type: 'image/png',
  scale: 2,
  frame: 'content',
  padding: 16,
});

PNG is the default; image/jpeg and image/webp request the browser's native encoder. Unsupported encoders reject clearly instead of returning a different format. frame: 'content' (default) uses geometric content bounds in drawing units, independently of the camera, with zero padding by default. frame: 'viewBox' uses the current document view and ignores padding. Positive finite scale rounds output dimensions up to pixels. No export changes the source model or camera; snapshots are taken before asynchronous resource loading. Add padding for strokes, markers and filters, which can extend beyond geometric bounds.

background accepts a CSS color. PNG/WebP default to transparent; JPEG defaults to white. Zero-size content needs positive padding. Output is limited to 32,767 pixels per axis and 16,777,216 total pixels; reduce scale for larger documents.

Images must be data URLs or direct same-origin HTTP(S) resources. Resources are fetched, validated and embedded, including images inside nested SVG image files. Redirects, other protocols, cross-origin resources, corrupt images and cyclic or overly nested resources reject. Tainted canvases produce a clear error; temporary object URLs are released on success and failure.

Web fonts are not embedded. External stylesheets, computed page styles and external SVG/CSS references are not embedded either. Rendering uses authored SVG attributes and browser SVG-as-image rules; fallback fonts can differ from the live editor. See SVG processing modes and canvas encoding rules.