@vielzeug/codex 26.11.21 → 26.11.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +280 -51
- package/data/llms-full.txt +2380 -30
- package/data/llms.txt +7 -2
- package/data/manifest.json +1 -1
- package/data/packages/atlas.json +70 -0
- package/data/packages/beacon.json +1 -1
- package/data/packages/codex.json +1 -1
- package/data/packages/dnd.json +2 -2
- package/data/packages/gesture.json +27 -5
- package/data/packages/ink.json +32 -0
- package/data/packages/palette.json +42 -0
- package/data/packages/prism.json +1 -1
- package/data/packages/stage.json +25 -0
- package/data/packages/wire.json +36 -0
- package/data/refine.json +94 -7
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +25 -18
package/data/llms.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Vielzeug
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> 52 focused TypeScript packages. Version: 26.11.22
|
|
4
4
|
|
|
5
5
|
Install any package independently: `pnpm add @vielzeug/<name>`
|
|
6
6
|
|
|
@@ -9,6 +9,7 @@ Install any package independently: `pnpm add @vielzeug/<name>`
|
|
|
9
9
|
- [@vielzeug/archive](/archive/): Community content publishing for Cloudflare Workers + D1: a hardened Worker core over per-collection payload schemas
|
|
10
10
|
- [@vielzeug/arsenal](/arsenal/): Tree-shakeable TypeScript utilities with focused category entry points for arrays, async work, caching, objects, strings, math, and guards.
|
|
11
11
|
- [@vielzeug/assay](/assay/): Scoped DOM queries, exact event dispatch, and cancellable async waiting for browser tests.
|
|
12
|
+
- [@vielzeug/atlas](/atlas/): Camera transforms, matrix and rect math, polygon hit-testing, and a dynamic R-tree spatial index for infinite 2D canvases.
|
|
12
13
|
- [@vielzeug/bard](/bard/): Lifecycle-owned Web Audio mixing: buses with ducking, buffered SFX and sprites, procedural synth, streamed tracks, and crossfading music decks
|
|
13
14
|
- [@vielzeug/beacon](/beacon/): Guided onboarding and contextual product tours for web applications
|
|
14
15
|
- [@vielzeug/clockwork](/clockwork/): Framework-neutral typed state machines with pure transitions, actor-owned runtime work, timers, invokes, and explicit effects.
|
|
@@ -21,9 +22,10 @@ Install any package independently: `pnpm add @vielzeug/<name>`
|
|
|
21
22
|
- [@vielzeug/flux](/flux/): Reusable push streams with subscription-owned cancellation, bounded buffering, channels, and dependency-free structural bridges.
|
|
22
23
|
- [@vielzeug/focus](/focus/): Framework-neutral list navigation and focus restoration primitives.
|
|
23
24
|
- [@vielzeug/forge](/forge/): Framework-neutral form and field state with nested handles, flat validation issues, and explicit integration helpers.
|
|
24
|
-
- [@vielzeug/gesture](/gesture/): Framework-neutral
|
|
25
|
+
- [@vielzeug/gesture](/gesture/): Framework-neutral pointer drag, pan, pinch, and wheel recognition with lifecycle-owned handles.
|
|
25
26
|
- [@vielzeug/herald](/herald/): Typed synchronous event delivery with wildcard subscriptions, one-shot waits, tracing, and AbortSignal lifecycle.
|
|
26
27
|
- [@vielzeug/illusionist](/illusionist/): Typed, deterministic, locale-aware fake data generator with a seeded PRNG, eight data categories, and zero external runtime dependencies.
|
|
28
|
+
- [@vielzeug/ink](/ink/): Deterministic causal stroke stabilization, Catmull-Rom smoothing, speed and pressure width profiling, outline polygons, RDP simplification, and SVG path output.
|
|
27
29
|
- [@vielzeug/keymap](/keymap/): Target-local keyboard shortcut manager with chords, event-aware guards, modifier aliases, and terminal disposal.
|
|
28
30
|
- [@vielzeug/ledger](/ledger/): Serialized reversible command history with cancellation ownership and atomic reactive snapshots.
|
|
29
31
|
- [@vielzeug/lingua](/lingua/): Framework-neutral locale catalogs, typed translations, and explicit plural messages.
|
|
@@ -31,6 +33,7 @@ Install any package independently: `pnpm add @vielzeug/<name>`
|
|
|
31
33
|
- [@vielzeug/necromancer](/necromancer/): Lifecycle-owned Web Animations API primitives for native playback, groups, and additive FLIP transitions.
|
|
32
34
|
- [@vielzeug/orbit](/orbit/): Floating positioning with lifecycle-owned geometry and middleware.
|
|
33
35
|
- [@vielzeug/ore](/ore/): Functional custom-element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.
|
|
36
|
+
- [@vielzeug/palette](/palette/): Color parsing, conversion, mixing, and contrast for design tools
|
|
34
37
|
- [@vielzeug/patchwork](/patchwork/): RFC 6902 JSON Patch: structural diff, immutable apply, and guarded tryApply for sync protocols.
|
|
35
38
|
- [@vielzeug/postmaster](/postmaster/): Typed durable job outbox with leased processing, retries, and dead-letter recovery for browser applications.
|
|
36
39
|
- [@vielzeug/prism](/prism/): Responsive SVG charts with explicit updates: line, bar, area, scatter, pie, radar, heatmap, sparkline
|
|
@@ -46,6 +49,7 @@ Install any package independently: `pnpm add @vielzeug/<name>`
|
|
|
46
49
|
- [@vielzeug/sigil](/sigil/): QR code generation and scanning: pure matrix encoder, SVG and canvas renderers, native BarcodeDetector scanning
|
|
47
50
|
- [@vielzeug/sourcerer](/sourcerer/): Framework-agnostic collection pagination and observable single-value resources.
|
|
48
51
|
- [@vielzeug/spell](/spell/): Zero-dependency schema validation with explicit async checks, Standard Schema interoperability, and JSON Schema export.
|
|
52
|
+
- [@vielzeug/stage](/stage/): Retained-mode 2D canvas stage engine with DPR-aware layers, dirty repaints, and PNG export
|
|
49
53
|
- [@vielzeug/tabula](/tabula/): Typed CSV and TSV: RFC 4180 parser with schema-validated rows, streaming reader, and safe serializer.
|
|
50
54
|
- [@vielzeug/tandem](/tandem/): Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes for browser applications.
|
|
51
55
|
- [@vielzeug/tavern](/tavern/): Table sessions over mesh: host-owned state replication with guest command forwarding
|
|
@@ -53,3 +57,4 @@ Install any package independently: `pnpm add @vielzeug/<name>`
|
|
|
53
57
|
- [@vielzeug/vault](/vault/): Typed browser storage and opt-in driver-neutral SQLite with portable keys, TTL, observation, and transactions.
|
|
54
58
|
- [@vielzeug/ward](/ward/): Zero-dependency authorization decisions with ordered rules, role helpers, ownership predicates, and default deny.
|
|
55
59
|
- [@vielzeug/wayfinder](/wayfinder/): Framework-agnostic client-side router with typed params, async data loading, middleware, leave guards, and cancellation.
|
|
60
|
+
- [@vielzeug/wire](/wire/): Deterministic bezier and orthogonal edge routing over obstacles, plus topological ordering and cycle detection for node graphs.
|
package/data/manifest.json
CHANGED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiSource": "// Public root surface of @vielzeug/atlas. Every public export goes through this file.\n\nexport {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';\nexport { AtlasConfigError, AtlasError } from './errors.js';\nexport { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';\nexport { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';\nexport {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';\nexport type { Matrix, Point, Rect, Size } from './shapes.js';\nexport {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';\nexport {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';\n",
|
|
3
|
+
"docs": {
|
|
4
|
+
"index": "---\ntitle: 'Atlas: Spatial Math for 2D Canvases'\ndescription: Camera transforms, matrix and rect math, polygon hit-testing, and a dynamic R-tree spatial index for infinite 2D canvases.\npackage: atlas\ncategory: utilities\nkeywords:\n [\n camera,\n viewport,\n zoom,\n pan,\n matrix,\n rect,\n aabb,\n hit-testing,\n r-tree,\n spatial-index,\n culling,\n marquee,\n geometry,\n canvas,\n ]\nexports: [createCamera, createSpatialIndex, multiply, invert, rectsIntersect, pointInPolygon, snapRect]\nrelated: [gesture, ink, wire]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"atlas\" />\n\n## Why Atlas?\n\nEvery infinite canvas re-implements the same three things badly: a camera that keeps the point under your cursor fixed while zooming, a hit-test that stops being O(n) once the scene grows, and selection and snapping math for moving rects. Atlas ships them as pure, headless primitives: a viewport-centred camera with anchor-preserving transforms and injectable animation scheduling, matrix/rect math, exact polygon narrow-phase, and a dynamic R-tree for O(log n) queries.\n\n```ts\n// Before\n// Hand-rolled transform stacks, linear scans on every pointermove, and\n// selection boxes that drift while zooming.\n\n// After\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\nconst camera = createCamera();\ncamera.zoomAt({ x: 400, y: 300 }, 1.2); // world point under (400,300) stays put\n\nconst index = createSpatialIndex();\nindex.set('shape-1', { height: 40, width: 60, x: 12, y: 8 });\nconst hits = index.queryRect(camera.visibleRect); // viewport culling, returns ids\n```\n\n| Feature | Atlas | Ad-hoc math | Full scene libraries |\n| ------------------------------------- | -------------------------------------------- | ----------- | -------------------- |\n| Bundle size | <PackageInfo package=\"atlas\" type=\"size\" /> | n/a | Typically 20–100 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a | Varies |\n| Anchor-preserving zoom/rotate | Built in | Drifts | Yes |\n| Dynamic R-tree hit-testing | Built in | O(n) scans | Yes |\n| Headless: no DOM, canvas, or renderer | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies | Usually coupled |\n\n<div class=\"decision-callout\">\n\n**Use Atlas when** you own the render loop and scene model but want correct, tested camera, geometry, and spatial-query math without writing it yourself.\n\n**Consider a full canvas engine when** you want a retained scene graph, built-in rendering, and event routing wholesale instead of headless primitives.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/atlas\n```\n\n```sh [npm]\nnpm install @vielzeug/atlas\n```\n\n```sh [yarn]\nyarn add @vielzeug/atlas\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// state.x/y is the world point at the viewport centre\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: 600, width: 800 });\ncamera.panBy(20, 0); // content follows the drag\ncamera.fitBounds({ height: 400, width: 600, x: -50, y: -50 }, { padding: 40 });\n\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nindex.queryPoint({ x: 5, y: 5 }); // ['a']\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createCamera()`: viewport-centred state, pan, anchor-preserving zoom/rotate, `fitBounds()`, rotated `visibleRect`, and `animateTo()` with an injectable frame scheduler\n- `createSpatialIndex()`: dynamic R-tree (Guttman quadratic split) with `set`/`delete`/`get`/`queryRect`/`queryPoint` over ids\n- Matrix helpers: `multiply`, `invert`, `apply`, `translate`, `scale`, `rotate`, `around`, `scaleOf`, `toCssMatrix` in Canvas2D element order\n- Rect math: union, closed-interval intersection, containment, inflation, and bounds-from-points\n- Snapping: `snapRect()` alignment/grid/equal-gap guides with `kind`-tagged targets, plus pure `alignRects()`/`distributeRects()`\n- Narrow-phase geometry: `pointInPolygon`, `distanceToPolyline`, `pointNearPolygon` for exact stroke and polygon hit-testing\n- `AtlasError` / `AtlasConfigError`: typed errors; the camera follows the Vielzeug disposal contract\n- Zero runtime dependencies, no DOM requirement: works in Node, Workers, and SSR\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Gesture](/gesture/): pinch and wheel handles feed `zoomAt()` and `panBy()` directly.\n- [Ink](/ink/): stroke geometry whose bounds and outlines Atlas hit-tests.\n- [Wire](/wire/): edge routing for node editors sharing the same world coordinates.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Atlas: API Reference'\ndescription: API reference for the Atlas camera, spatial index, matrix, rect, and narrow-phase geometry helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ------------------------------------ | -------------------------------------------------------- | --------- | --------------------------------------------------------- |\n| `createCamera()` | Pan/zoom/rotate camera with anchor-preserving transforms | Sync | `x`/`y` is the world point at the viewport centre |\n| `createSpatialIndex()` | Dynamic R-tree over world-space rects | Sync | Broad-phase only: bounds overlap, not exact shape hits |\n| `multiply()` etc. | Canvas2D-order matrix composition | Sync | Element order is `[a,b,c,d,e,f]`, not row-major 3×3 |\n| `rectFromPoints()` | AABB of a point set | Sync | Returns `null` only for iterable input that may be empty |\n| `pointInPolygon()` | Even-odd ray-cast containment | Sync | Boundary points are implementation-defined; add tolerance |\n| `distanceToPolyline()` | Distance to the nearest segment | Sync | Returns `Infinity` for empty paths |\n| `snapRect()` | Alignment, grid, and equal-gap snapping with guides | Sync | Each axis resolves independently; alignment wins |\n| `alignRects()` | Align rects to a shared edge or center | Sync | Pure: returns new rects, input untouched |\n| `distributeRects()` | Equalize gaps along one axis | Sync | Needs 3+ rects; outermost rects stay fixed |\n| `AtlasError` | Base class for all atlas errors | Sync | Narrow with `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options and negative tolerances | Sync | Thrown at call time |\n| `Point` / `Rect` / `Size` / `Matrix` | Structural shapes shared across the canvas toolkit | Sync | All readonly; treat as values |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------------- | ---------------------------------------------------------------------- |\n| `@vielzeug/atlas` | Camera, spatial index, matrix/rect/geometry helpers, types, and errors |\n| `@vielzeug/atlas/grid` | Square-tile math, recursive shadowcasting FOV, and fog-of-war state |\n\n---\n\n## Core Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\ntype Size = Readonly<{ width: number; height: number }>;\ntype Rect = Readonly<{ x: number; y: number; width: number; height: number }>;\n/** Canvas2D/DOMMatrix element order: [a, b, c, d, e, f]. */\ntype Matrix = readonly [number, number, number, number, number, number];\n```\n\n---\n\n## `createCamera()`\n\n```ts\nfunction createCamera(options?: CameraOptions): Camera;\n```\n\nCreates a mutable camera. `state.x`/`state.y` name the world point at the **centre** of the viewport, so a saved state renders the same view on any screen size.\n\n| Parameter | Type | Description |\n| --------- | --------------- | ----------------------------------------------------------------------------------- |\n| `options` | `CameraOptions` | `initial` state, `viewport` size in CSS px, `minZoom`/`maxZoom` clamps, `scheduler` |\n\n**Returns:** `Camera` handle.\n\n**Example**\n\n```ts\nimport { createCamera } from '@vielzeug/atlas';\n\nconst camera = createCamera({\n initial: { zoom: 1.5 },\n maxZoom: 8,\n minZoom: 0.1,\n viewport: { height: 600, width: 800 },\n});\ncamera.zoomAt({ x: 400, y: 300 }, 1.2);\n```\n\nWithout `viewport` the camera starts at 0×0, where the centre is the origin; call `camera.resize()` once the real size is known (a `ResizeObserver` on the viewport element is the usual source).\n\nThrows `AtlasConfigError` when clamps violate `0 < minZoom <= maxZoom` or initial coordinates are non-finite.\n\n### Camera members\n\n| Member | Description |\n| ---------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `state` | Current `{ x, y, zoom, rotation }` (readonly snapshot) |\n| `viewport` | Current viewport `Size` in CSS px |\n| `matrix` / `inverse` | world → screen / screen → world matrices; `inverse` is always defined |\n| `toScreen(p)` / `toWorld(p)` | Point transforms |\n| `set(target)` | Jump to a partial state immediately, cancelling any animation |\n| `resize(size)` | Change the viewport size, keeping the world centre fixed |\n| `panBy(dx, dy)` | Screen-space pan; content follows the delta |\n| `zoomAt(screenPoint, factor)` | Multiplicative zoom holding the world point under `screenPoint` fixed |\n| `rotateAt(screenPoint, delta)` | Rotation (radians) holding the world point under `screenPoint` fixed |\n| `fitBounds(bounds, { padding? })` | Frame `bounds` in the current viewport at current rotation |\n| `visibleRect` | World AABB of the rotated viewport, for culling (getter) |\n| `animateTo(target, options?)` | Animate `{ x, y, zoom, rotation }`; replaces any running animation |\n| `stop()` | Cancel the running animation without completing it |\n| `subscribe(listener, options?)` | State-change listener; returns an unsubscribe function |\n| `dispose()` / `disposed` / `disposalSignal` / `[Symbol.dispose]` | Vielzeug disposal contract; disposal aborts animations |\n\nDirect manipulation (`set`, `resize`, `panBy`, `zoomAt`, `rotateAt`, `fitBounds`) cancels a running `animateTo` first, so user input is never overwritten by the next animation frame. After `dispose`, every mutating method is a no-op and `subscribe` returns a no-op unsubscribe.\n\n`AnimationOptions`: `duration` (ms, default 250), `easing` (default ease-in-out), `signal` (abort mid-flight; the animation stops where it is). Zoom interpolates in log space; rotation takes the shortest angular path and lands normalized to `(-π, π]`. A zoom-only animation keeps the viewport centre fixed.\n\n`FrameScheduler`: `{ requestFrame, cancelFrame, now }`. Defaults to `requestAnimationFrame`/`performance.now()`; inject a fake one in tests.\n\n---\n\n## `createSpatialIndex()`\n\n```ts\nfunction createSpatialIndex<K = string>(options?: SpatialIndexOptions): SpatialIndex<K>;\n```\n\nCreates a dynamic R-tree (Guttman, quadratic split) keyed by ids. The index stores only ids and rects — you keep your data in your own `Map` and look it up from returned ids — so stored values can never go stale.\n\n| Parameter | Type | Description |\n| --------- | --------------------- | -------------------------------------------- |\n| `options` | `SpatialIndexOptions` | `maxEntriesPerNode` (integer ≥ 4, default 8) |\n\n**Returns:** `SpatialIndex<K>` handle.\n\n**Example**\n\n```ts\nimport { createSpatialIndex } from '@vielzeug/atlas';\n\nconst shapes = new Map<string, Shape>();\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nconst hits = index.queryRect(marquee); // string[] of ids\nconst shape = shapes.get(hits[0]);\n```\n\n### SpatialIndex members\n\n| Member | Description |\n| ----------------------------------- | ----------------------------------------------------------------------------------- |\n| `set(id, rect)` | Insert, or move an existing id; a no-op when the rect is unchanged |\n| `delete(id)` | `true` when removed, `false` when unknown |\n| `get(id)` | The current `Rect` for an id, or `undefined` |\n| `has(id)` | Membership test |\n| `queryRect(rect)` | Ids whose bounds overlap **or touch** `rect` (closed intervals) |\n| `queryPoint(point, { tolerance? })` | Ids within `tolerance` of `point` (default 0, inclusive); throws on negative values |\n| `clear()` / `size` / `bounds` | Reset, entry count, aggregate bounds (`null` when empty) |\n\nClosed-interval semantics mean zero-area rects (lines, points) are findable: a horizontal line entry is returned by any query rect that crosses it. The index owns no resources, so it has no disposal contract — drop the reference when done.\n\n---\n\n## Matrix Functions\n\nAll matrices use Canvas2D element order `[a, b, c, d, e, f]`; composition `multiply(a, b)` applies `a` first, then `b` (same order as chained `ctx.transform()` calls).\n\n| Function | Description |\n| ------------------------ | ------------------------------------------------- |\n| `IDENTITY` | Frozen identity matrix |\n| `multiply(a, b)` | Compose two matrices |\n| `apply(matrix, point)` | Transform a point |\n| `translate(tx, ty)` | Translation builder |\n| `scale(sx, sy?)` | Scale builder (`sy` defaults to `sx`) |\n| `rotate(radians)` | Rotation builder; positive is clockwise on screen |\n| `invert(matrix)` | Inverse; `null` for zero determinant |\n| `around(anchor, matrix)` | `translate(anchor) · matrix · translate(-anchor)` |\n| `scaleOf(matrix)` | Average axis scale (0 for degenerate matrices) |\n| `toCssMatrix(matrix)` | `matrix(...)` CSS value |\n\n---\n\n## Rect Functions\n\n| Function | Description |\n| ----------------------------------------------------------- | ------------------------------------------------------------------------------ |\n| `rectFromPoints(points)` | AABB of a point set; `null` for iterable input, non-null for a non-empty tuple |\n| `rectRight(rect)` / `rectBottom(rect)` / `rectCenter(rect)` | Edge and center accessors |\n| `unionRect(a, b)` | Smallest rect containing both |\n| `intersectRect(a, b)` | Overlap rect; `null` only when disjoint; touching yields a zero-area rect |\n| `rectsIntersect(a, b)` | Overlap-or-touch test (closed intervals) |\n| `containsRect(outer, inner)` / `containsPoint(rect, point)` | Inclusive containment tests |\n| `inflateRect(rect, amount)` | Grow every edge by `amount` |\n\n`rectFromPoints` has two overloads: pass a literal non-empty tuple (`rectFromPoints([a, b])`) for a guaranteed `Rect`, or any `Iterable<Point>` for `Rect | null`.\n\n---\n\n## Geometry Functions\n\n| Function | Description |\n| --------------------------------------------- | --------------------------------------------------------------------------- |\n| `pointInPolygon(polygon, point)` | Even-odd ray-cast containment |\n| `distanceToPolyline(path, point)` | Distance to the nearest segment; `Infinity` for empty paths |\n| `pointNearPolygon(polygon, point, tolerance)` | Inside the polygon OR within `tolerance` of its outline; throws on negative |\n\n---\n\n## Snapping Functions\n\n| Function | Description |\n| ------------------------------ | ---------------------------------------------------------------------------------------------- |\n| `snapRect(rect, options)` | Snapped `{ delta, guides }` against candidate rects, grid lines, and equal gaps |\n| `alignRects(rects, edge)` | Copies aligned to a shared `left`/`horizontal-center`/`right`/`top`/`vertical-center`/`bottom` |\n| `distributeRects(rects, axis)` | Copies with equalized gaps along `'x'` or `'y'` |\n\n`snapRect` options: `candidates` (rects to snap to; the moving rect itself must not be included), `grid` (`{ x?, y? }` line spacing), `spacing` (enable equal-gap centering, default `false`), `threshold` (max snap distance; throws `AtlasConfigError` when negative). Each axis resolves independently to its nearest target within `threshold` (inclusive) among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` reports which one engaged. When no target engaged on an axis, `spacing: true` centers the rect between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate counts as a neighbor only when it overlaps the moving rect on the perpendicular axis, and both sides need one.\n\nA `SnapGuide` is `{ axis, kind, position, from, to, marks? }`: `axis` is the axis the guide line is perpendicular to, `kind` is `'grid'`, `'object'`, or `'spacing'` (what the snap engaged, for dashed vs solid rendering), `position` is the world coordinate of the line, and `from`/`to` span the line along the other axis. Spacing guides sit at the position the rect actually occupies after both axes snapped, and carry `marks`: the centers of the two equal gaps, to draw as × markers. `alignRects` and `distributeRects` are pure; distribution keeps the outermost rects fixed and returns input copies unchanged for fewer than three rects.\n\n---\n\n## Grid Functions\n\nFrom the `@vielzeug/atlas/grid` subpath:\n\n| Function | Returns |\n| -------------------------------------- | ----------------------------------------------------------------------------------------------- |\n| `worldToTile(point, grid)` | `TileCoord` (`{ col, row }`) containing the point (floor division) |\n| `tileToRect(coord, grid)` | World `Rect` of the tile |\n| `tileCenter(coord, grid)` | World `Point` at the tile's centre |\n| `visibleTileRange(view, grid)` | `TileRange` (`minCol/maxCol/minRow/maxRow`) intersecting a world rect |\n| `iterateTileRange(range)` | Generator over every `TileCoord` in a range |\n| `tileKey(coord)` | Stable `\"col:row\"` string |\n| `computeFov(origin, radius, options?)` | `Set<string>` of visible `tileKey`s (8-octant recursive shadowcasting) |\n| `createFog()` | Three-state fog tracker over tile keys: `update`/`state`/`visible`, `exportState`/`importState` |\n\n`grid` is `{ tileSize }` (positive; `worldToTile`/`tileToRect`/`tileCenter`/`visibleTileRange` throw `AtlasConfigError` otherwise, as does a negative/non-integer FOV `radius`). `computeFov` options: `blocks(coord)` returns true when sight cannot pass through the tile; blocking tiles within range are themselves visible. The origin is always in the result. `TileCoord` is `{ col, row }`. `createFog()` stores `tileKey` strings, so a `computeFov` result feeds `fog.update()` directly: one call demotes the previously visible tiles to `seen` and marks the new keys `visible`. `fog.visible` is a `ReadonlySet<string>`.\n\n---\n\n## Errors\n\n| Class | Thrown when |\n| ------------------ | ------------------------------------------------------------ |\n| `AtlasError` | Base class; catch-all via `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options/clamps and negative snap or query tolerances |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Atlas: Usage Guide'\ndescription: Drive a camera, index shapes in an R-tree, and hit-test points, marquee rects, and polygons with Atlas.\n---\n\n[[toc]]\n\n## Basic Usage\n\nAtlas is headless: it never touches the DOM or a canvas. You feed it input events and scene rectangles, and it answers where things are.\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// Camera: (x, y) is the world point shown at the viewport centre.\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: viewport.clientHeight, width: viewport.clientWidth });\n\n// Screen → world for input handling.\nconst world = camera.toWorld({ x: event.offsetX, y: event.offsetY });\n\n// World → screen for positioning DOM overlays.\nconst screen = camera.toScreen(shape.position);\n```\n\n## Coordinate Spaces\n\nAtlas works in three spaces and never guesses between them:\n\n- **Client space**: `PointerEvent.clientX/Y`. Subtract the viewport's `getBoundingClientRect()` offset before handing coordinates to the camera.\n- **Screen space**: CSS pixels from the viewport element's top-left. `toWorld()` and `zoomAt()` take screen points. The camera learns this size through `resize()` — a `ResizeObserver` on the viewport element is the usual source.\n- **World space**: your scene coordinates. `camera.matrix` maps world → screen; `zoom` is screen pixels per world unit.\n\nPositive `rotation` is clockwise on screen (y grows downward) and is kept normalized to `(-π, π]`. `camera.matrix` uses Canvas2D element order `[a, b, c, d, e, f]`, so you can hand it straight to `ctx.setTransform()` (multiply by DPR first) or hand it to `toCssMatrix()` for DOM overlays. The getter is a cached composite recomputed only when the camera changes.\n\n## Zooming to the Cursor\n\n`zoomAt()` keeps the world point under a screen point fixed while the zoom changes — the standard infinite-canvas feel:\n\n```ts\nwheelElement.addEventListener('wheel', (event) => {\n const factor = Math.exp(-event.deltaY * 0.0015);\n camera.zoomAt({ x: event.offsetX, y: event.offsetY }, factor);\n});\n```\n\n`rotateAt()` does the same for rotation. Both clamp against `minZoom`/`maxZoom` and still hold the anchor exactly at the clamp.\n\n## Panning and Fitting\n\n`panBy(dx, dy)` takes a screen-space delta; content follows the drag. `fitBounds()` frames a world rect inside the current viewport with optional padding, preserving the current rotation:\n\n```ts\ncamera.panBy(event.movementX, event.movementY);\ncamera.fitBounds(selectionBounds, { padding: 48 });\n```\n\nBecause `state.x`/`state.y` is the world point at the viewport centre, a saved camera state re-frames the same view on any screen size, and a zoom-only `animateTo({ zoom })` keeps the view centred where the user is looking.\n\n## Animating the Camera\n\n`animateTo()` interpolates position linearly and zoom in log space (multiplicative zoom feels linear to the eye). Rotation takes the shortest angular path. Pass an injectable scheduler to drive animations from your render loop or tests:\n\n```ts\ncamera.animateTo(\n { x: 250, y: 100, zoom: 2 },\n {\n duration: 300,\n signal: controller.signal, // abort mid-flight; the animation stops where it is\n },\n);\n```\n\n## Indexing the Scene\n\n`createSpatialIndex()` is a dynamic R-tree keyed by ids. Index every shape by its world-space bounding box, then answer three questions fast: what is under this point, what does this marquee rect touch, and what is inside the viewport:\n\n```ts\nconst index = createSpatialIndex(); // keys default to string\n\nindex.set(shape.id, shape.bounds); // insert, and again after every move\nindex.delete(shape.id); // on delete\n\n// Viewport culling each frame.\nconst visibleIds = index.queryRect(camera.visibleRect);\n\n// Marquee selection — the index returns ids; your own Map holds the data.\nconst selected = index.queryRect(marquee).map((id) => shapes.get(id));\n\n// Hover: tolerance widens the point into a box for fat-finger targets.\nconst hovered = index.queryPoint(worldPoint, { tolerance: 4 / camera.state.zoom });\n```\n\nThe index stores only ids and rects, so it can never hand back a stale copy of your data — call `set()` with the new rect after each committed move. Queries use closed intervals: touching edges count, and zero-area rects (lines, points) are findable. The R-tree is broad-phase only: it answers \"bounding boxes overlap or touch\". For exact hits on polygonal shapes, follow up with the narrow-phase helpers below.\n\n## Exact Hit-Testing\n\n```ts\nimport { pointNearPolygon, pointInPolygon } from '@vielzeug/atlas';\n\npointInPolygon(polygon, worldPoint); // even-odd ray cast\npointNearPolygon(polygon, worldPoint, 2); // inside OR within 2 units of the outline\n```\n\nBuild the polygon from the shape's actual corners (rotate each point yourself with `apply()` if needed) and index its axis-aligned hull in the R-tree. `pointNearPolygon` is what a vector tool needs to hit-test a stroked (unfilled) shape: the outline band plus the interior both count.\n\n## Snapping and Alignment\n\nWhile a shape moves, one `snapRect()` call snaps it to nearby shapes, grid lines, and equal gaps, and returns the guides to draw on an overlay:\n\n```ts\nimport { snapRect } from '@vielzeug/atlas';\n\nconst snap = snapRect(dragRect, {\n candidates: otherSelectedOutRects,\n grid: { x: 50, y: 50 },\n spacing: true, // opt into equal-gap spacing between neighbors\n threshold: 8,\n});\nconst snapped = { ...dragRect, x: dragRect.x + snap.delta.x, y: dragRect.y + snap.delta.y };\n// snap.guides: [{ axis, kind, position, from, to, marks? }] in world coordinates — draw them through the camera.\n```\n\nEach axis resolves independently to its nearest target within `threshold` among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` says which one engaged. With `spacing: true`, an axis that found no target at all falls back to img.ly-style equal-gap centering: the rect centers itself between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate only counts as a neighbor when it overlaps the moving rect on the perpendicular axis, and both sides need one, so a lone shape never spacing-snaps.\n\nEvery guide carries `kind: 'grid' | 'object' | 'spacing'` so you can style them apart (dashed for grid, solid for objects, × marks at `marks` for spacing). `axis` is the axis the line is perpendicular to: an `axis: 'x'` guide is a vertical line at `position`, running from `from` to `to`. Spacing guides sit at the position the rect actually occupies after both axes snapped, so the marker lines up with the shape. On drop, commit `snapped` to your model so undo history records the final position, not the raw pointer position.\n\nAfter a multi-select, align or distribute with the pure helpers and record one command:\n\n```ts\nimport { alignRects, distributeRects } from '@vielzeug/atlas';\n\nconst aligned = alignRects(selectedRects, 'horizontal-center'); // copies, same order\nconst spread = distributeRects(selectedRects, 'x'); // equal gaps, outermost fixed\n```\n\n## Matrix Helpers\n\nFor custom transforms, the matrix functions use Canvas2D order and compose left-to-right like `ctx.transform()`:\n\n```ts\nimport {\n apply,\n around,\n IDENTITY,\n invert,\n multiply,\n rotate,\n scale,\n scaleOf,\n toCssMatrix,\n translate,\n} from '@vielzeug/atlas';\n\nconst transform = multiply(multiply(scale(2), rotate(Math.PI / 4)), translate(10, 5));\napply(transform, { x: 1, y: 0 }); // transformed point\ninvert(transform); // null for degenerate matrices\naround({ x: 100, y: 100 }, scale(2)); // scale about a point, not the origin\nscaleOf(transform); // average axis scale\ntoCssMatrix(transform); // 'matrix(...)' for CSS transforms\n```\n\n## Tile Grids\n\nTile and map editors live on a square grid. The `@vielzeug/atlas/grid` subpath converts between world coordinates and tile coordinates, and enumerates only the tiles a viewport can see:\n\n```ts\nimport { iterateTileRange, tileCenter, tileKey, tileToRect, visibleTileRange, worldToTile } from '@vielzeug/atlas/grid';\n\nconst grid = { tileSize: 32 };\n\nworldToTile({ x: 40, y: -1 }, grid); // { col: 1, row: -1 }\ntileToRect({ col: 1, row: -1 }, grid); // { x: 32, y: -32, width: 32, height: 32 }\ntileCenter({ col: 1, row: -1 }, grid); // { x: 48, y: -16 }\n\n// Render loop: iterate the tiles intersecting the camera's world rect.\nfor (const coord of iterateTileRange(visibleTileRange(camera.visibleRect, grid))) {\n drawTile(coord);\n}\n```\n\n`tileKey(coord)` yields the stable `\"col:row\"` string used by the FOV and fog APIs (and convenient as a `Map` key).\n\n## Field of View and Fog\n\n`computeFov()` runs recursive shadowcasting over the eight octants and returns the set of `tileKey` strings a viewer can see within a radius. Blocking tiles are visible but cast shadows behind themselves:\n\n```ts\nimport { computeFov, createFog } from '@vielzeug/atlas/grid';\n\nconst fov = computeFov({ col: 10, row: 8 }, 6, { blocks: (c) => walls.has(`${c.col}:${c.row}`) });\n\nconst fog = createFog();\nfog.update(fov); // demotes the previous frame's visible tiles to 'seen'\nfog.state(tileKey({ col: 10, row: 8 })); // 'visible' | 'seen' | 'unseen'\nsaveGame(fog.exportState()); // serializable { seen, visible } key lists\n```\n\n`computeFov()` is pure and costs O(radius²) worst case; walls prune the walk. `createFog()` owns the three-state bookkeeping (`unseen` → `visible` → `seen`) over `tileKey` strings and round-trips through `exportState()`/`importState()` for save files. One `update(visibleKeys)` call per frame replaces the whole visible set — demote-then-reveal ordering is handled for you — and `fog.visible` is a `ReadonlySet<string>` of the current keys.\n\n## Best Practices\n\n- Subtract the viewport rect once at the input boundary; never mix client and screen coordinates inside camera calls.\n- Call `camera.resize()` from a `ResizeObserver` on the viewport element; the camera cannot anchor zooms to the centre without knowing its size.\n- Call `index.set(id, rect)` after every committed move — stale bounds silently break marquee and culling queries.\n- Use `camera.visibleRect` (the world AABB of the rotated viewport) for culling; it is conservative by design, so no visible shape is ever dropped.\n- Snap against the pre-move rect each pointer move (not the last snapped rect) so the delta stays relative to the raw pointer and snapping never drifts cumulatively.\n- Dispose the camera when the editor unmounts; disposal aborts in-flight animations and turns every mutating method into a no-op. The spatial index owns no resources, so it needs no disposal.\n",
|
|
7
|
+
"examples": "---\ntitle: 'Atlas: Examples'\ndescription: Practical examples and recipes for @vielzeug/atlas.\n---\n\n## Examples\n\n- [Pan, Zoom and Culling](./examples/pan-zoom-and-culling.md)\n"
|
|
8
|
+
},
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "atlas-camera",
|
|
12
|
+
"code": "import { createCamera, createSpatialIndex } from '@vielzeug/atlas'\n\n// A small scene of world-space rects, indexed by id for hit-testing.\nconst index = createSpatialIndex()\nconst colors = new Map()\nconst palette = ['#38bdf8', '#a78bfa', '#f472b6', '#34d399', '#fbbf24']\nfor (let i = 0; i < 40; i++) {\n const x = (i % 8) * 90 - 320\n const y = Math.floor(i / 8) * 70 - 140\n index.set('r' + i, { x, y, width: 60, height: 44 })\n colors.set('r' + i, palette[i % palette.length])\n}\n\n// Camera state is the world point at the viewport centre (the SVG is 480x300).\nconst camera = createCamera({ minZoom: 0.2, maxZoom: 8, viewport: { width: 480, height: 300 } })\ncamera.fitBounds({ x: -320, y: -140, width: 700, height: 420 }, { padding: 20 })\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 480 300')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none;cursor:grab'\ndocument.body.appendChild(svg)\n\nfunction render() {\n svg.replaceChildren()\n for (const id of index.queryRect(camera.visibleRect)) {\n const r = index.get(id)\n const p = camera.toScreen({ x: r.x, y: r.y })\n const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')\n rect.setAttribute('x', String(p.x))\n rect.setAttribute('y', String(p.y))\n rect.setAttribute('width', String(r.width * camera.state.zoom))\n rect.setAttribute('height', String(r.height * camera.state.zoom))\n rect.setAttribute('rx', '6')\n rect.setAttribute('fill', colors.get(id))\n svg.appendChild(rect)\n }\n}\nrender()\n\n// Wheel zoom anchored at the cursor.\nsvg.addEventListener('wheel', (event) => {\n event.preventDefault()\n const box = svg.getBoundingClientRect()\n const sx = (event.clientX - box.left) * (480 / box.width)\n const sy = (event.clientY - box.top) * (300 / box.height)\n camera.zoomAt({ x: sx, y: sy }, Math.exp(-event.deltaY * 0.0015))\n render()\n}, { passive: false })\n\n// Drag to pan; double-click fits the whole scene again.\nlet dragging = false\nsvg.addEventListener('pointerdown', (event) => {\n dragging = true\n svg.setPointerCapture(event.pointerId)\n svg.style.cursor = 'grabbing'\n})\nsvg.addEventListener('pointermove', (event) => {\n if (dragging) { camera.panBy(event.movementX, event.movementY); render() }\n})\nsvg.addEventListener('pointerup', () => { dragging = false; svg.style.cursor = 'grab' })\nsvg.addEventListener('dblclick', () => {\n camera.animateTo({ x: 0, y: 0, zoom: 1, rotation: 0 }, { duration: 400 })\n})\n\nconsole.log('visible rects:', index.queryRect(camera.visibleRect).length)",
|
|
13
|
+
"name": "createCamera - Pan, zoom and culling"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"id": "atlas-snap",
|
|
17
|
+
"code": "import { alignRects, distributeRects, snapRect, type Rect } from '@vielzeug/atlas'\n\n// Drag a rect with the pointer; it snaps to nearby rects and a 50px grid.\nconst candidates: Rect[] = [\n { x: -120, y: -80, width: 80, height: 60 },\n { x: 40, y: 20, width: 100, height: 40 },\n { x: -30, y: 110, width: 60, height: 60 },\n]\nlet moving: Rect = { x: 150, y: -40, width: 90, height: 50 }\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '-200 -150 480 340')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none'\ndocument.body.appendChild(svg)\n\nfunction render(guides) {\n svg.replaceChildren()\n const ns = 'http://www.w3.org/2000/svg'\n for (const g of guides) {\n const line = document.createElementNS(ns, 'line')\n if (g.axis === 'x') {\n line.setAttribute('x1', String(g.position)); line.setAttribute('x2', String(g.position))\n line.setAttribute('y1', String(g.from)); line.setAttribute('y2', String(g.to))\n } else {\n line.setAttribute('y1', String(g.position)); line.setAttribute('y2', String(g.position))\n line.setAttribute('x1', String(g.from)); line.setAttribute('x2', String(g.to))\n }\n line.setAttribute('stroke', '#f472b6'); line.setAttribute('stroke-width', '1.5')\n svg.appendChild(line)\n }\n for (const r of [...candidates, moving]) {\n const rect = document.createElementNS(ns, 'rect')\n rect.setAttribute('x', String(r.x)); rect.setAttribute('y', String(r.y))\n rect.setAttribute('width', String(r.width)); rect.setAttribute('height', String(r.height))\n rect.setAttribute('rx', '6')\n rect.setAttribute('fill', r === moving ? '#38bdf8' : '#334155')\n svg.appendChild(rect)\n }\n}\nrender([])\n\nsvg.addEventListener('pointermove', (event) => {\n if (event.buttons !== 1) return\n const box = svg.getBoundingClientRect()\n const px = (event.clientX - box.left) * (480 / box.width) - 200\n const py = (event.clientY - box.top) * (340 / box.height) - 150\n const target = { ...moving, x: px - moving.width / 2, y: py - moving.height / 2 }\n const snap = snapRect(target, { candidates, grid: { x: 50, y: 50 }, threshold: 8 })\n moving = { ...target, x: target.x + snap.delta.x, y: target.y + snap.delta.y }\n render(snap.guides)\n})\n\n// Press A to align all rects to the top edge, D to distribute horizontally.\nwindow.addEventListener('keydown', (event) => {\n if (event.key === 'a') candidates.splice(0, candidates.length, ...alignRects(candidates, 'top'))\n if (event.key === 'd') candidates.splice(0, candidates.length, ...distributeRects(candidates, 'x'))\n render([])\n})",
|
|
18
|
+
"name": "snapRect - Magnetic snapping and guides"
|
|
19
|
+
}
|
|
20
|
+
],
|
|
21
|
+
"typeSignatures": {
|
|
22
|
+
"AnimationOptions": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
23
|
+
"Camera": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
24
|
+
"CameraOptions": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
25
|
+
"CameraState": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
26
|
+
"createCamera": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
27
|
+
"FrameScheduler": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
28
|
+
"AtlasConfigError": "export { AtlasConfigError, AtlasError } from './errors.js';",
|
|
29
|
+
"AtlasError": "export { AtlasConfigError, AtlasError } from './errors.js';",
|
|
30
|
+
"distanceToPolyline": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
31
|
+
"pointInPolygon": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
32
|
+
"pointNearPolygon": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
33
|
+
"apply": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
34
|
+
"around": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
35
|
+
"IDENTITY": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
36
|
+
"invert": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
37
|
+
"multiply": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
38
|
+
"rotate": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
39
|
+
"scale": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
40
|
+
"scaleOf": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
41
|
+
"toCssMatrix": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
42
|
+
"translate": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
43
|
+
"containsPoint": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
44
|
+
"containsRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
45
|
+
"inflateRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
46
|
+
"intersectRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
47
|
+
"rectBottom": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
48
|
+
"rectCenter": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
49
|
+
"rectFromPoints": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
50
|
+
"rectRight": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
51
|
+
"rectsIntersect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
52
|
+
"unionRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
53
|
+
"Matrix": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
54
|
+
"Point": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
55
|
+
"Rect": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
56
|
+
"Size": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
57
|
+
"AlignEdge": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
58
|
+
"alignRects": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
59
|
+
"distributeRects": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
60
|
+
"SnapGuide": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
61
|
+
"SnapGuideKind": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
62
|
+
"SnapOptions": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
63
|
+
"SnapResult": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
64
|
+
"snapRect": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
65
|
+
"createSpatialIndex": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';",
|
|
66
|
+
"SpatialIndex": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';",
|
|
67
|
+
"SpatialIndexOptions": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';",
|
|
68
|
+
"SpatialQueryOptions": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"index": "---\ntitle: 'Beacon: Product tours and coachmarks'\ndescription: 'Guided onboarding and contextual product tours for web applications'\npackage: beacon\ncategory: ui-interaction\nkeywords: [onboarding, product-tour, coachmark, walkthrough, step-by-step, spotlight, headless]\nrelated: [refine, orbit, ripple, vault]\nexports: [createTour, createCoachmark, resolveTarget]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"beacon\" />\n\n## Why Beacon?\n\nProduct tours rot fast: hand-wired step sequences hard-code positioning, persistence, and target waiting into application code, and break the first time the UI moves. Beacon is the headless half of a tour — it owns step order, target waiting, resumable progress, and events — while your markup (or `@vielzeug/refine`'s `ore-tour` components) decides what a step looks like.\n\n```ts\n// Before: step logic tangled with rendering and storage\nlet step = Number(localStorage.getItem('tour-step') ?? 0);\nfunction showStep() {\n const el = document.querySelector(steps[step].selector);\n card.style.top = `${el.getBoundingClientRect().bottom + 8}px`; // breaks on scroll\n card.innerHTML = steps[step].html;\n}\n\n// After: the engine owns order, persistence, and the anchor rect\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({ id: 'welcome', steps, storage });\ntour.current.subscribe(() => renderCard(tour.current.value)); // rect is the live anchor\ntour.start();\n```\n\n| Feature | Beacon | Shepherd.js | Intro.js |\n| ---------------------------- | --------------------------------------------------- | -------------------------------------------- | ----------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"beacon\" type=\"size\" /> | ~50 kB | ~25 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> (none) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Headless (you own the UI) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Resumable persisted progress | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| Versioned re-offers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Coachmarks (single hints) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Beacon when** tours must survive UI changes: steps anchor to your real DOM, progress persists and resumes, and the card markup is yours (or refine's ready-made `ore-tour`).\n\n**Consider Shepherd or Intro.js when** you want a fully-rendered, opinionated tour widget you never style yourself and can accept their DOM and CSS.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/beacon\n```\n\n```sh [npm]\nnpm install @vielzeug/beacon\n```\n\n```sh [yarn]\nyarn add @vielzeug/beacon\n```\n\n:::\n\n## Quick Start\n\nDefine the tour as data, run it, and render the current step wherever you like. The handle is disposable, so component teardown cleans everything up.\n\n```ts\nimport { createTour, type BeaconTourConfig } from '@vielzeug/beacon';\n\nconst config = {\n id: 'getting-started',\n steps: [\n { id: 'welcome', title: 'Welcome', description: 'A two-minute look around.' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Navigation', placement: 'bottom-start' },\n ],\n} satisfies BeaconTourConfig;\n\nconst tour = createTour(config);\n\n// Render from the live snapshot: rect is the anchor, null centers the card.\nconst unsubscribe = tour.current.subscribe(() => {\n const { presentation, rect, step } = tour.current.value;\n console.log({ presentation, rect, step }); // drive your card from this\n});\n\ntour.start();\n\n// On teardown:\nunsubscribe();\ntour.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createTour()` runs a sequential, resumable walkthrough over your own DOM.\n- `createCoachmark()` shows a single contextual hint once per user per version.\n- `current` is a live `Readable<BeaconCurrentStep>` snapshot: step, index, placement, presentation, and resolved anchor rect, kept fresh on scroll, resize, and layout changes.\n- `target` accepts a selector, `Element`, rect, or lazy resolver, and beacon waits for lazily-mounted targets before showing the step.\n- `storage` persists progress through any `BeaconStorage` bridge (localStorage, IndexedDB via `@vielzeug/vault`, a server API).\n- `version` re-offers a finished tour when the product changes underneath it.\n- `tap()` subscribes to lifecycle events (`step:start`, `tour:complete`, `target-missing`, ...) with `AbortSignal` support.\n- `resolveTarget()` turns any target into a viewport rect compatible with `@vielzeug/orbit` positioners.\n- `ore-tour`'s `bind()` in `@vielzeug/refine` renders a handle and routes its actions with zero glue code.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Refine](/refine/): ships `ore-tour` and `ore-spotlight`, the ready-made dialog/popover/bottom-sheet presentation layer for a beacon handle.\n- [Orbit](/orbit/): compute exact popover coordinates from `current.rect` when you build a custom presentation.\n- [Vault](/vault/): durable storage backends that plug into `BeaconStorage` with a six-line bridge.\n- [Ripple](/ripple/): the `Readable` signals every beacon handle exposes come from here.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
5
|
"api": "---\ntitle: 'Beacon: API Reference'\ndescription: Public API of @vielzeug/beacon.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------- | ----------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------- |\n| `createTour(config)` | Runs a sequential, resumable walkthrough over the app's DOM | Sync (storage reads may be async) | `start()` is a no-op when the stored record says the tour is completed |\n| `createCoachmark(config)` | Shows a single contextual hint anchored to one target | Sync (storage reads may be async) | `show()` is a no-op after `dismiss()` until `reset()` or a `version` bump |\n| `resolveTarget(target)` | Resolves any target to a viewport-space rect or `null` | Sync | Call it per position update; a scrolled target's rect changes |\n| `BeaconError` | Base class for all beacon-originated errors | — | Catch this to catch any beacon error |\n| `BeaconConfigError` | Invalid tour/coachmark configuration | Thrown at creation | Empty `steps` or duplicate step ids fail at `createTour()` |\n| `BeaconDisposedError` | Handle used after `dispose()` | Thrown on call | `dispose()` is idempotent; later method calls throw |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------- |\n| `@vielzeug/beacon` | Complete public Beacon API |\n\n---\n\n## Core Functions\n\n### createTour\n\n```ts\nfunction createTour(config: BeaconTourConfig): BeaconTourHandle;\n```\n\nReturns a live handle for one guided tour. Throws `BeaconConfigError` when `id` is empty, `steps` is empty, or step ids are duplicated.\n\nParameters: see [`BeaconTourConfig`](#beacontourconfig).\n\n**Returns:** a [`BeaconTourHandle`](#beacontourhandle) that is also `Disposable`.\n\n**Example:**\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({\n id: 'release-tour',\n steps: [{ id: 'intro', title: 'What changed' }],\n autoStart: true,\n});\n\ntour.status.subscribe(() => console.log(tour.status.value));\n```\n\nHandle methods:\n\n| Member | Behavior |\n| ---------------------------------- | ------------------------------------------------------------------------------------------------- |\n| `start()` | Begin or resume the tour. No-op when completed; throws after dispose. |\n| `next()` | Advance; past the last step, finishes the tour. |\n| `back()` | Return to the previous step. No-op on the first step. |\n| `goto(step)` | Jump to a step by index or id. Unknown values warn and no-op. |\n| `pause()` | Stop showing, keep progress so `start()` resumes it. |\n| `skip()` | End from a \"Skip\" control. Persisted as dismissed, reported with reason `'skip'`. |\n| `finish()` | Mark finished and stop showing. |\n| `dismiss()` | End by closing (Escape, backdrop). Persisted as dismissed. |\n| `reset()` | Discard persisted progress; the tour is eligible again. |\n| `tap(handler, options?)` | Observe [`BeaconTourEvent`](#beacontourentype)s; returns an unsubscribe, honors `options.signal`. |\n| `dispose()` / `[Symbol.dispose]()` | Release all listeners and observers. Idempotent. |\n| Handle properties: |\n\n| Member | Type | Notes |\n| ---------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `current` | `Readable<BeaconCurrentStep>` | The snapshot to render; `step` is `null` while closed. Beacon re-publishes the rect on scroll, resize, and target layout changes while a step is active. |\n| `status` | `Readable<BeaconStatus>` | Lifecycle, persisted on every change. |\n| `eligible` | `Readable<boolean>` | Whether the tour should be offered to this user. |\n| `steps` | `readonly BeaconStep[]` | The configured steps, in order. |\n| `id` | `string` | The configured id (also the storage key suffix). |\n| `disposed` | `boolean` | Whether `dispose()` has run. |\n| `disposalSignal` | `AbortSignal` | Aborted on dispose; pass it to your own listeners. |\n\n---\n\n### createCoachmark\n\n```ts\nfunction createCoachmark(config: BeaconCoachmarkConfig): BeaconCoachmarkHandle;\n```\n\nReturns a handle for one contextual hint. Throws `BeaconConfigError` when `id` is empty.\n\nParameters: see [`BeaconCoachmarkConfig`](#beaconcoachmarkconfig).\n\n**Returns:** a [`BeaconCoachmarkHandle`](#beaconcoachmarkhandle) that is also `Disposable`.\n\n**Example:**\n\n```ts\nimport { createCoachmark } from '@vielzeug/beacon';\n\nconst hint = createCoachmark({\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n});\n\nhint.show(); // waits for the target to mount if it is not on screen yet\n```\n\nHandle members:\n\n| Member | Behavior |\n| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `show()` | Show the hint. No-op once dismissed without a newer version. |\n| `hide()` | Hide without recording it as seen; it can show again. |\n| `dismiss()` | Hide and record as seen permanently (until `reset()`/`version`). |\n| `reset()` | Discard the persisted record; the hint is eligible again. |\n| `tap(handler, options?)` | Observe `coachmark:show`, `coachmark:dismiss`, and common events. |\n| `current` | `Readable<BeaconCurrentStep>` — the hint as a single-step snapshot: `step` is the hint while visible, `null` while hidden. The rect stays live on scroll, resize, and target layout changes. |\n| `eligible` | `Readable<boolean>` — never seen, or superseded by a newer version. |\n\n---\n\n### resolveTarget\n\n```ts\nfunction resolveTarget(target: BeaconTarget): BeaconRect | null;\n```\n\nResolves a target to a viewport-space rect, or `null` when it is not available yet. Strings resolve through `document.querySelector`; functions are called and their result normalized.\n\n| Parameter | Type | Description |\n| --------- | -------------- | -------------------------------------------- |\n| `target` | `BeaconTarget` | Selector, `Element`, rect, or lazy resolver. |\n\n**Returns:** `BeaconRect | null` — shape-compatible with `getBoundingClientRect()` and `@vielzeug/orbit`'s `Rect`.\n\n**Example:**\n\n```ts\nimport { resolveTarget } from '@vielzeug/beacon';\n\nconst rect = resolveTarget('[data-tour=\"share\"]');\n// Anchor an orbit positioner from a virtual reference:\nconst reference = { getBoundingClientRect: () => resolveTarget('[data-tour=\"share\"]') ?? ZERO_RECT };\n```\n\n---\n\n## Types\n\n### BeaconTourConfig\n\n| Option | Type | Default | Description |\n| ----------------- | -------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------- |\n| `id` | `string` | required | Unique identity; used as the storage key. |\n| `steps` | `readonly BeaconStep[]` | required | Every step, in order. At least one. |\n| `autoScroll` | `boolean` | `true` | Scroll each anchored step's target into view when it activates. |\n| `autoStart` | `boolean` | `false` | Start on the next microtask when eligible. |\n| `placement` | `BeaconPlacement` | `'auto'` | Default placement handed to the presentation layer. |\n| `presentation` | `BeaconPresentation` | `'auto'` | Default presentation handed to the presentation layer. |\n| `scrollOffset` | `number \\| (() => number)` | `0` | Pixels kept clear at the viewport top for a sticky header, read at scroll time. |\n| `storage` | `BeaconStorage` | memory-only | Progress persistence. |\n| `targetTimeoutMs` | `number` | `Infinity` | How long to wait for a step's target before skipping that step. `0` publishes immediately with a `null` rect. |\n| `version` | `number` | `1` | Bump to re-show a finished tour. |\n\n### BeaconCoachmarkConfig\n\n| Option | Type | Default | Description |\n| -------------- | -------------------- | ----------- | ------------------------------------------ |\n| `id` | `string` | required | Unique identity; used as the storage key. |\n| `target` | `BeaconTarget` | required | Where the hint points. |\n| `autoShow` | `boolean` | `true` | Show automatically when not yet seen. |\n| `data` | `unknown` | — | Free-form data for the presentation layer. |\n| `description` | `string` | — | Supporting copy. |\n| `placement` | `BeaconPlacement` | `'auto'` | Preferred side. |\n| `presentation` | `BeaconPresentation` | `'auto'` | Preferred presentation. |\n| `storage` | `BeaconStorage` | memory-only | Seen-record persistence. |\n| `title` | `string` | — | Headline copy. |\n| `version` | `number` | `1` | Bump to re-show a seen coachmark. |\n\n### BeaconStep\n\n```ts\ninterface BeaconStep {\n readonly data?: unknown;\n readonly description?: string;\n readonly id: string;\n readonly placement?: BeaconPlacement;\n readonly presentation?: BeaconPresentation;\n readonly target?: BeaconTarget;\n readonly title?: string;\n}\n```\n\nOne stop in a tour. `id` is stable and persisted — renaming it resets progress for that step. Omit `target` for a centered intro/outro step. `placement`/`presentation` override the tour-level defaults.\n\n### BeaconTarget\n\n```ts\ntype BeaconTarget = BeaconTargetResolver | BeaconRect | Element | string;\n```\n\nWhat a step points at. Selectors and elements anchor to real DOM; rects (or resolvers returning one) anchor to element-less geometry such as a canvas region.\n\n### BeaconTargetResolver\n\n```ts\ntype BeaconTargetResolver = () => Element | BeaconRect | null;\n```\n\nResolves a target lazily; `null` means \"not available yet\".\n\n### BeaconRect\n\n```ts\ninterface BeaconRect {\n readonly height: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n}\n```\n\nA viewport-space rectangle in CSS pixels. Matches `@vielzeug/orbit`'s `Rect` shape.\n\n### BeaconPlacement\n\n```ts\ntype BeaconPlacement =\n | 'auto'\n | 'bottom'\n | 'bottom-end'\n | 'bottom-start'\n | 'left'\n | 'left-end'\n | 'left-start'\n | 'right'\n | 'right-end'\n | 'right-start'\n | 'top'\n | 'top-end'\n | 'top-start';\n```\n\nPreferred side for an anchored presentation; `'auto'` asks the positioning layer to choose.\n\n### BeaconPresentation\n\n```ts\ntype BeaconPresentation = 'auto' | 'bottom-sheet' | 'modal' | 'popover';\n```\n\nHow a step should be presented. `'auto'` lets the presentation layer pick by available space.\n\n### BeaconStatus\n\n```ts\ntype BeaconStatus = 'active' | 'completed' | 'dismissed' | 'idle' | 'paused';\n```\n\nTour lifecycle, persisted across visits. `'idle'` means never started.\n\n### BeaconProgress\n\n```ts\ninterface BeaconProgress {\n readonly status: BeaconStatus;\n readonly stepIndex: number;\n readonly version: number;\n}\n```\n\nThe persisted record for one tour or coachmark. `stepIndex` is `-1` before the first step. Records are validated on read; invalid records fall back to a fresh tour.\n\n### BeaconStorage\n\n```ts\ninterface BeaconStorage {\n get(key: string): Promise<BeaconProgress | null | undefined> | BeaconProgress | null | undefined;\n remove(key: string): Promise<unknown> | unknown;\n set(key: string, value: BeaconProgress): Promise<unknown> | unknown;\n}\n```\n\nMinimal storage contract; sync or async. Values are JSON. Keys arrive namespaced (`@vielzeug/beacon:<id>`). A `@vielzeug/vault` store plugs in with:\n\n```ts\nconst storage: BeaconStorage = {\n get: (key) => store.get('progress', key),\n remove: (key) => store.delete('progress', key),\n set: (key, value) => store.put('progress', { id: key, ...value }),\n};\n```\n\n### BeaconCurrentStep\n\n```ts\ninterface BeaconCurrentStep {\n readonly placement: BeaconPlacement;\n readonly presentation: BeaconPresentation;\n readonly rect: BeaconRect | null;\n readonly step: BeaconStep | null;\n readonly stepIndex: number;\n readonly totalSteps: number;\n}\n```\n\nThe snapshot a presentation layer renders from. `step` is `null` before start and after the tour ends; `rect` is `null` for centered steps and unresolved targets. While a step is active, Beacon keeps `rect` fresh on scroll, resize, and target layout changes — no app-side refresh call is needed.\n\n### BeaconTourEvent\n\n```ts\ntype BeaconTourEvent =\n | { readonly index: number; readonly step: BeaconStep; readonly type: 'step:start' }\n | { readonly index: number; readonly step: BeaconStep; readonly type: 'step:complete' }\n | { readonly reason: 'finish' | 'skip'; readonly type: 'tour:complete' }\n | { readonly type: 'tour:dismiss' }\n | { readonly status: BeaconStatus; readonly type: 'status-change' }\n | { readonly message: string; readonly type: 'target-missing' }\n | { readonly index: number; readonly message: string; readonly step: BeaconStep; readonly type: 'target-waiting' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\nNotable moments a tour reports through `tap()`. `target-missing` means a step was skipped because its target did not appear in time; `target-waiting` fires when a step begins waiting for its target to mount; `warning` carries storage or handler failures.\n\n### BeaconCoachmarkEvent\n\n```ts\ntype BeaconCoachmarkEvent =\n | { readonly type: 'coachmark:show' }\n | { readonly type: 'coachmark:dismiss' }\n | { readonly type: 'target-waiting' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\nNotable moments a coachmark reports through `tap()`.\n\n### BeaconTourHandle / BeaconCoachmarkHandle\n\nThe objects returned by `createTour()` and `createCoachmark()`, documented in [Core Functions](#core-functions). Both expose `disposalSignal`, `disposed`, `tap()`, `dispose()`, and `[Symbol.dispose]()`.\n\n## Errors\n\n| Error | Triggered by | Notes |\n| --------------------- | ----------------------------------------------------- | ------------------------------------------------------------------ |\n| `BeaconError` | Base for all beacon errors | `name` is the subclass name; `cause` supported via `ErrorOptions`. |\n| `BeaconConfigError` | Empty `id`, empty `steps`, missing/duplicate step ids | Thrown synchronously from `createTour()`/`createCoachmark()`. |\n| `BeaconDisposedError` | Calling handle methods after `dispose()` | `dispose()` itself never throws. |\n",
|
|
6
6
|
"usage": "---\ntitle: 'Beacon: Usage Guide'\ndescription: How to use @vielzeug/beacon.\n---\n\n[[toc]]\n\n## Basic Usage\n\nA tour is a config object plus a handle you drive from your own UI. The handle never renders anything: it publishes a `current` snapshot, and your card (or refine's `ore-tour`) renders it.\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({\n id: 'product-tour',\n steps: [\n { id: 'welcome', title: 'Welcome', description: 'See what changed in this release.' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Find everything', placement: 'bottom-start' },\n { id: 'share', target: '[data-tour=\"share\"]', title: 'Share the board', placement: 'bottom-end' },\n ],\n autoStart: true,\n});\n\n// Readable<T> from @vielzeug/ripple: the listener takes no arguments;\n// read .value inside it.\nconst unsubscribe = tour.current.subscribe(() => {\n const current = tour.current.value;\n if (!current.step) {\n hideCard();\n return;\n }\n renderCard({\n anchor: current.rect, // viewport rect of the target, null for centered steps\n index: current.stepIndex,\n placement: current.placement,\n presentation: current.presentation,\n title: current.step.title,\n total: current.totalSteps,\n });\n});\n\n// Wire your card's controls back to the handle.\ncardEl.addEventListener('next', () => tour.next());\ncardEl.addEventListener('back', () => tour.back());\ncardEl.addEventListener('skip', () => tour.skip());\n\n// On teardown:\nunsubscribe();\ntour.dispose();\n```\n\n`start()` is a no-op when the stored record says this user already completed the tour, so calling it on every page load is safe.\n\n## Steps and Targets\n\nA step without a `target` centers (intro/outro copy). A step with one anchors, and beacon waits for the target to exist before publishing the step — a tour can walk through lazily-mounted routes without any coordination code.\n\n```ts\nconst tour = createTour({\n id: 'deep-tour',\n steps: [\n // Selector: resolved with document.querySelector on activation.\n { id: 'sidebar', target: '[data-tour=\"sidebar\"]', title: 'Your libraries' },\n // Element: a ref your framework already holds.\n { id: 'editor', target: editorEl, title: 'The editor' },\n // Rect: geometry with no element, such as a canvas region.\n { id: 'chart', target: { height: 120, width: 240, x: 400, y: 300 }, title: 'This trend' },\n // Resolver: computed on every activation, and on scroll/resize while the step is active.\n {\n id: 'selection',\n target: () => window.getSelection()?.getRangeAt(0).getBoundingClientRect() ?? null,\n title: 'Your selection',\n },\n ],\n // Give up waiting after 4s and skip the step instead of hanging the tour.\n targetTimeoutMs: 4000,\n});\n```\n\nWith the default `targetTimeoutMs: Infinity`, a step whose target never mounts simply waits: the tour resumes the moment the user navigates to it. Set `0` to publish immediately with a `null` rect instead of waiting.\n\n## Persisting Progress\n\nWithout `storage`, progress lives in memory for the handle's lifetime only. Any object matching `BeaconStorage` makes it durable — values are JSON, keys are namespaced under `@vielzeug/beacon:`.\n\n```ts\nimport type { BeaconStorage } from '@vielzeug/beacon';\n\nconst storage: BeaconStorage = {\n get: (key) => JSON.parse(localStorage.getItem(key) ?? 'null'),\n remove: (key) => localStorage.removeItem(key),\n set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),\n};\n\nconst tour = createTour({ id: 'product-tour', steps, storage });\n```\n\nAsync storage works too: `get` may return a promise, and the tour boots as soon as it resolves. A `set` that rejects is reported through `tap()` as a `warning` event, never thrown.\n\nRecords are validated on read, so a hand-edited or stale record falls back to a fresh tour instead of crashing.\n\n### Re-offering a finished tour\n\nBump `version` when the product changes and every user who finished the old tour becomes eligible again — users mid-tour on the old version keep their progress.\n\n```ts\nconst tour = createTour({\n id: 'product-tour',\n steps: newSteps,\n version: 2, // stored records at version 1 no longer block the tour\n});\n```\n\n`reset()` clears the persisted record for the current user, which is what a \"Replay tour\" or \"Reset onboarding\" control should call before `start()`.\n\n## Driving a Refine Presentation\n\n`@vielzeug/refine` ships `ore-tour` (a dialog with step footer, progress, and focus handling) and `ore-spotlight` (a decorative cutout that dims everything but the target). A beacon handle satisfies `ore-tour`'s `TourController` shape, so one call wires both directions:\n\n```ts\nimport type { OreTourElement } from '@vielzeug/refine/tour';\n\nconst card = document.querySelector<OreTourElement>('#tour-card');\n\nconst tour = createTour({ id: 'product-tour', presentation: 'auto', steps });\n\n// bind() renders `current` into the card's props and routes the card's\n// next/back/skip/finish/dismiss actions back into the handle.\nconst unbind = card.bind(tour);\n\ntour.start();\n\n// On teardown:\nunbind();\ntour.dispose();\n```\n\n`presentation: 'auto'` maps to a popover on wide viewports and a bottom sheet on narrow ones; ore-tour makes that switch itself and freezes the choice while the card is open, so a mid-step resize never rebuilds the card. Beacon keeps `current.rect` fresh on scroll, resize, and layout changes, so the anchored card follows the layout with no app-side listeners.\n\nApps that render their own markup read `current` directly instead (see [Basic Usage](#basic-usage)).\n\n## Coachmarks\n\nA coachmark is one hint anchored to one target, shown the first time the target appears and dismissed permanently after. Use it for the \"explain this button once\" moment a tour would be too heavy for — or as the follow-up a tour hands off to.\n\n```ts\nimport { createCoachmark } from '@vielzeug/beacon';\n\nconst share = createCoachmark({\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n description: 'Send a link that opens straight into this view.',\n storage,\n});\n\n// Render from `current` — the same single-step snapshot a tour publishes.\nshare.current.subscribe(() => console.log(share.current.value.step !== null, share.current.value.rect));\n\n// The target may never appear on this page; show() waits for it.\nshare.show();\n\n// \"Got it\" button:\nshare.dismiss(); // records it as seen; never shows again for this version\n```\n\n`hide()` closes the hint without recording it, so it can appear again later; `dismiss()` is permanent until `reset()` or a `version` bump.\n\n## Events and Analytics\n\n`tap()` observes everything the engine considers notable. It returns an unsubscribe function and accepts an `AbortSignal`, so one controller can tear down every subscription.\n\n```ts\nconst controller = new AbortController();\n\ntour.tap(\n (event) => {\n switch (event.type) {\n case 'step:start':\n analytics.track('tour_step', { id: tour.id, step: event.step.id });\n break;\n case 'tour:complete':\n analytics.track('tour_complete', { id: tour.id, reason: event.reason });\n break;\n case 'target-missing':\n // A step's target never mounted: your selector drifted from the DOM.\n console.warn(event.message);\n break;\n case 'warning':\n console.warn(event.message, event.error);\n break;\n }\n },\n { signal: controller.signal },\n);\n```\n\n`target-missing` is the event to alert on: it means a step was skipped because its target did not appear within `targetTimeoutMs`, which is exactly how stale tours announce themselves.\n\n## Testing\n\nBeacon runs without a rendering layer, so plain DOM tests are enough. The default in-memory storage keeps each handle's progress isolated, and `jsdom`'s `getBoundingClientRect()` returns zero-sized rects, which is fine for step-order assertions.\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\nimport { expect, test } from 'vitest';\n\ntest('walks steps in order and completes', () => {\n const tour = createTour({\n id: 'test-tour',\n steps: [{ id: 'a' }, { id: 'b' }],\n targetTimeoutMs: 0, // publish immediately even without targets\n });\n\n tour.start();\n expect(tour.current.value.step?.id).toBe('a');\n\n tour.next();\n expect(tour.current.value.step?.id).toBe('b');\n\n tour.next(); // past the last step finishes\n expect(tour.status.value).toBe('completed');\n});\n```\n\nFor persistence assertions, pass a `Map`-backed `BeaconStorage` and a second handle with the same `id` to check it resumes where the first stopped.\n\n## Framework Integration\n\nBeacon is framework-neutral: bridge the `Readable` snapshot with whatever primitive your framework already has.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport { createTour } from '@vielzeug/beacon';\n\nfunction useTourState(tour: ReturnType<typeof createTour>) {\n const [current, setCurrent] = useState(tour.current.value);\n useEffect(() => tour.current.subscribe(() => setCurrent(tour.current.value)), [tour]);\n return current;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onScopeDispose, shallowRef } from 'vue';\nimport { createTour } from '@vielzeug/beacon';\n\nconst current = shallowRef(tour.current.value);\nconst unsubscribe = tour.current.subscribe(() => (current.value = tour.current.value));\nonScopeDispose(unsubscribe);\n</script>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n import { readable } from 'svelte/store';\n\n const current = readable(tour.current.value, (set) => {\n set(tour.current.value);\n return tour.current.subscribe(() => set(tour.current.value));\n });\n onDestroy(() => tour.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Refine**: `ore-tour` and `ore-spotlight` are the intended presentation layer; see [Driving a Refine Presentation](#driving-a-refine-presentation).\n- **Orbit**: `current.rect` matches orbit's `Rect` shape, so a custom card positions with `computePosition({ getBoundingClientRect: () => current.rect ?? ZERO_RECT }, floatingEl, middleware)`.\n- **Vault**: any vault store becomes a `BeaconStorage` with a six-line bridge (see the `BeaconStorage` docs in [API Reference](./api.md)).\n- **Ripple**: every handle exposes ripple `Readable`s; `createRipple().isBatchingObservable` semantics apply when you subscribe from effects.\n\n## Best Practices\n\n- Give every tour and coachmark a stable `id` — it is the storage key; treat renames as data migrations.\n- Keep tour configs in their own modules as plain data checked with `satisfies BeaconTourConfig`, so steps stay reviewable data, not component code.\n- Prefer `data-tour=\"...\"` attributes as target selectors: they survive class renames and read as intent.\n- Set a finite `targetTimeoutMs` in production and alert on `target-missing` to catch stale selectors.\n- Call `reset()` before `start()` for replay controls; never delete storage keys by hand.\n- Bump `version` when a tour's meaning changes, not when its copy is typo-fixed.\n- Dispose handles on teardown; `tap()` subscriptions with a shared `AbortSignal` clean up in one call.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Beacon: Examples'\ndescription: Practical examples and recipes for @vielzeug/beacon.\n---\n\n## Examples\n\n- [
|
|
7
|
+
"examples": "---\ntitle: 'Beacon: Examples'\ndescription: Practical examples and recipes for @vielzeug/beacon.\n---\n\n## Examples\n\n- [Guided Tour](./examples/guided-tour.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
10
10
|
{
|
package/data/packages/codex.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: Codex\ndescription: Local MCP access to Vielzeug documentation and package metadata.\npackage: codex\ncategory: AI\nkeywords: [mcp, docs, ai]\nrelated: [refine]\nexports: [loadSnapshot, SnapshotCatalog, createMcpServer, startHttpHost, StdioServerTransport, CatalogError, CodexError]\nenvironments: [node]\n---\n\n<PackageHero package=\"codex\" />\n\n## Why Codex?\n\nCodex exposes current Vielzeug catalog data through MCP without scanning source at request time.\n\n## Installation\n\n```sh\npnpm add @vielzeug/codex\n```\n\n## Quick Start\n\n```sh\nnpx -y @vielzeug/codex\n```\n\n## Features\n\n- `loadSnapshot` validates chunked snapshot metadata.\n- `SnapshotCatalog` loads package content only when requested.\n- `createMcpServer` registers package tools, plus Refine component tools whenever the snapshot carries them.\n- The single entry point publishes TypeScript declarations.\n- `startHttpHost` enforces loopback binding plus localhost Host and Origin validation.\n\n## Documentation\n\n- [Usage](./usage.md)\n- [API](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n## See Also\n\n- [Refine](../refine/) provides component metadata bundled by Codex.\n",
|
|
5
5
|
"api": "---\ntitle: Codex API\ndescription: Snapshot, catalog, MCP server, and local HTTP host APIs.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------ | ------------------------------------------ | -------------- | ------------------------------------- |\n| `loadSnapshot` | Read validated snapshot metadata | Sync | Content chunks load lazily |\n| `validateSnapshot` | Full artifact verification (all chunks) | Sync | Generation/CI use, not normal startup |\n| `SnapshotCatalog` | Query package corpus and Refine components | Sync | Construct from loaded snapshot |\n| `createMcpServer` | MCP adapter factory | Sync | Requires catalog and version |\n| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |\n\n## Package Entry Point\n\n`@vielzeug/codex` is the single entry point: catalog (package docs plus bundled Refine component\nmetadata), snapshot loader, errors, the MCP server factory, the loopback HTTP host, and a\nre-export of `StdioServerTransport`. There is one `Catalog` surface and one server factory.\n\n## Snapshot\n\n### `loadSnapshot`\n\n```ts\nloadSnapshot(directory?: string, options?: { validateContents?: boolean }): LoadedSnapshot;\n```\n\nLoads one snapshot directory: `manifest.json` plus `catalog.json` (eager metadata), an optional\n`refine.json`, and lazily read `packages/<slug>.json` content chunks. `directory` defaults to the\nbundled `data/`. The snapshot layout is fixed by code; the manifest carries `{ schemaVersion, version }`\nonly. `validateContents: true` turns the lazy chunks into an eager cross-checked read.\n\n### `validateSnapshot`\n\n```ts\nvalidateSnapshot(snapshotRoot?: string): void;\n```\n\nRuns `loadSnapshot` with `validateContents: true`. Used by snapshot generation, integration tests,\nand artifact verification; normal startup keeps package chunks lazy.\n\n### `SnapshotCatalog`\n\n```ts\nnew SnapshotCatalog(snapshot: LoadedSnapshot)\n```\n\nProvides package lookup, docs/source/example/signature access, deterministic search, and the\nRefine component lookup (`listComponents()`, `getComponent(tagName)`). Component methods return an\nempty list (and `NOT_FOUND` per tag) when the snapshot carries no Refine metadata. `search()`\nreads content chunks through the same lazy cache as the content getters; there is no separate\nsearch index.\n\n---\n\n## MCP\n\n### `createMcpServer`\n\n```ts\ncreateMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;\n```\n\nRegisters the generic package tools over `Catalog`, plus the `refine-*` component tools when the\ncatalog actually carries Refine metadata; tools that could only answer \"unavailable\" are never\noffered. The root also re-exports `StdioServerTransport` for connecting the server without a\nsecond package import.\n\n## HTTP\n\n### `startHttpHost`\n\n```ts\nstartHttpHost(options: HttpHostOptions): Promise<HttpHost>;\n```\n\nStarts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or\n`::1`; every request must also pass localhost Host and Origin checks. `createServer` must return a\nfresh, unconnected server with its request handlers registered.\n\n## Types\n\n```ts\ninterface SnapshotManifest {\n readonly schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;\n readonly version: string;\n}\n\ninterface LoadedSnapshot {\n readonly catalog: CatalogFile;\n readonly contentDirectory: string;\n readonly manifest: SnapshotManifest;\n readonly refineComponents: readonly CemDeclaration[];\n}\n```\n\n```ts\ninterface CatalogFile {\n readonly packages: readonly PackageMeta[];\n readonly version: string;\n}\n\ninterface PackageMeta {\n readonly availableDocPages: readonly DocPage[];\n readonly category: string;\n readonly description: string;\n readonly exampleIds: readonly string[];\n readonly exports: readonly string[];\n readonly hasSource: boolean;\n readonly keywords: readonly string[];\n readonly name: string;\n readonly related: readonly string[];\n readonly slug: string;\n readonly version: string;\n}\n\ninterface Example {\n readonly code: string;\n readonly id: string;\n readonly name: string;\n}\n```\n\n```ts\ninterface Catalog {\n getComponent(tagName: string): CemDeclaration;\n getDocs(slug: string, page: DocPage): string;\n getExample(slug: string, exampleId: string): Example;\n getPackage(slug: string): PackageMeta;\n getSource(slug: string): string;\n getTypeSignature(slug: string, symbol: string): string;\n listComponents(): readonly CemDeclaration[];\n listExamples(slug: string): readonly Pick<Example, 'id' | 'name'>[];\n listPackages(): readonly PackageMeta[];\n search(query: string): readonly SearchHit[];\n}\n\ninterface SearchHit {\n readonly matchedExamples?: readonly string[];\n readonly matchedIn: readonly ('docs' | 'examples' | 'exports' | 'keywords' | 'metadata' | 'related' | 'source')[];\n readonly matchedPages?: readonly DocPage[];\n readonly name: string;\n readonly slug: string;\n}\n```\n\nCatalog exposes semantic reads. It does not expose its cached content chunks.\n\n```ts\ninterface HttpHost {\n dispose(): Promise<void>;\n readonly disposed: boolean;\n readonly host: string;\n readonly port: number;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\ninterface HttpHostOptions {\n createServer: () => Server;\n host?: '127.0.0.1' | '::1';\n port: number;\n version: string;\n}\n```\n\n```ts\nconst DOC_PAGES = ['index', 'api', 'usage', 'examples'] as const;\ntype DocPage = (typeof DOC_PAGES)[number];\n\nconst SNAPSHOT_SCHEMA_VERSION = 2 as const;\n```\n\n```ts\ninterface CemDeclaration {\n readonly attributes?: readonly CemAttribute[];\n readonly cssParts?: readonly CemCssPart[];\n readonly cssProperties?: readonly CemCssProperty[];\n readonly description?: string;\n readonly events?: readonly CemEvent[];\n readonly members?: readonly CemMember[];\n readonly name?: string;\n readonly slots?: readonly CemSlot[];\n readonly superclass?: { readonly name: string; readonly package?: string };\n readonly tagName?: string;\n readonly [key: string]: unknown;\n}\n\ninterface CemAttribute {\n readonly default?: string;\n readonly description?: string;\n readonly fieldName?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemCssPart {\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemCssProperty {\n readonly default?: string;\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemEvent {\n readonly description?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemMember {\n readonly description?: string;\n readonly kind?: 'field' | 'method';\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemSlot {\n readonly description?: string;\n readonly name: string;\n}\n```\n\nComponent declarations and their nested data use readonly TypeScript types. The loader pins only\nthe contract its consumers depend on: declarations form an array with valid, unique custom-element\n`tagName`s.\n\n## Errors\n\n`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`,\n`NOT_FOUND`, or `UNAVAILABLE` for expected tool failures.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Codex: Usage Guide'\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed` when coordinating shutdown.\n\n## Agent Skill\n\nCodex ships a `vielzeug` agent skill: a `SKILL.md` that tells an AI agent working in _your_ project to discover packages through the MCP tools instead of guessing, to use the owning `@vielzeug/*` package instead of hand-rolling, and to build UI from Refine components, tokens, and theme whenever `@vielzeug/refine` is installed. Install it into the project:\n\n```sh\nnpx -y @vielzeug/codex skills install\nnpx -y @vielzeug/codex skills install --target=.claude/skills\nnpx -y @vielzeug/codex skills install --force # overwrite an existing copy\n```\n\nWithout `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\nbun install\ncd packages/codex\nbun run test:unit\nbun run test:integration\nbun run dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`bun run dev` watches documentation and package inputs, regenerates `.dev/` through a staging swap, and restarts the server against it.\n\n## Debugging\n\n```sh\nbun run dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\n`createMcpServer` also registers the `refine-*` component tools whenever the loaded snapshot carries Refine metadata; there is nothing to opt into.\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Call `check-install` when working inside a project that depends on `@vielzeug/*`: it compares the served snapshot with the versions that project declares and its lockfile resolves, so agents can tell whether snapshot docs may lag the install.\n- Every snapshot is one flat directory (manifest, catalog, content chunks, optional Refine metadata); `--snapshot` points at it directly.\n- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.\n- Return a fresh configured server from `startHttpHost`'s `createServer` factory.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `bun run test:unit` before `bun run test:integration`.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Codex: Usage Guide'\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed` when coordinating shutdown.\n\n## Agent Skill\n\nCodex ships a `vielzeug` agent skill: a `SKILL.md` that tells an AI agent working in _your_ project to discover packages through the MCP tools instead of guessing, to use the owning `@vielzeug/*` package instead of hand-rolling, and to build UI from Refine components, tokens, and theme whenever `@vielzeug/refine` is installed. Install it into the project:\n\n```sh\nnpx -y @vielzeug/codex skills install\nnpx -y @vielzeug/codex skills install --target=.claude/skills\nnpx -y @vielzeug/codex skills install --force # overwrite an existing copy\n```\n\nWithout `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.\n\nThis installs only the **vielzeug consumer** skill (package discovery, Refine lookups). It does **not** install klugzeug workflow skills (`plan`, `build`, `test`, `review`, `docs`, `deliver`, `pipeline`, `onboard`). In the Vielzeug monorepo, workflow procedure lives under `~/.agents/skills/`; repo policy and validation gates live in root `AGENTS.md`.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\nbun install\ncd packages/codex\nbun run test:unit\nbun run test:integration\nbun run dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`bun run dev` watches documentation and package inputs, regenerates `.dev/` through a staging swap, and restarts the server against it.\n\n## Debugging\n\n```sh\nbun run dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\n`createMcpServer` also registers the `refine-*` component tools whenever the loaded snapshot carries Refine metadata; there is nothing to opt into.\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Call `check-install` when working inside a project that depends on `@vielzeug/*`: it compares the served snapshot with the versions that project declares and its lockfile resolves, so agents can tell whether snapshot docs may lag the install.\n- Every snapshot is one flat directory (manifest, catalog, content chunks, optional Refine metadata); `--snapshot` points at it directly.\n- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.\n- Return a fresh configured server from `startHttpHost`'s `createServer` factory.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `bun run test:unit` before `bun run test:integration`.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Codex: Examples'\ndescription: Practical MCP tool-call examples for package discovery, docs lookup, and Refine component queries.\n---\n\n## Examples\n\n- [Listing Packages](./examples/listing-packages.md)\n- [Searching Packages](./examples/searching-packages.md)\n- [Package Metadata](./examples/package-metadata.md)\n- [Reading Docs](./examples/reading-docs.md)\n- [Running REPL Examples](./examples/running-repl-examples.md)\n- [Looking Up Components](./examples/looking-up-components.md)\n- [Inspector](./examples/inspector.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [],
|